Fix for avoiding subtraction from unsigned zero.
[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 "ldt.h"
17 #include "dlgs.h"
18 #include "shellapi.h"
19 #include "shlobj.h"
20 #include "debugtools.h"
21 #include "winreg.h"
22 #include "shlwapi.h"
23
24 DEFAULT_DEBUG_CHANNEL(shell);
25 DECLARE_DEBUG_CHANNEL(exec);
26
27
28 typedef struct {     /* structure for dropped files */
29  WORD     wSize;
30  POINT16  ptMousePos;
31  BOOL16   fInNonClientArea;
32  /* memory block with filenames follows */
33 } DROPFILESTRUCT16, *LPDROPFILESTRUCT16;
34
35 static const char*      lpstrMsgWndCreated = "OTHERWINDOWCREATED";
36 static const char*      lpstrMsgWndDestroyed = "OTHERWINDOWDESTROYED";
37 static const char*      lpstrMsgShellActivate = "ACTIVATESHELLWINDOW";
38
39 static HWND16   SHELL_hWnd = 0;
40 static HHOOK    SHELL_hHook = 0;
41 static UINT16   uMsgWndCreated = 0;
42 static UINT16   uMsgWndDestroyed = 0;
43 static UINT16   uMsgShellActivate = 0;
44 HINSTANCE16     SHELL_hInstance = 0;
45 HINSTANCE SHELL_hInstance32;
46 static int SHELL_Attach = 0;
47
48 /***********************************************************************
49  * SHELL_DllEntryPoint [SHELL.entry]
50  *
51  * Initialization code for shell.dll. Automatically loads the
52  * 32-bit shell32.dll to allow thunking up to 32-bit code.
53  *
54  * RETURNS:
55  */
56 BOOL WINAPI SHELL_DllEntryPoint(DWORD Reason, HINSTANCE16 hInst,
57                                 WORD ds, WORD HeapSize, DWORD res1, WORD res2)
58 {
59     TRACE("(%08lx, %04x, %04x, %04x, %08lx, %04x)\n",
60           Reason, hInst, ds, HeapSize, res1, res2);
61
62     switch(Reason)
63     {
64     case DLL_PROCESS_ATTACH:
65         SHELL_Attach++;
66         if (SHELL_hInstance)
67         {
68             ERR("shell.dll instantiated twice!\n");
69             /*
70              * We should return FALSE here, but that will break
71              * most apps that use CreateProcess because we do
72              * not yet support seperate address-spaces.
73              */
74             return TRUE;
75         }
76
77         SHELL_hInstance = hInst;
78         if(!SHELL_hInstance32)
79         {
80             if(!(SHELL_hInstance32 = LoadLibraryA("shell32.dll")))
81             {
82                 ERR("Could not load sibling shell32.dll\n");
83                 return FALSE;
84             }
85         }
86         break;
87
88     case DLL_PROCESS_DETACH:
89         if(!--SHELL_Attach)
90         {
91             SHELL_hInstance = 0;
92             if(SHELL_hInstance32)
93                 FreeLibrary(SHELL_hInstance32);
94         }
95         break;
96     }
97     return TRUE;
98 }
99
100 /*************************************************************************
101  *                              DragAcceptFiles16               [SHELL.9]
102  */
103 void WINAPI DragAcceptFiles16(HWND16 hWnd, BOOL16 b)
104 {
105   DragAcceptFiles(hWnd, b);
106 }
107
108 /*************************************************************************
109  *                              DragQueryFile16         [SHELL.11]
110  */
111 UINT16 WINAPI DragQueryFile16(
112         HDROP16 hDrop,
113         WORD wFile,
114         LPSTR lpszFile,
115         WORD wLength)
116 {
117         LPSTR lpDrop;
118         UINT i = 0;
119         LPDROPFILESTRUCT16 lpDropFileStruct = (LPDROPFILESTRUCT16) GlobalLock16(hDrop); 
120    
121         TRACE("(%04x, %x, %p, %u)\n", hDrop,wFile,lpszFile,wLength);
122     
123         if(!lpDropFileStruct) goto end;
124     
125         lpDrop = (LPSTR) lpDropFileStruct + lpDropFileStruct->wSize;
126         wFile = (wFile==0xffff) ? 0xffffffff : wFile;
127
128         while (i++ < wFile)
129         {
130           while (*lpDrop++); /* skip filename */
131           if (!*lpDrop) 
132           {
133             i = (wFile == 0xFFFFFFFF) ? i : 0; 
134             goto end;
135           }
136         }
137     
138         i = strlen(lpDrop);
139         i++;
140         if (!lpszFile ) goto end;   /* needed buffer size */
141         i = (wLength > i) ? i : wLength;
142         lstrcpynA (lpszFile,  lpDrop,  i);
143 end:
144         GlobalUnlock16(hDrop);
145         return i;
146 }
147
148 /*************************************************************************
149  *                              DragFinish16            [SHELL.12]
150  */
151 void WINAPI DragFinish16(HDROP16 h)
152 {
153     TRACE("\n");
154     GlobalFree16((HGLOBAL16)h);
155 }
156
157
158 /*************************************************************************
159  *                              DragQueryPoint16                [SHELL.13]
160  */
161 BOOL16 WINAPI DragQueryPoint16(HDROP16 hDrop, POINT16 *p)
162 {
163   LPDROPFILESTRUCT16 lpDropFileStruct;  
164   BOOL16           bRet;
165   TRACE("\n");
166   lpDropFileStruct = (LPDROPFILESTRUCT16) GlobalLock16(hDrop);
167   
168   memcpy(p,&lpDropFileStruct->ptMousePos,sizeof(POINT16));
169   bRet = lpDropFileStruct->fInNonClientArea;
170   
171   GlobalUnlock16(hDrop);
172   return bRet;
173 }
174
175 /*************************************************************************
176  *      SHELL_FindExecutable [Internal]
177  *
178  * Utility for code sharing between FindExecutable and ShellExecute
179  */
180 HINSTANCE SHELL_FindExecutable( LPCSTR lpFile, 
181                                          LPCSTR lpOperation,
182                                          LPSTR lpResult)
183 { char *extension = NULL; /* pointer to file extension */
184     char tmpext[5];         /* local copy to mung as we please */
185     char filetype[256];     /* registry name for this filetype */
186     LONG filetypelen=256;   /* length of above */
187     char command[256];      /* command from registry */
188     LONG commandlen=256;    /* This is the most DOS can handle :) */
189     char buffer[256];       /* Used to GetProfileString */
190     HINSTANCE retval=31;  /* default - 'No association was found' */
191     char *tok;              /* token pointer */
192     int i;                  /* random counter */
193     char xlpFile[256] = ""; /* result of SearchPath */
194
195   TRACE("%s\n", (lpFile != NULL?lpFile:"-") );
196
197     lpResult[0]='\0'; /* Start off with an empty return string */
198
199     /* trap NULL parameters on entry */
200     if (( lpFile == NULL ) || ( lpResult == NULL ) || ( lpOperation == NULL ))
201   { WARN_(exec)("(lpFile=%s,lpResult=%s,lpOperation=%s): NULL parameter\n",
202            lpFile, lpOperation, lpResult);
203         return 2; /* File not found. Close enough, I guess. */
204     }
205
206     if (SearchPathA( NULL, lpFile,".exe",sizeof(xlpFile),xlpFile,NULL))
207   { TRACE("SearchPathA returned non-zero\n");
208         lpFile = xlpFile;
209     }
210
211     /* First thing we need is the file's extension */
212     extension = strrchr( xlpFile, '.' ); /* Assume last "." is the one; */
213                                         /* File->Run in progman uses */
214                                         /* .\FILE.EXE :( */
215   TRACE("xlpFile=%s,extension=%s\n", xlpFile, extension);
216
217     if ((extension == NULL) || (extension == &xlpFile[strlen(xlpFile)]))
218   { WARN("Returning 31 - No association\n");
219         return 31; /* no association */
220     }
221
222     /* Make local copy & lowercase it for reg & 'programs=' lookup */
223     lstrcpynA( tmpext, extension, 5 );
224     CharLowerA( tmpext );
225   TRACE("%s file\n", tmpext);
226     
227     /* Three places to check: */
228     /* 1. win.ini, [windows], programs (NB no leading '.') */
229     /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
230     /* 3. win.ini, [extensions], extension (NB no leading '.' */
231     /* All I know of the order is that registry is checked before */
232     /* extensions; however, it'd make sense to check the programs */
233     /* section first, so that's what happens here. */
234
235     /* See if it's a program - if GetProfileString fails, we skip this
236      * section. Actually, if GetProfileString fails, we've probably
237      * got a lot more to worry about than running a program... */
238     if ( GetProfileStringA("windows", "programs", "exe pif bat com",
239                                                   buffer, sizeof(buffer)) > 0 )
240   { for (i=0;i<strlen(buffer); i++) buffer[i]=tolower(buffer[i]);
241
242                 tok = strtok(buffer, " \t"); /* ? */
243                 while( tok!= NULL)
244                   {
245                         if (strcmp(tok, &tmpext[1])==0) /* have to skip the leading "." */
246                           {
247                                 strcpy(lpResult, xlpFile);
248                                 /* Need to perhaps check that the file has a path
249                                  * attached */
250         TRACE("found %s\n", lpResult);
251         return 33;
252
253                 /* Greater than 32 to indicate success FIXME According to the
254                  * docs, I should be returning a handle for the
255                  * executable. Does this mean I'm supposed to open the
256                  * executable file or something? More RTFM, I guess... */
257                           }
258                         tok=strtok(NULL, " \t");
259                   }
260           }
261
262     /* Check registry */
263     if (RegQueryValue16( HKEY_CLASSES_ROOT, tmpext, filetype,
264                          &filetypelen ) == ERROR_SUCCESS )
265     {
266         filetype[filetypelen]='\0';
267         TRACE("File type: %s\n", filetype);
268
269         /* Looking for ...buffer\shell\lpOperation\command */
270         strcat( filetype, "\\shell\\" );
271         strcat( filetype, lpOperation );
272         strcat( filetype, "\\command" );
273         
274         if (RegQueryValue16( HKEY_CLASSES_ROOT, filetype, command,
275                              &commandlen ) == ERROR_SUCCESS )
276         {
277             LPSTR tmp;
278             char param[256];
279             LONG paramlen = 256;
280
281
282             /* Get the parameters needed by the application 
283                from the associated ddeexec key */ 
284             tmp = strstr(filetype,"command");
285             tmp[0] = '\0';
286             strcat(filetype,"ddeexec");
287
288             if(RegQueryValue16( HKEY_CLASSES_ROOT, filetype, param,&paramlen ) == ERROR_SUCCESS)
289             {
290               strcat(command," ");
291               strcat(command,param);
292               commandlen += paramlen;
293             }
294
295             /* Is there a replace() function anywhere? */
296             command[commandlen]='\0';
297             strcpy( lpResult, command );
298             tok=strstr( lpResult, "%1" );
299             if (tok != NULL)
300             {
301                 tok[0]='\0'; /* truncate string at the percent */
302                 strcat( lpResult, xlpFile ); /* what if no dir in xlpFile? */
303                 tok=strstr( command, "%1" );
304                 if ((tok!=NULL) && (strlen(tok)>2))
305                 {
306                     strcat( lpResult, &tok[2] );
307                 }
308             }
309             retval=33; /* FIXME see above */
310         }
311     }
312     else /* Check win.ini */
313     {
314         /* Toss the leading dot */
315         extension++;
316         if ( GetProfileStringA( "extensions", extension, "", command,
317                                   sizeof(command)) > 0)
318           {
319                 if (strlen(command)!=0)
320                   {
321                         strcpy( lpResult, command );
322                         tok=strstr( lpResult, "^" ); /* should be ^.extension? */
323                         if (tok != NULL)
324                           {
325                                 tok[0]='\0';
326                                 strcat( lpResult, xlpFile ); /* what if no dir in xlpFile? */
327                                 tok=strstr( command, "^" ); /* see above */
328                                 if ((tok != NULL) && (strlen(tok)>5))
329                                   {
330                                         strcat( lpResult, &tok[5]);
331                                   }
332                           }
333                         retval=33; /* FIXME - see above */
334                   }
335           }
336         }
337
338     TRACE("returning %s\n", lpResult);
339     return retval;
340 }
341
342 /*************************************************************************
343  *                              ShellExecute16          [SHELL.20]
344  */
345 HINSTANCE16 WINAPI ShellExecute16( HWND16 hWnd, LPCSTR lpOperation,
346                                    LPCSTR lpFile, LPCSTR lpParameters,
347                                    LPCSTR lpDirectory, INT16 iShowCmd )
348 {   HINSTANCE16 retval=31;
349     char old_dir[1024];
350     char cmd[1024] = "";
351
352     TRACE("(%04x,'%s','%s','%s','%s',%x)\n",
353                 hWnd, lpOperation ? lpOperation:"<null>", lpFile ? lpFile:"<null>",
354                 lpParameters ? lpParameters : "<null>", 
355                 lpDirectory ? lpDirectory : "<null>", iShowCmd);
356
357     if (lpFile==NULL) return 0; /* should not happen */
358     if (lpOperation==NULL) /* default is open */
359       lpOperation="open";
360
361     if (lpDirectory)
362     { GetCurrentDirectoryA( sizeof(old_dir), old_dir );
363         SetCurrentDirectoryA( lpDirectory );
364     }
365
366     /* First try to execute lpFile with lpParameters directly */ 
367     strcpy(cmd,lpFile);
368     strcat(cmd,lpParameters ? lpParameters : "");
369
370     retval = WinExec16( cmd, iShowCmd );
371
372     /* Unable to execute lpFile directly
373        Check if we can match an application to lpFile */
374     if(retval < 32)
375     { 
376       cmd[0] = '\0';
377       retval = SHELL_FindExecutable( lpFile, lpOperation, cmd );
378
379       if (retval > 32)  /* Found */
380       {
381         if (lpParameters)
382         {
383             strcat(cmd," ");
384             strcat(cmd,lpParameters);
385         }
386         retval = WinExec16( cmd, iShowCmd );
387       }
388       else if(PathIsURLA((LPSTR)lpFile))    /* File not found, check for URL */
389       {
390         char lpstrProtocol[256];
391         LONG cmdlen = 512;
392         LPSTR lpstrRes;
393         INT iSize;
394       
395         lpstrRes = strchr(lpFile,':');
396         iSize = lpstrRes - lpFile;
397         
398         /* Looking for ...protocol\shell\lpOperation\command */
399         strncpy(lpstrProtocol,lpFile,iSize);
400         lpstrProtocol[iSize]='\0';
401         strcat( lpstrProtocol, "\\shell\\" );
402         strcat( lpstrProtocol, lpOperation );
403         strcat( lpstrProtocol, "\\command" );
404         
405         /* Remove File Protocol from lpFile */
406         /* In the case file://path/file     */
407         if(!strncasecmp(lpFile,"file",iSize))
408         {
409           lpFile += iSize;
410           while(*lpFile == ':') lpFile++;
411         }
412         
413
414         /* Get the application for the protocol and execute it */
415         if (RegQueryValue16( HKEY_CLASSES_ROOT, lpstrProtocol, cmd,
416                              &cmdlen ) == ERROR_SUCCESS )
417         {
418             LPSTR tok;
419             LPSTR tmp;
420             char param[256] = "";
421             LONG paramlen = 256;
422
423             /* Get the parameters needed by the application 
424                from the associated ddeexec key */ 
425             tmp = strstr(lpstrProtocol,"command");
426             tmp[0] = '\0';
427             strcat(lpstrProtocol,"ddeexec");
428
429             if(RegQueryValue16( HKEY_CLASSES_ROOT, lpstrProtocol, param,&paramlen ) == ERROR_SUCCESS)
430             {
431               strcat(cmd," ");
432               strcat(cmd,param);
433               cmdlen += paramlen;
434             }
435             
436             /* Is there a replace() function anywhere? */
437             cmd[cmdlen]='\0';
438
439             tok=strstr( cmd, "%1" );
440             if (tok != NULL)
441             {
442                 tok[0]='\0'; /* truncate string at the percent */
443                 strcat( cmd, lpFile ); /* what if no dir in xlpFile? */
444                 tok=strstr( cmd, "%1" );
445                 if ((tok!=NULL) && (strlen(tok)>2))
446                 {
447                     strcat( cmd, &tok[2] );
448                 }
449             }
450  
451             retval = WinExec16( cmd, iShowCmd );
452         }
453       }
454     /* Check if file specified is in the form www.??????.*** */
455       else if(!strncasecmp(lpFile,"www",3))
456       {
457         /* if so, append lpFile http:// and call ShellExecute */ 
458         char lpstrTmpFile[256] = "http://" ;
459         strcat(lpstrTmpFile,lpFile);
460         retval = ShellExecuteA(hWnd,lpOperation,lpstrTmpFile,NULL,NULL,0);
461       }
462     }
463     if (lpDirectory)
464       SetCurrentDirectoryA( old_dir );
465     return retval;
466 }
467
468 /*************************************************************************
469  *             FindExecutable16   (SHELL.21)
470  */
471 HINSTANCE16 WINAPI FindExecutable16( LPCSTR lpFile, LPCSTR lpDirectory,
472                                      LPSTR lpResult )
473 { return (HINSTANCE16)FindExecutableA( lpFile, lpDirectory, lpResult );
474 }
475
476
477 /*************************************************************************
478  *             AboutDlgProc16   (SHELL.33)
479  */
480 BOOL16 WINAPI AboutDlgProc16( HWND16 hWnd, UINT16 msg, WPARAM16 wParam,
481                                LPARAM lParam )
482 { return AboutDlgProc( hWnd, msg, wParam, lParam );
483 }
484
485
486 /*************************************************************************
487  *             ShellAbout16   (SHELL.22)
488  */
489 BOOL16 WINAPI ShellAbout16( HWND16 hWnd, LPCSTR szApp, LPCSTR szOtherStuff,
490                             HICON16 hIcon )
491 { return ShellAboutA( hWnd, szApp, szOtherStuff, hIcon );
492 }
493
494 /*************************************************************************
495  *                      InternalExtractIcon             [SHELL.39]
496  *
497  * This abortion is called directly by Progman
498  */
499 HGLOBAL16 WINAPI InternalExtractIcon16(HINSTANCE16 hInstance,
500                                      LPCSTR lpszExeFileName, UINT16 nIconIndex, WORD n )
501 {
502     HGLOBAL16 hRet = 0;
503     HICON16 *RetPtr = NULL;
504     OFSTRUCT ofs;
505     HFILE hFile;
506
507         TRACE("(%04x,file %s,start %d,extract %d\n", 
508                        hInstance, lpszExeFileName, nIconIndex, n);
509
510         if( !n )
511           return 0;
512
513         hFile = OpenFile( lpszExeFileName, &ofs, OF_READ );
514
515         hRet = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(HICON16)*n);
516         RetPtr = (HICON16*)GlobalLock16(hRet);
517
518         if (hFile == HFILE_ERROR)
519         { /* not found - load from builtin module if available */
520           HINSTANCE hInst = (HINSTANCE)LoadLibrary16(lpszExeFileName);
521
522           if (hInst < 32) /* hmm, no Win16 module - try Win32 :-) */
523             hInst = LoadLibraryA(lpszExeFileName);
524           if (hInst)
525           {
526             int i;
527             for (i=nIconIndex; i < nIconIndex + n; i++)
528               RetPtr[i-nIconIndex] =
529                       (HICON16)LoadIconA(hInst, (LPCSTR)(DWORD)i);
530             FreeLibrary(hInst);
531             return hRet;
532           }
533           GlobalFree16( hRet );
534           return 0;
535         }
536
537         if (nIconIndex == (UINT16)-1)  /* get number of icons */
538         {
539             RetPtr[0] = PrivateExtractIconsA( ofs.szPathName, -1, 0, 0, NULL, 0, 0, 0 );
540         }
541         else
542         {
543             HRESULT res;
544             HICON *icons;
545             icons = HeapAlloc( GetProcessHeap(), 0, n * sizeof(*icons) );
546             res = PrivateExtractIconsA( ofs.szPathName, nIconIndex,
547                                         GetSystemMetrics(SM_CXICON),
548                                         GetSystemMetrics(SM_CYICON),
549                                         icons, 0, n, 0 );
550             if (!res)
551             {
552                 int i;
553                 for (i = 0; i < n; i++) RetPtr[i] = (HICON16)icons[i];
554             }
555             else
556             {
557                 GlobalFree16( hRet );
558                 hRet = 0;
559             }
560             HeapFree( GetProcessHeap(), 0, icons );
561         }
562         return hRet;
563 }
564
565 /*************************************************************************
566  *             ExtractIcon16   (SHELL.34)
567  */
568 HICON16 WINAPI ExtractIcon16( HINSTANCE16 hInstance, LPCSTR lpszExeFileName,
569         UINT16 nIconIndex )
570 {   TRACE("\n");
571     return ExtractIconA( hInstance, lpszExeFileName, nIconIndex );
572 }
573
574 /*************************************************************************
575  *             ExtractIconEx16   (SHELL.40)
576  */
577 HICON16 WINAPI ExtractIconEx16(
578         LPCSTR lpszFile, INT16 nIconIndex, HICON16 *phiconLarge,
579         HICON16 *phiconSmall, UINT16 nIcons
580 ) {
581     HICON       *ilarge,*ismall;
582     UINT16      ret;
583     int         i;
584
585     if (phiconLarge)
586         ilarge = (HICON*)HeapAlloc(GetProcessHeap(),0,nIcons*sizeof(HICON));
587     else
588         ilarge = NULL;
589     if (phiconSmall)
590         ismall = (HICON*)HeapAlloc(GetProcessHeap(),0,nIcons*sizeof(HICON));
591     else
592         ismall = NULL;
593     ret = ExtractIconExA(lpszFile,nIconIndex,ilarge,ismall,nIcons);
594     if (ilarge) {
595         for (i=0;i<nIcons;i++)
596             phiconLarge[i]=ilarge[i];
597         HeapFree(GetProcessHeap(),0,ilarge);
598     }
599     if (ismall) {
600         for (i=0;i<nIcons;i++)
601             phiconSmall[i]=ismall[i];
602         HeapFree(GetProcessHeap(),0,ismall);
603     }
604     return ret;
605 }
606
607 /*************************************************************************
608  *                              ExtractAssociatedIcon   [SHELL.36]
609  * 
610  * Return icon for given file (either from file itself or from associated
611  * executable) and patch parameters if needed.
612  */
613 HICON16 WINAPI ExtractAssociatedIcon16(HINSTANCE16 hInst, LPSTR lpIconPath, LPWORD lpiIcon)
614 {       HICON16 hIcon;
615         WORD wDummyIcon = 0;
616
617         TRACE("\n");
618
619         if(lpiIcon == NULL)
620             lpiIcon = &wDummyIcon;
621
622         hIcon = ExtractIcon16(hInst, lpIconPath, *lpiIcon);
623
624         if( hIcon < 2 )
625         { if( hIcon == 1 ) /* no icons found in given file */
626           { char  tempPath[0x80];
627             UINT16  uRet = FindExecutable16(lpIconPath,NULL,tempPath);
628
629             if( uRet > 32 && tempPath[0] )
630             { strcpy(lpIconPath,tempPath);
631               hIcon = ExtractIcon16(hInst, lpIconPath, *lpiIcon);
632               if( hIcon > 2 ) 
633                 return hIcon;
634             }
635             else hIcon = 0;
636           }
637
638           if( hIcon == 1 ) 
639             *lpiIcon = 2;   /* MSDOS icon - we found .exe but no icons in it */
640           else
641             *lpiIcon = 6;   /* generic icon - found nothing */
642
643           GetModuleFileName16(hInst, lpIconPath, 0x80);
644           hIcon = LoadIcon16( hInst, MAKEINTRESOURCE16(*lpiIcon));
645         }
646         return hIcon;
647 }
648
649 /*************************************************************************
650  *                              ExtractAssociatedIconA
651  * 
652  * Return icon for given file (either from file itself or from associated
653  * executable) and patch parameters if needed.
654  */
655 HICON WINAPI ExtractAssociatedIconA(HINSTANCE hInst, LPSTR lpIconPath, LPWORD lpiIcon)
656 {       TRACE("\n");
657         return ExtractAssociatedIcon16(hInst,lpIconPath,lpiIcon);
658 }
659
660 /*************************************************************************
661  *                              FindEnvironmentString   [SHELL.38]
662  *
663  * Returns a pointer into the DOS environment... Ugh.
664  */
665 LPSTR SHELL_FindString(LPSTR lpEnv, LPCSTR entry)
666 { UINT16 l;
667
668   TRACE("\n");
669
670   l = strlen(entry); 
671   for( ; *lpEnv ; lpEnv+=strlen(lpEnv)+1 )
672   { if( strncasecmp(lpEnv, entry, l) ) 
673       continue;
674         if( !*(lpEnv+l) )
675             return (lpEnv + l);                 /* empty entry */
676         else if ( *(lpEnv+l)== '=' )
677             return (lpEnv + l + 1);
678     }
679     return NULL;
680 }
681
682 SEGPTR WINAPI FindEnvironmentString16(LPSTR str)
683 { SEGPTR  spEnv;
684   LPSTR lpEnv,lpString;
685   TRACE("\n");
686     
687   spEnv = GetDOSEnvironment16();
688
689   lpEnv = (LPSTR)PTR_SEG_TO_LIN(spEnv);
690   lpString = (spEnv)?SHELL_FindString(lpEnv, str):NULL; 
691
692     if( lpString )              /*  offset should be small enough */
693         return spEnv + (lpString - lpEnv);
694     return (SEGPTR)NULL;
695 }
696
697 /*************************************************************************
698  *                              DoEnvironmentSubst      [SHELL.37]
699  *
700  * Replace %KEYWORD% in the str with the value of variable KEYWORD
701  * from "DOS" environment.
702  */
703 DWORD WINAPI DoEnvironmentSubst16(LPSTR str,WORD length)
704 {
705   LPSTR   lpEnv = (LPSTR)PTR_SEG_TO_LIN(GetDOSEnvironment16());
706   LPSTR   lpBuffer = (LPSTR)HeapAlloc( GetProcessHeap(), 0, length);
707   LPSTR   lpstr = str;
708   LPSTR   lpbstr = lpBuffer;
709
710   CharToOemA(str,str);
711
712   TRACE("accept %s\n", str);
713
714   while( *lpstr && lpbstr - lpBuffer < length )
715    {
716      LPSTR lpend = lpstr;
717
718      if( *lpstr == '%' )
719        {
720           do { lpend++; } while( *lpend && *lpend != '%' );
721           if( *lpend == '%' && lpend - lpstr > 1 )      /* found key */
722             {
723                LPSTR lpKey;
724               *lpend = '\0';  
725                lpKey = SHELL_FindString(lpEnv, lpstr+1);
726                if( lpKey )                              /* found key value */
727                  {
728                    int l = strlen(lpKey);
729
730                    if( l > length - (lpbstr - lpBuffer) - 1 )
731                      {
732            WARN("-- Env subst aborted - string too short\n");
733                       *lpend = '%';
734                        break;
735                      }
736                    strcpy(lpbstr, lpKey);
737                    lpbstr += l;
738                  }
739                else break;
740               *lpend = '%';
741                lpstr = lpend + 1;
742             }
743           else break;                                   /* back off and whine */
744
745           continue;
746        } 
747
748      *lpbstr++ = *lpstr++;
749    }
750
751  *lpbstr = '\0';
752   if( lpstr - str == strlen(str) )
753     {
754       strncpy(str, lpBuffer, length);
755       length = 1;
756     }
757   else
758       length = 0;
759
760   TRACE("-- return %s\n", str);
761
762   OemToCharA(str,str);
763   HeapFree( GetProcessHeap(), 0, lpBuffer);
764
765   /*  Return str length in the LOWORD
766    *  and 1 in HIWORD if subst was successful.
767    */
768  return (DWORD)MAKELONG(strlen(str), length);
769 }
770
771 /*************************************************************************
772  *                              ShellHookProc           [SHELL.103]
773  * System-wide WH_SHELL hook.
774  */
775 LRESULT WINAPI ShellHookProc16(INT16 code, WPARAM16 wParam, LPARAM lParam)
776 {
777     TRACE("%i, %04x, %08x\n", code, wParam, 
778                                                       (unsigned)lParam );
779     if( SHELL_hHook && SHELL_hWnd )
780     {
781         UINT16  uMsg = 0;
782         switch( code )
783         {
784             case HSHELL_WINDOWCREATED:          uMsg = uMsgWndCreated;   break;
785             case HSHELL_WINDOWDESTROYED:        uMsg = uMsgWndDestroyed; break;
786             case HSHELL_ACTIVATESHELLWINDOW:    uMsg = uMsgShellActivate;
787         }
788         PostMessage16( SHELL_hWnd, uMsg, wParam, 0 );
789     }
790     return CallNextHookEx16( WH_SHELL, code, wParam, lParam );
791 }
792
793 /*************************************************************************
794  *                              RegisterShellHook       [SHELL.102]
795  */
796 BOOL WINAPI RegisterShellHook16(HWND16 hWnd, UINT16 uAction)
797
798     TRACE("%04x [%u]\n", hWnd, uAction );
799
800     switch( uAction )
801     { 
802     case 2:  /* register hWnd as a shell window */
803         if( !SHELL_hHook )
804         { 
805             HMODULE16 hShell = GetModuleHandle16( "SHELL" );
806             HOOKPROC16 hookProc = (HOOKPROC16)GetProcAddress16( hShell, (SEGPTR)103 );
807             SHELL_hHook = SetWindowsHookEx16( WH_SHELL, hookProc, hShell, 0 );
808             if ( SHELL_hHook )
809             { 
810                 uMsgWndCreated = RegisterWindowMessageA( lpstrMsgWndCreated );
811                 uMsgWndDestroyed = RegisterWindowMessageA( lpstrMsgWndDestroyed );
812                 uMsgShellActivate = RegisterWindowMessageA( lpstrMsgShellActivate );
813             } 
814             else 
815                 WARN("-- unable to install ShellHookProc()!\n");
816         }
817
818         if ( SHELL_hHook )
819             return ((SHELL_hWnd = hWnd) != 0);
820         break;
821
822     default:
823         WARN("-- unknown code %i\n", uAction );
824         SHELL_hWnd = 0; /* just in case */
825     }
826     return FALSE;
827 }