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