Explicit import user32.dll.
[wine] / dlls / shell32 / shell.c
1 /*
2  *                              Shell Library Functions
3  *
4  *  1998 Marcus Meissner
5  */
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <ctype.h>
10 #include "windef.h"
11 #include "wingdi.h"
12 #include "wine/winuser16.h"
13 #include "wine/winbase16.h"
14 #include "wine/shell16.h"
15 #include "winerror.h"
16 #include "file.h"
17 #include "heap.h"
18 #include "ldt.h"
19 #include "module.h"
20 #include "neexe.h"
21 #include "dlgs.h"
22 #include "cursoricon.h"
23 #include "shellapi.h"
24 #include "shlobj.h"
25 #include "debugtools.h"
26 #include "winreg.h"
27 #include "syslevel.h"
28 #include "shlwapi.h"
29 #include "imagelist.h"
30
31 DEFAULT_DEBUG_CHANNEL(shell)
32 DECLARE_DEBUG_CHANNEL(exec)
33
34 /* .ICO file ICONDIR definitions */
35
36 #include "pshpack1.h"
37
38 typedef struct
39 {
40     BYTE        bWidth;          /* Width, in pixels, of the image      */
41     BYTE        bHeight;         /* Height, in pixels, of the image     */
42     BYTE        bColorCount;     /* Number of colors in image (0 if >=8bpp) */
43     BYTE        bReserved;       /* Reserved ( must be 0)               */
44     WORD        wPlanes;         /* Color Planes                        */
45     WORD        wBitCount;       /* Bits per pixel                      */
46     DWORD       dwBytesInRes;    /* How many bytes in this resource?    */
47     DWORD       dwImageOffset;   /* Where in the file is this image?    */
48 } icoICONDIRENTRY, *LPicoICONDIRENTRY;
49
50 typedef struct
51 {
52     WORD            idReserved;   /* Reserved (must be 0)               */
53     WORD            idType;       /* Resource Type (1 for icons)        */
54     WORD            idCount;      /* How many images?                   */
55     icoICONDIRENTRY idEntries[1]; /* An entry for each image (idCount of 'em) */
56 } icoICONDIR, *LPicoICONDIR;
57
58 #include "poppack.h"
59
60 static const char*      lpstrMsgWndCreated = "OTHERWINDOWCREATED";
61 static const char*      lpstrMsgWndDestroyed = "OTHERWINDOWDESTROYED";
62 static const char*      lpstrMsgShellActivate = "ACTIVATESHELLWINDOW";
63
64 static HWND16   SHELL_hWnd = 0;
65 static HHOOK    SHELL_hHook = 0;
66 static UINT16   uMsgWndCreated = 0;
67 static UINT16   uMsgWndDestroyed = 0;
68 static UINT16   uMsgShellActivate = 0;
69 HINSTANCE16     SHELL_hInstance = 0;
70 HINSTANCE SHELL_hInstance32;
71 static int SHELL_Attach = 0;
72
73 /***********************************************************************
74  * SHELL_DllEntryPoint [SHELL.entry]
75  *
76  * Initialization code for shell.dll. Automatically loads the
77  * 32-bit shell32.dll to allow thunking up to 32-bit code.
78  *
79  * RETURNS:
80  */
81 BOOL WINAPI SHELL_DllEntryPoint(DWORD Reason, HINSTANCE16 hInst,
82                                 WORD ds, WORD HeapSize, DWORD res1, WORD res2)
83 {
84     TRACE("(%08lx, %04x, %04x, %04x, %08lx, %04x)\n",
85           Reason, hInst, ds, HeapSize, res1, res2);
86
87     switch(Reason)
88     {
89     case DLL_PROCESS_ATTACH:
90         SHELL_Attach++;
91         if (SHELL_hInstance)
92         {
93             ERR("shell.dll instantiated twice!\n");
94             /*
95              * We should return FALSE here, but that will break
96              * most apps that use CreateProcess because we do
97              * not yet support seperate address-spaces.
98              */
99             return TRUE;
100         }
101
102         SHELL_hInstance = hInst;
103         if(!SHELL_hInstance32)
104         {
105             if(!(SHELL_hInstance32 = LoadLibraryA("shell32.dll")))
106             {
107                 ERR("Could not load sibling shell32.dll\n");
108                 return FALSE;
109             }
110         }
111         break;
112
113     case DLL_PROCESS_DETACH:
114         if(!--SHELL_Attach)
115         {
116             SHELL_hInstance = 0;
117             if(SHELL_hInstance32)
118                 FreeLibrary(SHELL_hInstance32);
119         }
120         break;
121     }
122     return TRUE;
123 }
124
125 /*************************************************************************
126  *                              DragAcceptFiles16               [SHELL.9]
127  */
128 void WINAPI DragAcceptFiles16(HWND16 hWnd, BOOL16 b)
129 {
130   DragAcceptFiles(hWnd, b);
131 }
132
133 /*************************************************************************
134  *                              DragQueryFile16         [SHELL.11]
135  */
136 UINT16 WINAPI DragQueryFile16(
137         HDROP16 hDrop,
138         WORD wFile,
139         LPSTR lpszFile,
140         WORD wLength)
141 {
142         LPSTR lpDrop;
143         UINT i = 0;
144         LPDROPFILESTRUCT16 lpDropFileStruct = (LPDROPFILESTRUCT16) GlobalLock16(hDrop); 
145    
146         TRACE("(%04x, %x, %p, %u)\n", hDrop,wFile,lpszFile,wLength);
147     
148         if(!lpDropFileStruct) goto end;
149     
150         lpDrop = (LPSTR) lpDropFileStruct + lpDropFileStruct->wSize;
151         wFile = (wFile==0xffff) ? 0xffffffff : wFile;
152
153         while (i++ < wFile)
154         {
155           while (*lpDrop++); /* skip filename */
156           if (!*lpDrop) 
157           {
158             i = (wFile == 0xFFFFFFFF) ? i : 0; 
159             goto end;
160           }
161         }
162     
163         i = lstrlenA(lpDrop);
164         i++;
165         if (!lpszFile ) goto end;   /* needed buffer size */
166         i = (wLength > i) ? i : wLength;
167         lstrcpynA (lpszFile,  lpDrop,  i);
168 end:
169         GlobalUnlock16(hDrop);
170         return i;
171 }
172
173 /*************************************************************************
174  *                              DragFinish16            [SHELL.12]
175  */
176 void WINAPI DragFinish16(HDROP16 h)
177 {
178     TRACE("\n");
179     GlobalFree16((HGLOBAL16)h);
180 }
181
182
183 /*************************************************************************
184  *                              DragQueryPoint16                [SHELL.13]
185  */
186 BOOL16 WINAPI DragQueryPoint16(HDROP16 hDrop, POINT16 *p)
187 {
188   LPDROPFILESTRUCT16 lpDropFileStruct;  
189   BOOL16           bRet;
190   TRACE("\n");
191   lpDropFileStruct = (LPDROPFILESTRUCT16) GlobalLock16(hDrop);
192   
193   memcpy(p,&lpDropFileStruct->ptMousePos,sizeof(POINT16));
194   bRet = lpDropFileStruct->fInNonClientArea;
195   
196   GlobalUnlock16(hDrop);
197   return bRet;
198 }
199
200 /*************************************************************************
201  *      SHELL_FindExecutable [Internal]
202  *
203  * Utility for code sharing between FindExecutable and ShellExecute
204  */
205 HINSTANCE SHELL_FindExecutable( LPCSTR lpFile, 
206                                          LPCSTR lpOperation,
207                                          LPSTR lpResult)
208 { char *extension = NULL; /* pointer to file extension */
209     char tmpext[5];         /* local copy to mung as we please */
210     char filetype[256];     /* registry name for this filetype */
211     LONG filetypelen=256;   /* length of above */
212     char command[256];      /* command from registry */
213     LONG commandlen=256;    /* This is the most DOS can handle :) */
214     char buffer[256];       /* Used to GetProfileString */
215     HINSTANCE retval=31;  /* default - 'No association was found' */
216     char *tok;              /* token pointer */
217     int i;                  /* random counter */
218     char xlpFile[256] = ""; /* result of SearchPath */
219
220   TRACE("%s\n", (lpFile != NULL?lpFile:"-") );
221
222     lpResult[0]='\0'; /* Start off with an empty return string */
223
224     /* trap NULL parameters on entry */
225     if (( lpFile == NULL ) || ( lpResult == NULL ) || ( lpOperation == NULL ))
226   { WARN_(exec)("(lpFile=%s,lpResult=%s,lpOperation=%s): NULL parameter\n",
227            lpFile, lpOperation, lpResult);
228         return 2; /* File not found. Close enough, I guess. */
229     }
230
231     if (SearchPathA( NULL, lpFile,".exe",sizeof(xlpFile),xlpFile,NULL))
232   { TRACE("SearchPathA returned non-zero\n");
233         lpFile = xlpFile;
234     }
235
236     /* First thing we need is the file's extension */
237     extension = strrchr( xlpFile, '.' ); /* Assume last "." is the one; */
238                                         /* File->Run in progman uses */
239                                         /* .\FILE.EXE :( */
240   TRACE("xlpFile=%s,extension=%s\n", xlpFile, extension);
241
242     if ((extension == NULL) || (extension == &xlpFile[strlen(xlpFile)]))
243   { WARN("Returning 31 - No association\n");
244         return 31; /* no association */
245     }
246
247     /* Make local copy & lowercase it for reg & 'programs=' lookup */
248     lstrcpynA( tmpext, extension, 5 );
249     CharLowerA( tmpext );
250   TRACE("%s file\n", tmpext);
251     
252     /* Three places to check: */
253     /* 1. win.ini, [windows], programs (NB no leading '.') */
254     /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
255     /* 3. win.ini, [extensions], extension (NB no leading '.' */
256     /* All I know of the order is that registry is checked before */
257     /* extensions; however, it'd make sense to check the programs */
258     /* section first, so that's what happens here. */
259
260     /* See if it's a program - if GetProfileString fails, we skip this
261      * section. Actually, if GetProfileString fails, we've probably
262      * got a lot more to worry about than running a program... */
263     if ( GetProfileStringA("windows", "programs", "exe pif bat com",
264                                                   buffer, sizeof(buffer)) > 0 )
265   { for (i=0;i<strlen(buffer); i++) buffer[i]=tolower(buffer[i]);
266
267                 tok = strtok(buffer, " \t"); /* ? */
268                 while( tok!= NULL)
269                   {
270                         if (strcmp(tok, &tmpext[1])==0) /* have to skip the leading "." */
271                           {
272                                 strcpy(lpResult, xlpFile);
273                                 /* Need to perhaps check that the file has a path
274                                  * attached */
275         TRACE("found %s\n", lpResult);
276         return 33;
277
278                 /* Greater than 32 to indicate success FIXME According to the
279                  * docs, I should be returning a handle for the
280                  * executable. Does this mean I'm supposed to open the
281                  * executable file or something? More RTFM, I guess... */
282                           }
283                         tok=strtok(NULL, " \t");
284                   }
285           }
286
287     /* Check registry */
288     if (RegQueryValue16( HKEY_CLASSES_ROOT, tmpext, filetype,
289                          &filetypelen ) == ERROR_SUCCESS )
290     {
291         filetype[filetypelen]='\0';
292         TRACE("File type: %s\n", filetype);
293
294         /* Looking for ...buffer\shell\lpOperation\command */
295         strcat( filetype, "\\shell\\" );
296         strcat( filetype, lpOperation );
297         strcat( filetype, "\\command" );
298         
299         if (RegQueryValue16( HKEY_CLASSES_ROOT, filetype, command,
300                              &commandlen ) == ERROR_SUCCESS )
301         {
302             LPSTR tmp;
303             char param[256];
304             LONG paramlen = 256;
305
306
307             /* Get the parameters needed by the application 
308                from the associated ddeexec key */ 
309             tmp = strstr(filetype,"command");
310             tmp[0] = '\0';
311             strcat(filetype,"ddeexec");
312
313             if(RegQueryValue16( HKEY_CLASSES_ROOT, filetype, param,&paramlen ) == ERROR_SUCCESS)
314             {
315               strcat(command," ");
316               strcat(command,param);
317               commandlen += paramlen;
318             }
319
320             /* Is there a replace() function anywhere? */
321             command[commandlen]='\0';
322             strcpy( lpResult, command );
323             tok=strstr( lpResult, "%1" );
324             if (tok != NULL)
325             {
326                 tok[0]='\0'; /* truncate string at the percent */
327                 strcat( lpResult, xlpFile ); /* what if no dir in xlpFile? */
328                 tok=strstr( command, "%1" );
329                 if ((tok!=NULL) && (strlen(tok)>2))
330                 {
331                     strcat( lpResult, &tok[2] );
332                 }
333             }
334             retval=33; /* FIXME see above */
335         }
336     }
337     else /* Check win.ini */
338     {
339         /* Toss the leading dot */
340         extension++;
341         if ( GetProfileStringA( "extensions", extension, "", command,
342                                   sizeof(command)) > 0)
343           {
344                 if (strlen(command)!=0)
345                   {
346                         strcpy( lpResult, command );
347                         tok=strstr( lpResult, "^" ); /* should be ^.extension? */
348                         if (tok != NULL)
349                           {
350                                 tok[0]='\0';
351                                 strcat( lpResult, xlpFile ); /* what if no dir in xlpFile? */
352                                 tok=strstr( command, "^" ); /* see above */
353                                 if ((tok != NULL) && (strlen(tok)>5))
354                                   {
355                                         strcat( lpResult, &tok[5]);
356                                   }
357                           }
358                         retval=33; /* FIXME - see above */
359                   }
360           }
361         }
362
363     TRACE("returning %s\n", lpResult);
364     return retval;
365 }
366
367 /*************************************************************************
368  *                              ShellExecute16          [SHELL.20]
369  */
370 HINSTANCE16 WINAPI ShellExecute16( HWND16 hWnd, LPCSTR lpOperation,
371                                    LPCSTR lpFile, LPCSTR lpParameters,
372                                    LPCSTR lpDirectory, INT16 iShowCmd )
373 {   HINSTANCE16 retval=31;
374     char old_dir[1024];
375     char cmd[1024] = "";
376
377     TRACE("(%04x,'%s','%s','%s','%s',%x)\n",
378                 hWnd, lpOperation ? lpOperation:"<null>", lpFile ? lpFile:"<null>",
379                 lpParameters ? lpParameters : "<null>", 
380                 lpDirectory ? lpDirectory : "<null>", iShowCmd);
381
382     if (lpFile==NULL) return 0; /* should not happen */
383     if (lpOperation==NULL) /* default is open */
384       lpOperation="open";
385
386     if (lpDirectory)
387     { GetCurrentDirectoryA( sizeof(old_dir), old_dir );
388         SetCurrentDirectoryA( lpDirectory );
389     }
390
391     /* First try to execute lpFile with lpParameters directly */ 
392     strcpy(cmd,lpFile);
393     strcat(cmd,lpParameters ? lpParameters : "");
394
395     SYSLEVEL_ReleaseWin16Lock();
396     retval = WinExec( cmd, iShowCmd );
397     SYSLEVEL_RestoreWin16Lock();
398
399     /* Unable to execute lpFile directly
400        Check if we can match an application to lpFile */
401     if(retval < 31)
402     { 
403       cmd[0] = '\0';
404       retval = SHELL_FindExecutable( lpFile, lpOperation, cmd );
405
406       if (retval > 32)  /* Found */
407       {
408         if (lpParameters)
409         {
410             strcat(cmd," ");
411             strcat(cmd,lpParameters);
412         }
413         SYSLEVEL_ReleaseWin16Lock();
414         retval = WinExec( cmd, iShowCmd );
415         SYSLEVEL_RestoreWin16Lock();
416       }
417       else if(PathIsURLA((LPSTR)lpFile))    /* File not found, check for URL */
418       {
419         char lpstrProtocol[256];
420         LONG cmdlen = 512;
421         LPSTR lpstrRes;
422         INT iSize;
423       
424         lpstrRes = strchr(lpFile,':');
425         iSize = lpstrRes - lpFile;
426         
427         /* Looking for ...protocol\shell\lpOperation\command */
428         strncpy(lpstrProtocol,lpFile,iSize);
429         lpstrProtocol[iSize]='\0';
430         strcat( lpstrProtocol, "\\shell\\" );
431         strcat( lpstrProtocol, lpOperation );
432         strcat( lpstrProtocol, "\\command" );
433         
434         /* Remove File Protocol from lpFile */
435         /* In the case file://path/file     */
436         if(!strncasecmp(lpFile,"file",iSize))
437         {
438           lpFile += iSize;
439           while(*lpFile == ':') lpFile++;
440         }
441         
442
443         /* Get the application for the protocol and execute it */
444         if (RegQueryValue16( HKEY_CLASSES_ROOT, lpstrProtocol, cmd,
445                              &cmdlen ) == ERROR_SUCCESS )
446         {
447             LPSTR tok;
448             LPSTR tmp;
449             char param[256] = "";
450             LONG paramlen = 256;
451
452             /* Get the parameters needed by the application 
453                from the associated ddeexec key */ 
454             tmp = strstr(lpstrProtocol,"command");
455             tmp[0] = '\0';
456             strcat(lpstrProtocol,"ddeexec");
457
458             if(RegQueryValue16( HKEY_CLASSES_ROOT, lpstrProtocol, param,&paramlen ) == ERROR_SUCCESS)
459             {
460               strcat(cmd," ");
461               strcat(cmd,param);
462               cmdlen += paramlen;
463             }
464             
465             /* Is there a replace() function anywhere? */
466             cmd[cmdlen]='\0';
467
468             tok=strstr( cmd, "%1" );
469             if (tok != NULL)
470             {
471                 tok[0]='\0'; /* truncate string at the percent */
472                 strcat( cmd, lpFile ); /* what if no dir in xlpFile? */
473                 tok=strstr( cmd, "%1" );
474                 if ((tok!=NULL) && (strlen(tok)>2))
475                 {
476                     strcat( cmd, &tok[2] );
477                 }
478             }
479  
480             SYSLEVEL_ReleaseWin16Lock();
481             retval = WinExec( cmd, iShowCmd );
482             SYSLEVEL_RestoreWin16Lock();
483         }
484       }
485     /* Check if file specified is in the form www.??????.*** */
486       else if(!strncasecmp(lpFile,"www",3))
487       {
488         /* if so, append lpFile http:// and call ShellExecute */ 
489         char lpstrTmpFile[256] = "http://" ;
490         strcat(lpstrTmpFile,lpFile);
491         retval = ShellExecuteA(hWnd,lpOperation,lpstrTmpFile,NULL,NULL,0);
492       }
493     }
494     if (lpDirectory)
495       SetCurrentDirectoryA( old_dir );
496     return retval;
497 }
498
499 /*************************************************************************
500  *             FindExecutable16   (SHELL.21)
501  */
502 HINSTANCE16 WINAPI FindExecutable16( LPCSTR lpFile, LPCSTR lpDirectory,
503                                      LPSTR lpResult )
504 { return (HINSTANCE16)FindExecutableA( lpFile, lpDirectory, lpResult );
505 }
506
507
508 /*************************************************************************
509  *             AboutDlgProc16   (SHELL.33)
510  */
511 BOOL16 WINAPI AboutDlgProc16( HWND16 hWnd, UINT16 msg, WPARAM16 wParam,
512                                LPARAM lParam )
513 { return AboutDlgProc( hWnd, msg, wParam, lParam );
514 }
515
516
517 /*************************************************************************
518  *             ShellAbout16   (SHELL.22)
519  */
520 BOOL16 WINAPI ShellAbout16( HWND16 hWnd, LPCSTR szApp, LPCSTR szOtherStuff,
521                             HICON16 hIcon )
522 { return ShellAboutA( hWnd, szApp, szOtherStuff, hIcon );
523 }
524
525 /*************************************************************************
526  *                              SHELL_GetResourceTable
527  */
528 static DWORD SHELL_GetResourceTable(HFILE hFile,LPBYTE *retptr)
529 {       IMAGE_DOS_HEADER        mz_header;
530         char                    magic[4];
531         int                     size;
532
533         TRACE("\n");  
534
535         *retptr = NULL;
536         _llseek( hFile, 0, SEEK_SET );
537         if ((_lread(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) || (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
538         { /* .ICO file ? */
539           if (mz_header.e_cblp == 1) 
540           { /* ICONHEADER.idType, must be 1 */
541             *retptr = (LPBYTE)-1;
542             return 1;
543           }
544           else
545             return 0; /* failed */
546         }
547         _llseek( hFile, mz_header.e_lfanew, SEEK_SET );
548
549         if (_lread( hFile, magic, sizeof(magic) ) != sizeof(magic))
550           return 0;
551
552         _llseek( hFile, mz_header.e_lfanew, SEEK_SET);
553
554         if (*(DWORD*)magic  == IMAGE_NT_SIGNATURE)
555           return IMAGE_NT_SIGNATURE;
556
557         if (*(WORD*)magic == IMAGE_OS2_SIGNATURE)
558         { IMAGE_OS2_HEADER      ne_header;
559           LPBYTE                pTypeInfo = (LPBYTE)-1;
560
561           if (_lread(hFile,&ne_header,sizeof(ne_header))!=sizeof(ne_header))
562             return 0;
563
564           if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE)
565             return 0;
566
567           size = ne_header.ne_restab - ne_header.ne_rsrctab;
568
569           if( size > sizeof(NE_TYPEINFO) )
570           { pTypeInfo = (BYTE*)HeapAlloc( GetProcessHeap(), 0, size);
571             if( pTypeInfo ) 
572             { _llseek(hFile, mz_header.e_lfanew+ne_header.ne_rsrctab, SEEK_SET);
573               if( _lread( hFile, (char*)pTypeInfo, size) != size )
574               { HeapFree( GetProcessHeap(), 0, pTypeInfo); 
575                 pTypeInfo = NULL;
576               }
577             }
578           }
579           *retptr = pTypeInfo;
580           return IMAGE_OS2_SIGNATURE;
581         }
582         return 0; /* failed */
583 }
584
585 /*************************************************************************
586  *                      SHELL_LoadResource
587  */
588 static HGLOBAL16 SHELL_LoadResource(HINSTANCE16 hInst, HFILE hFile, NE_NAMEINFO* pNInfo, WORD sizeShift)
589 {       BYTE*  ptr;
590         HGLOBAL16 handle = DirectResAlloc16( hInst, 0x10, (DWORD)pNInfo->length << sizeShift);
591
592         TRACE("\n");
593
594         if( (ptr = (BYTE*)GlobalLock16( handle )) )
595         { _llseek( hFile, (DWORD)pNInfo->offset << sizeShift, SEEK_SET);
596           _lread( hFile, (char*)ptr, pNInfo->length << sizeShift);
597           return handle;
598         }
599         return 0;
600 }
601
602 /*************************************************************************
603  *                      ICO_LoadIcon
604  */
605 static HGLOBAL16 ICO_LoadIcon(HINSTANCE16 hInst, HFILE hFile, LPicoICONDIRENTRY lpiIDE)
606 {       BYTE*  ptr;
607         HGLOBAL16 handle = DirectResAlloc16( hInst, 0x10, lpiIDE->dwBytesInRes);
608         TRACE("\n");
609         if( (ptr = (BYTE*)GlobalLock16( handle )) )
610         { _llseek( hFile, lpiIDE->dwImageOffset, SEEK_SET);
611           _lread( hFile, (char*)ptr, lpiIDE->dwBytesInRes);
612           return handle;
613         }
614         return 0;
615 }
616
617 /*************************************************************************
618  *                      ICO_GetIconDirectory
619  *
620  *  Read .ico file and build phony ICONDIR struct for GetIconID
621  */
622 static HGLOBAL16 ICO_GetIconDirectory(HINSTANCE16 hInst, HFILE hFile, LPicoICONDIR* lplpiID ) 
623 { WORD    id[3];  /* idReserved, idType, idCount */
624   LPicoICONDIR  lpiID;
625   int           i;
626  
627   TRACE("\n"); 
628   _llseek( hFile, 0, SEEK_SET );
629   if( _lread(hFile,(char*)id,sizeof(id)) != sizeof(id) ) return 0;
630
631   /* check .ICO header 
632    *
633    * - see http://www.microsoft.com/win32dev/ui/icons.htm
634    */
635
636   if( id[0] || id[1] != 1 || !id[2] ) return 0;
637
638   i = id[2]*sizeof(icoICONDIRENTRY) ;
639
640   lpiID = (LPicoICONDIR)HeapAlloc( GetProcessHeap(), 0, i + sizeof(id));
641
642   if( _lread(hFile,(char*)lpiID->idEntries,i) == i )
643   { HGLOBAL16 handle = DirectResAlloc16( hInst, 0x10,
644                                      id[2]*sizeof(CURSORICONDIRENTRY) + sizeof(id) );
645      if( handle ) 
646     { CURSORICONDIR*     lpID = (CURSORICONDIR*)GlobalLock16( handle );
647        lpID->idReserved = lpiID->idReserved = id[0];
648        lpID->idType = lpiID->idType = id[1];
649        lpID->idCount = lpiID->idCount = id[2];
650        for( i=0; i < lpiID->idCount; i++ )
651       { memcpy((void*)(lpID->idEntries + i), 
652                    (void*)(lpiID->idEntries + i), sizeof(CURSORICONDIRENTRY) - 2);
653             lpID->idEntries[i].wResId = i;
654          }
655       *lplpiID = lpiID;
656        return handle;
657      }
658   }
659   /* fail */
660
661   HeapFree( GetProcessHeap(), 0, lpiID);
662   return 0;
663 }
664
665 /*************************************************************************
666  *                      InternalExtractIcon             [SHELL.39]
667  *
668  * This abortion is called directly by Progman
669  */
670 HGLOBAL16 WINAPI InternalExtractIcon16(HINSTANCE16 hInstance,
671                                      LPCSTR lpszExeFileName, UINT16 nIconIndex, WORD n )
672 {       HGLOBAL16       hRet = 0;
673         HGLOBAL16*      RetPtr = NULL;
674         LPBYTE          pData;
675         OFSTRUCT        ofs;
676         DWORD           sig;
677         HFILE           hFile = OpenFile( lpszExeFileName, &ofs, OF_READ );
678         UINT16          iconDirCount = 0,iconCount = 0;
679         LPBYTE          peimage;
680         HANDLE  fmapping;
681         
682         TRACE("(%04x,file %s,start %d,extract %d\n", 
683                        hInstance, lpszExeFileName, nIconIndex, n);
684
685         if( hFile == HFILE_ERROR || !n )
686           return 0;
687
688         hRet = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(HICON16)*n);
689         RetPtr = (HICON16*)GlobalLock16(hRet);
690
691         *RetPtr = (n == 0xFFFF)? 0: 1;  /* error return values */
692
693         sig = SHELL_GetResourceTable(hFile,&pData);
694
695         if( sig==IMAGE_OS2_SIGNATURE || sig==1 ) /* .ICO file */
696         { HICON16        hIcon = 0;
697           NE_TYPEINFO* pTInfo = (NE_TYPEINFO*)(pData + 2);
698           NE_NAMEINFO* pIconStorage = NULL;
699           NE_NAMEINFO* pIconDir = NULL;
700           LPicoICONDIR lpiID = NULL;
701  
702           if( pData == (BYTE*)-1 )
703           { hIcon = ICO_GetIconDirectory(hInstance, hFile, &lpiID);     /* check for .ICO file */
704             if( hIcon ) 
705             { iconDirCount = 1; iconCount = lpiID->idCount; 
706             }
707           }
708           else while( pTInfo->type_id && !(pIconStorage && pIconDir) )
709           { if( pTInfo->type_id == NE_RSCTYPE_GROUP_ICON )      /* find icon directory and icon repository */
710             { iconDirCount = pTInfo->count;
711               pIconDir = ((NE_NAMEINFO*)(pTInfo + 1));
712               TRACE("\tfound directory - %i icon families\n", iconDirCount);
713             }
714             if( pTInfo->type_id == NE_RSCTYPE_ICON ) 
715             { iconCount = pTInfo->count;
716               pIconStorage = ((NE_NAMEINFO*)(pTInfo + 1));
717               TRACE("\ttotal icons - %i\n", iconCount);
718             }
719             pTInfo = (NE_TYPEINFO *)((char*)(pTInfo+1)+pTInfo->count*sizeof(NE_NAMEINFO));
720           }
721
722           /* load resources and create icons */
723
724           if( (pIconStorage && pIconDir) || lpiID )
725           { if( nIconIndex == (UINT16)-1 )
726             { RetPtr[0] = iconDirCount;
727             }
728             else if( nIconIndex < iconDirCount )
729             { UINT16   i, icon;
730               if( n > iconDirCount - nIconIndex ) 
731                 n = iconDirCount - nIconIndex;
732
733               for( i = nIconIndex; i < nIconIndex + n; i++ ) 
734               { /* .ICO files have only one icon directory */
735
736                 if( lpiID == NULL )
737                   hIcon = SHELL_LoadResource( hInstance, hFile, pIconDir + i, *(WORD*)pData );
738                 RetPtr[i-nIconIndex] = GetIconID16( hIcon, 3 );
739                 GlobalFree16(hIcon); 
740               }
741
742               for( icon = nIconIndex; icon < nIconIndex + n; icon++ )
743               { hIcon = 0;
744                 if( lpiID )
745                 { hIcon = ICO_LoadIcon( hInstance, hFile, lpiID->idEntries + RetPtr[icon-nIconIndex]);
746                 }
747                 else
748                 { for( i = 0; i < iconCount; i++ )
749                   { if( pIconStorage[i].id == (RetPtr[icon-nIconIndex] | 0x8000) )
750                     { hIcon = SHELL_LoadResource( hInstance, hFile, pIconStorage + i,*(WORD*)pData );
751                     }
752                   }
753                 }
754                 if( hIcon )
755                 { RetPtr[icon-nIconIndex] = LoadIconHandler16( hIcon, TRUE ); 
756                   FarSetOwner16( RetPtr[icon-nIconIndex], GetExePtr(hInstance) );
757                 }
758                 else
759                 { RetPtr[icon-nIconIndex] = 0;
760                 }
761               }
762             }
763           }
764           if( lpiID ) 
765             HeapFree( GetProcessHeap(), 0, lpiID);
766           else 
767             HeapFree( GetProcessHeap(), 0, pData);
768         } 
769
770         if( sig == IMAGE_NT_SIGNATURE)
771         { LPBYTE                idata,igdata;
772           PIMAGE_DOS_HEADER     dheader;
773           PIMAGE_NT_HEADERS     pe_header;
774           PIMAGE_SECTION_HEADER pe_sections;
775           PIMAGE_RESOURCE_DIRECTORY     rootresdir,iconresdir,icongroupresdir;
776           PIMAGE_RESOURCE_DATA_ENTRY    idataent,igdataent;
777           int                   i,j;
778           PIMAGE_RESOURCE_DIRECTORY_ENTRY       xresent;
779           CURSORICONDIR         **cids;
780         
781           fmapping = CreateFileMappingA(hFile,NULL,PAGE_READONLY|SEC_COMMIT,0,0,NULL);
782           if (fmapping == 0) 
783           { /* FIXME, INVALID_HANDLE_VALUE? */
784             WARN("failed to create filemap.\n");
785             hRet = 0;
786             goto end_2; /* failure */
787           }
788           peimage = MapViewOfFile(fmapping,FILE_MAP_READ,0,0,0);
789           if (!peimage) 
790           { WARN("failed to mmap filemap.\n");
791             hRet = 0;
792             goto end_2; /* failure */
793           }
794           dheader = (PIMAGE_DOS_HEADER)peimage;
795
796           /* it is a pe header, SHELL_GetResourceTable checked that */
797           pe_header = (PIMAGE_NT_HEADERS)(peimage+dheader->e_lfanew);
798
799           /* probably makes problems with short PE headers... but I haven't seen 
800           * one yet... 
801           */
802           pe_sections = (PIMAGE_SECTION_HEADER)(((char*)pe_header)+sizeof(*pe_header));
803           rootresdir = NULL;
804
805           for (i=0;i<pe_header->FileHeader.NumberOfSections;i++) 
806           { if (pe_sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
807               continue;
808             /* FIXME: doesn't work when the resources are not in a seperate section */
809             if (pe_sections[i].VirtualAddress == pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress) 
810             { rootresdir = (PIMAGE_RESOURCE_DIRECTORY)((char*)peimage+pe_sections[i].PointerToRawData);
811               break;
812             }
813           }
814
815           if (!rootresdir) 
816           { WARN("haven't found section for resource directory.\n");
817             goto end_4; /* failure */
818           }
819
820           icongroupresdir = GetResDirEntryW(rootresdir,RT_GROUP_ICONW, (DWORD)rootresdir,FALSE);
821
822           if (!icongroupresdir) 
823           { WARN("No Icongroupresourcedirectory!\n");
824             goto end_4; /* failure */
825           }
826
827           iconDirCount = icongroupresdir->NumberOfNamedEntries+icongroupresdir->NumberOfIdEntries;
828
829           if( nIconIndex == (UINT16)-1 ) 
830           { RetPtr[0] = iconDirCount;
831             goto end_3; /* success */
832           }
833
834           if (nIconIndex >= iconDirCount) 
835           { WARN("nIconIndex %d is larger than iconDirCount %d\n",nIconIndex,iconDirCount);
836             GlobalFree16(hRet);
837             goto end_4; /* failure */
838           }
839
840           cids = (CURSORICONDIR**)HeapAlloc(GetProcessHeap(),0,n*sizeof(CURSORICONDIR*));
841                 
842           /* caller just wanted the number of entries */
843           xresent = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(icongroupresdir+1);
844
845           /* assure we don't get too much ... */
846           if( n > iconDirCount - nIconIndex ) 
847           { n = iconDirCount - nIconIndex;
848           }
849
850           /* starting from specified index ... */
851           xresent = xresent+nIconIndex;
852
853           for (i=0;i<n;i++,xresent++) 
854           { CURSORICONDIR       *cid;
855             PIMAGE_RESOURCE_DIRECTORY   resdir;
856
857             /* go down this resource entry, name */
858             resdir = (PIMAGE_RESOURCE_DIRECTORY)((DWORD)rootresdir+(xresent->u2.s.OffsetToDirectory));
859
860             /* default language (0) */
861             resdir = GetResDirEntryW(resdir,(LPWSTR)0,(DWORD)rootresdir,TRUE);
862             igdataent = (PIMAGE_RESOURCE_DATA_ENTRY)resdir;
863
864             /* lookup address in mapped image for virtual address */
865             igdata = NULL;
866
867             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++) 
868             { if (igdataent->OffsetToData < pe_sections[j].VirtualAddress)
869                 continue;
870               if (igdataent->OffsetToData+igdataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
871                 continue;
872               igdata = peimage+(igdataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
873             }
874
875             if (!igdata) 
876             { WARN("no matching real address for icongroup!\n");
877               goto end_4;       /* failure */
878             }
879             /* found */
880             cid = (CURSORICONDIR*)igdata;
881             cids[i] = cid;
882             RetPtr[i] = LookupIconIdFromDirectoryEx(igdata,TRUE,GetSystemMetrics(SM_CXICON),GetSystemMetrics(SM_CYICON),0);
883           }
884
885           iconresdir=GetResDirEntryW(rootresdir,RT_ICONW,(DWORD)rootresdir,FALSE);
886
887           if (!iconresdir) 
888           { WARN("No Iconresourcedirectory!\n");
889             goto end_4; /* failure */
890           }
891
892           for (i=0;i<n;i++) 
893           { PIMAGE_RESOURCE_DIRECTORY   xresdir;
894             xresdir = GetResDirEntryW(iconresdir,(LPWSTR)(DWORD)RetPtr[i],(DWORD)rootresdir,FALSE);
895             xresdir = GetResDirEntryW(xresdir,(LPWSTR)0,(DWORD)rootresdir,TRUE);
896             idataent = (PIMAGE_RESOURCE_DATA_ENTRY)xresdir;
897             idata = NULL;
898
899             /* map virtual to address in image */
900             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++) 
901             { if (idataent->OffsetToData < pe_sections[j].VirtualAddress)
902                 continue;
903               if (idataent->OffsetToData+idataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
904                 continue;
905               idata = peimage+(idataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
906             }
907             if (!idata) 
908             { WARN("no matching real address found for icondata!\n");
909               RetPtr[i]=0;
910               continue;
911             }
912             RetPtr[i] = CreateIconFromResourceEx(idata,idataent->Size,TRUE,0x00030000,GetSystemMetrics(SM_CXICON),GetSystemMetrics(SM_CYICON),0);
913           }
914           goto end_3;   /* sucess */
915         }
916         goto end_1;     /* return array with icon handles */
917
918 /* cleaning up (try & catch would be nicer) */
919 end_4:  hRet = 0;       /* failure */
920 end_3:  UnmapViewOfFile(peimage);       /* success */
921 end_2:  CloseHandle(fmapping);
922 end_1:  _lclose( hFile);
923         return hRet;
924 }
925
926 /*************************************************************************
927  *             ExtractIcon16   (SHELL.34)
928  */
929 HICON16 WINAPI ExtractIcon16( HINSTANCE16 hInstance, LPCSTR lpszExeFileName,
930         UINT16 nIconIndex )
931 {   TRACE("\n");
932     return ExtractIconA( hInstance, lpszExeFileName, nIconIndex );
933 }
934
935 /*************************************************************************
936  *             ExtractIconEx16   (SHELL.40)
937  */
938 HICON16 WINAPI ExtractIconEx16(
939         LPCSTR lpszFile, INT16 nIconIndex, HICON16 *phiconLarge,
940         HICON16 *phiconSmall, UINT16 nIcons
941 ) {
942     HICON       *ilarge,*ismall;
943     UINT16      ret;
944     int         i;
945
946     if (phiconLarge)
947         ilarge = (HICON*)HeapAlloc(GetProcessHeap(),0,nIcons*sizeof(HICON));
948     else
949         ilarge = NULL;
950     if (phiconSmall)
951         ismall = (HICON*)HeapAlloc(GetProcessHeap(),0,nIcons*sizeof(HICON));
952     else
953         ismall = NULL;
954     ret = ExtractIconExA(lpszFile,nIconIndex,ilarge,ismall,nIcons);
955     if (ilarge) {
956         for (i=0;i<nIcons;i++)
957             phiconLarge[i]=ilarge[i];
958         HeapFree(GetProcessHeap(),0,ilarge);
959     }
960     if (ismall) {
961         for (i=0;i<nIcons;i++)
962             phiconSmall[i]=ismall[i];
963         HeapFree(GetProcessHeap(),0,ismall);
964     }
965     return ret;
966 }
967
968 /*************************************************************************
969  *                              ExtractAssociatedIconA
970  * 
971  * Return icon for given file (either from file itself or from associated
972  * executable) and patch parameters if needed.
973  */
974 HICON WINAPI ExtractAssociatedIconA(HINSTANCE hInst, LPSTR lpIconPath, LPWORD lpiIcon)
975 {       TRACE("\n");
976         return ExtractAssociatedIcon16(hInst,lpIconPath,lpiIcon);
977 }
978
979 /*************************************************************************
980  *                              ExtractAssociatedIcon   [SHELL.36]
981  * 
982  * Return icon for given file (either from file itself or from associated
983  * executable) and patch parameters if needed.
984  */
985 HICON16 WINAPI ExtractAssociatedIcon16(HINSTANCE16 hInst, LPSTR lpIconPath, LPWORD lpiIcon)
986 {       HICON16 hIcon;
987
988         TRACE("\n");
989
990         hIcon = ExtractIcon16(hInst, lpIconPath, *lpiIcon);
991
992         if( hIcon < 2 )
993         { if( hIcon == 1 ) /* no icons found in given file */
994           { char  tempPath[0x80];
995             UINT16  uRet = FindExecutable16(lpIconPath,NULL,tempPath);
996
997             if( uRet > 32 && tempPath[0] )
998             { strcpy(lpIconPath,tempPath);
999               hIcon = ExtractIcon16(hInst, lpIconPath, *lpiIcon);
1000               if( hIcon > 2 ) 
1001                 return hIcon;
1002             }
1003             else hIcon = 0;
1004           }
1005
1006           if( hIcon == 1 ) 
1007             *lpiIcon = 2;   /* MSDOS icon - we found .exe but no icons in it */
1008           else
1009             *lpiIcon = 6;   /* generic icon - found nothing */
1010
1011           GetModuleFileName16(hInst, lpIconPath, 0x80);
1012           hIcon = LoadIcon16( hInst, MAKEINTRESOURCE16(*lpiIcon));
1013         }
1014         return hIcon;
1015 }
1016
1017 /*************************************************************************
1018  *                              FindEnvironmentString   [SHELL.38]
1019  *
1020  * Returns a pointer into the DOS environment... Ugh.
1021  */
1022 LPSTR SHELL_FindString(LPSTR lpEnv, LPCSTR entry)
1023 { UINT16 l;
1024
1025   TRACE("\n");
1026
1027   l = strlen(entry); 
1028   for( ; *lpEnv ; lpEnv+=strlen(lpEnv)+1 )
1029   { if( lstrncmpiA(lpEnv, entry, l) ) 
1030       continue;
1031         if( !*(lpEnv+l) )
1032             return (lpEnv + l);                 /* empty entry */
1033         else if ( *(lpEnv+l)== '=' )
1034             return (lpEnv + l + 1);
1035     }
1036     return NULL;
1037 }
1038
1039 SEGPTR WINAPI FindEnvironmentString16(LPSTR str)
1040 { SEGPTR  spEnv;
1041   LPSTR lpEnv,lpString;
1042   TRACE("\n");
1043     
1044   spEnv = GetDOSEnvironment16();
1045
1046   lpEnv = (LPSTR)PTR_SEG_TO_LIN(spEnv);
1047   lpString = (spEnv)?SHELL_FindString(lpEnv, str):NULL; 
1048
1049     if( lpString )              /*  offset should be small enough */
1050         return spEnv + (lpString - lpEnv);
1051     return (SEGPTR)NULL;
1052 }
1053
1054 /*************************************************************************
1055  *                              DoEnvironmentSubst      [SHELL.37]
1056  *
1057  * Replace %KEYWORD% in the str with the value of variable KEYWORD
1058  * from "DOS" environment.
1059  */
1060 DWORD WINAPI DoEnvironmentSubst16(LPSTR str,WORD length)
1061 {
1062   LPSTR   lpEnv = (LPSTR)PTR_SEG_TO_LIN(GetDOSEnvironment16());
1063   LPSTR   lpBuffer = (LPSTR)HeapAlloc( GetProcessHeap(), 0, length);
1064   LPSTR   lpstr = str;
1065   LPSTR   lpbstr = lpBuffer;
1066
1067   CharToOemA(str,str);
1068
1069   TRACE("accept %s\n", str);
1070
1071   while( *lpstr && lpbstr - lpBuffer < length )
1072    {
1073      LPSTR lpend = lpstr;
1074
1075      if( *lpstr == '%' )
1076        {
1077           do { lpend++; } while( *lpend && *lpend != '%' );
1078           if( *lpend == '%' && lpend - lpstr > 1 )      /* found key */
1079             {
1080                LPSTR lpKey;
1081               *lpend = '\0';  
1082                lpKey = SHELL_FindString(lpEnv, lpstr+1);
1083                if( lpKey )                              /* found key value */
1084                  {
1085                    int l = strlen(lpKey);
1086
1087                    if( l > length - (lpbstr - lpBuffer) - 1 )
1088                      {
1089            WARN("-- Env subst aborted - string too short\n");
1090                       *lpend = '%';
1091                        break;
1092                      }
1093                    strcpy(lpbstr, lpKey);
1094                    lpbstr += l;
1095                  }
1096                else break;
1097               *lpend = '%';
1098                lpstr = lpend + 1;
1099             }
1100           else break;                                   /* back off and whine */
1101
1102           continue;
1103        } 
1104
1105      *lpbstr++ = *lpstr++;
1106    }
1107
1108  *lpbstr = '\0';
1109   if( lpstr - str == strlen(str) )
1110     {
1111       strncpy(str, lpBuffer, length);
1112       length = 1;
1113     }
1114   else
1115       length = 0;
1116
1117   TRACE("-- return %s\n", str);
1118
1119   OemToCharA(str,str);
1120   HeapFree( GetProcessHeap(), 0, lpBuffer);
1121
1122   /*  Return str length in the LOWORD
1123    *  and 1 in HIWORD if subst was successful.
1124    */
1125  return (DWORD)MAKELONG(strlen(str), length);
1126 }
1127
1128 /*************************************************************************
1129  *                              ShellHookProc           [SHELL.103]
1130  * System-wide WH_SHELL hook.
1131  */
1132 LRESULT WINAPI ShellHookProc16(INT16 code, WPARAM16 wParam, LPARAM lParam)
1133 {
1134     TRACE("%i, %04x, %08x\n", code, wParam, 
1135                                                       (unsigned)lParam );
1136     if( SHELL_hHook && SHELL_hWnd )
1137     {
1138         UINT16  uMsg = 0;
1139         switch( code )
1140         {
1141             case HSHELL_WINDOWCREATED:          uMsg = uMsgWndCreated;   break;
1142             case HSHELL_WINDOWDESTROYED:        uMsg = uMsgWndDestroyed; break;
1143             case HSHELL_ACTIVATESHELLWINDOW:    uMsg = uMsgShellActivate;
1144         }
1145         PostMessage16( SHELL_hWnd, uMsg, wParam, 0 );
1146     }
1147     return CallNextHookEx16( WH_SHELL, code, wParam, lParam );
1148 }
1149
1150 /*************************************************************************
1151  *                              RegisterShellHook       [SHELL.102]
1152  */
1153 BOOL WINAPI RegisterShellHook16(HWND16 hWnd, UINT16 uAction)
1154
1155     TRACE("%04x [%u]\n", hWnd, uAction );
1156
1157     switch( uAction )
1158     { 
1159     case 2:  /* register hWnd as a shell window */
1160         if( !SHELL_hHook )
1161         { 
1162             HMODULE16 hShell = GetModuleHandle16( "SHELL" );
1163             HOOKPROC16 hookProc = (HOOKPROC16)NE_GetEntryPoint( hShell, 103 );
1164             SHELL_hHook = SetWindowsHookEx16( WH_SHELL, hookProc, hShell, 0 );
1165             if ( SHELL_hHook )
1166             { 
1167                 uMsgWndCreated = RegisterWindowMessageA( lpstrMsgWndCreated );
1168                 uMsgWndDestroyed = RegisterWindowMessageA( lpstrMsgWndDestroyed );
1169                 uMsgShellActivate = RegisterWindowMessageA( lpstrMsgShellActivate );
1170             } 
1171             else 
1172                 WARN("-- unable to install ShellHookProc()!\n");
1173         }
1174
1175         if ( SHELL_hHook )
1176             return ((SHELL_hWnd = hWnd) != 0);
1177         break;
1178
1179     default:
1180         WARN("-- unknown code %i\n", uAction );
1181         SHELL_hWnd = 0; /* just in case */
1182     }
1183     return FALSE;
1184 }