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