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