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