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