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