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