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