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