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