Removed a number of global handle allocations and critical section
[wine] / dlls / shell32 / iconcache.c
1 /*
2  *      shell icon cache (SIC)
3  *
4  */
5 #include <string.h>
6 #include <sys/types.h>
7 #include <unistd.h>
8 #include "winbase.h"
9 #include "windef.h"
10 #include "wingdi.h"
11 #include "winuser.h"
12 #include "wine/winuser16.h"
13 #include "wine/winbase16.h"
14 #include "neexe.h"
15 #include "cursoricon.h"
16 #include "module.h"
17 #include "heap.h"
18 #include "debugtools.h"
19 #include "winversion.h"
20
21 #include "shellapi.h"
22 #include "pidl.h"
23 #include "shell32_main.h"
24
25 DEFAULT_DEBUG_CHANNEL(shell)
26
27 #include "pshpack1.h"
28
29 typedef struct
30 {
31     BYTE        bWidth;          /* Width, in pixels, of the image      */
32     BYTE        bHeight;         /* Height, in pixels, of the image     */
33     BYTE        bColorCount;     /* Number of colors in image (0 if >=8bpp) */
34     BYTE        bReserved;       /* Reserved ( must be 0)               */
35     WORD        wPlanes;         /* Color Planes                        */
36     WORD        wBitCount;       /* Bits per pixel                      */
37     DWORD       dwBytesInRes;    /* How many bytes in this resource?    */
38     DWORD       dwImageOffset;   /* Where in the file is this image?    */
39 } icoICONDIRENTRY, *LPicoICONDIRENTRY;
40
41 typedef struct
42 {
43     WORD            idReserved;   /* Reserved (must be 0) */
44     WORD            idType;       /* Resource Type (RES_ICON or RES_CURSOR) */
45     WORD            idCount;      /* How many images */
46     icoICONDIRENTRY idEntries[1]; /* An entry for each image (idCount of 'em) */
47 } icoICONDIR, *LPicoICONDIR;
48
49 #include "poppack.h"
50
51 #if 0
52 static void dumpIcoDirEnty ( LPicoICONDIRENTRY entry )
53 {       
54         TRACE("width = 0x%08x height = 0x%08x\n", entry->bWidth, entry->bHeight);
55         TRACE("colors = 0x%08x planes = 0x%08x\n", entry->bColorCount, entry->wPlanes);
56         TRACE("bitcount = 0x%08x bytesinres = 0x%08lx offset = 0x%08lx\n", 
57         entry->wBitCount, entry->dwBytesInRes, entry->dwImageOffset);
58 }
59 static void dumpIcoDir ( LPicoICONDIR entry )
60 {       
61         TRACE("type = 0x%08x count = 0x%08x\n", entry->idType, entry->idCount);
62 }
63 #endif
64 /*************************************************************************
65  *                              SHELL_GetResourceTable
66  */
67 static DWORD SHELL_GetResourceTable(HFILE hFile, LPBYTE *retptr)
68 {       IMAGE_DOS_HEADER        mz_header;
69         char                    magic[4];
70         int                     size;
71
72         TRACE("0x%08x %p\n", hFile, retptr);  
73
74         *retptr = NULL;
75         _llseek( hFile, 0, SEEK_SET );
76         if ((_lread(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) || (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
77         { if (mz_header.e_cblp == 1)    /* .ICO file ? */
78           { *retptr = (LPBYTE)-1;       /* ICONHEADER.idType, must be 1 */
79             return 1;
80           }
81           else
82             return 0; /* failed */
83         }
84         _llseek( hFile, mz_header.e_lfanew, SEEK_SET );
85
86         if (_lread( hFile, magic, sizeof(magic) ) != sizeof(magic))
87           return 0;
88
89         _llseek( hFile, mz_header.e_lfanew, SEEK_SET);
90
91         if (*(DWORD*)magic  == IMAGE_NT_SIGNATURE)
92           return IMAGE_NT_SIGNATURE;
93
94         if (*(WORD*)magic == IMAGE_OS2_SIGNATURE)
95         { IMAGE_OS2_HEADER      ne_header;
96           LPBYTE                pTypeInfo = (LPBYTE)-1;
97
98           if (_lread(hFile,&ne_header,sizeof(ne_header))!=sizeof(ne_header))
99             return 0;
100
101           if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE)
102             return 0;
103
104           size = ne_header.rname_tab_offset - ne_header.resource_tab_offset;
105
106           if( size > sizeof(NE_TYPEINFO) )
107           { pTypeInfo = (BYTE*)HeapAlloc( GetProcessHeap(), 0, size);
108             if( pTypeInfo ) 
109             { _llseek(hFile, mz_header.e_lfanew+ne_header.resource_tab_offset, SEEK_SET);
110               if( _lread( hFile, (char*)pTypeInfo, size) != size )
111               { HeapFree( GetProcessHeap(), 0, pTypeInfo); 
112                 pTypeInfo = NULL;
113               }
114             }
115           }
116           *retptr = pTypeInfo;
117           return IMAGE_OS2_SIGNATURE;
118         }
119         return 0; /* failed */
120 }
121 /*************************************************************************
122  *                      SHELL_LoadResource
123  */
124 static BYTE * SHELL_LoadResource( HFILE hFile, NE_NAMEINFO* pNInfo, WORD sizeShift, ULONG *uSize)
125 {       BYTE*  ptr;
126
127         TRACE("0x%08x %p 0x%08x\n", hFile, pNInfo, sizeShift);
128
129         *uSize = (DWORD)pNInfo->length << sizeShift;
130         if( (ptr = (BYTE*)HeapAlloc(GetProcessHeap(),0, *uSize) ))
131         { _llseek( hFile, (DWORD)pNInfo->offset << sizeShift, SEEK_SET);
132           _lread( hFile, (char*)ptr, pNInfo->length << sizeShift);
133           return ptr;
134         }
135         return 0;
136 }
137
138 /*************************************************************************
139  *                      ICO_LoadIcon
140  */
141 static BYTE * ICO_LoadIcon( HFILE hFile, LPicoICONDIRENTRY lpiIDE, ULONG *uSize)
142 {       BYTE*  ptr;
143
144         TRACE("0x%08x %p\n", hFile, lpiIDE);
145
146         *uSize = lpiIDE->dwBytesInRes;
147         if( (ptr = (BYTE*)HeapAlloc(GetProcessHeap(),0, *uSize)) )
148         { _llseek( hFile, lpiIDE->dwImageOffset, SEEK_SET);
149           _lread( hFile, (char*)ptr, lpiIDE->dwBytesInRes);
150           return ptr;
151         }
152
153         return 0;
154 }
155
156 /*************************************************************************
157  *                      ICO_GetIconDirectory
158  *
159  * Reads .ico file and build phony ICONDIR struct
160  * see http://www.microsoft.com/win32dev/ui/icons.htm
161  */
162 #define HEADER_SIZE             (sizeof(CURSORICONDIR) - sizeof (CURSORICONDIRENTRY))
163 #define HEADER_SIZE_FILE        (sizeof(icoICONDIR) - sizeof (icoICONDIRENTRY))
164
165 static BYTE * ICO_GetIconDirectory( HFILE hFile, LPicoICONDIR* lplpiID, ULONG *uSize ) 
166 {       CURSORICONDIR   lpcid;  /* icon resource in resource-dir format */
167         LPicoICONDIR    lpiID;  /* icon resource in file format */
168         int             i;
169
170         TRACE("0x%08x %p\n", hFile, lplpiID); 
171         
172         _llseek( hFile, 0, SEEK_SET );
173         if( _lread(hFile,(char*)&lpcid, HEADER_SIZE_FILE) != HEADER_SIZE_FILE )
174           return 0;
175
176         if( lpcid.idReserved || (lpcid.idType != 1) || (!lpcid.idCount) )
177           return 0;
178
179         i = lpcid.idCount * sizeof(icoICONDIRENTRY);
180         lpiID = (LPicoICONDIR)HeapAlloc( GetProcessHeap(), 0, HEADER_SIZE_FILE + i);
181
182         if( _lread(hFile,(char*)lpiID->idEntries,i) == i )
183         { CURSORICONDIR * lpID;                 /* icon resource in resource format */
184           *uSize = lpcid.idCount * sizeof(CURSORICONDIRENTRY) + HEADER_SIZE;
185           if( (lpID = (CURSORICONDIR*)HeapAlloc(GetProcessHeap(),0, *uSize) ))
186           {
187             /* copy the header */
188             lpID->idReserved    = lpiID->idReserved = 0;
189             lpID->idType        = lpiID->idType = 1;
190             lpID->idCount       = lpiID->idCount = lpcid.idCount;
191
192             /* copy the entrys */
193             for( i=0; i < lpiID->idCount; i++ )
194             { memcpy((void*)&(lpID->idEntries[i]),(void*)&(lpiID->idEntries[i]), sizeof(CURSORICONDIRENTRY) - 2);
195               lpID->idEntries[i].wResId = i;
196             }
197
198             *lplpiID = lpiID;
199             return (BYTE *)lpID;
200           }
201         }
202         /* fail */
203
204         HeapFree( GetProcessHeap(), 0, lpiID);
205         return 0;
206 }
207
208 /*************************************************************************
209  *
210  * returns
211  *  failure:0; success: icon handle or nr of icons (nIconIndex-1)
212  */
213 HICON WINAPI ICO_ExtractIconEx(LPCSTR lpszExeFileName, HICON * RetPtr, UINT nIconIndex, UINT n, UINT cxDesired, UINT cyDesired )
214 {       HGLOBAL         hRet = 0;
215         LPBYTE          pData;
216         OFSTRUCT        ofs;
217         DWORD           sig;
218         HFILE           hFile = OpenFile( lpszExeFileName, &ofs, OF_READ );
219         UINT16          iconDirCount = 0,iconCount = 0;
220         LPBYTE          peimage;
221         HANDLE          fmapping;
222         ULONG           uSize;
223         
224         TRACE("(file %s,start %d,extract %d\n", lpszExeFileName, nIconIndex, n);
225
226         if( hFile == HFILE_ERROR || (nIconIndex!=-1 && !n) )
227           return hRet;
228
229         sig = SHELL_GetResourceTable(hFile,&pData);
230
231 /* ico file */
232         if( sig==IMAGE_OS2_SIGNATURE || sig==1 ) /* .ICO file */
233         { BYTE          *pCIDir = 0;
234           NE_TYPEINFO   *pTInfo = (NE_TYPEINFO*)(pData + 2);
235           NE_NAMEINFO   *pIconStorage = NULL;
236           NE_NAMEINFO   *pIconDir = NULL;
237           LPicoICONDIR  lpiID = NULL;
238
239           TRACE("-- OS2/icon Signature (0x%08lx)\n", sig);
240
241           if( pData == (BYTE*)-1 )
242           { pCIDir = ICO_GetIconDirectory(hFile, &lpiID, &uSize);       /* check for .ICO file */
243             if( pCIDir ) 
244             { iconDirCount = 1; iconCount = lpiID->idCount;
245               TRACE("-- icon found %p 0x%08lx 0x%08x 0x%08x\n", pCIDir, uSize, iconDirCount, iconCount);
246             }
247           }
248           else while( pTInfo->type_id && !(pIconStorage && pIconDir) )
249           { if( pTInfo->type_id == NE_RSCTYPE_GROUP_ICON )      /* find icon directory and icon repository */
250             { iconDirCount = pTInfo->count;
251               pIconDir = ((NE_NAMEINFO*)(pTInfo + 1));
252               TRACE("\tfound directory - %i icon families\n", iconDirCount);
253             }
254             if( pTInfo->type_id == NE_RSCTYPE_ICON ) 
255             { iconCount = pTInfo->count;
256               pIconStorage = ((NE_NAMEINFO*)(pTInfo + 1));
257               TRACE("\ttotal icons - %i\n", iconCount);
258             }
259             pTInfo = (NE_TYPEINFO *)((char*)(pTInfo+1)+pTInfo->count*sizeof(NE_NAMEINFO));
260           }
261
262           if( (pIconStorage && pIconDir) || lpiID )       /* load resources and create icons */
263           { if( nIconIndex == (UINT16)-1 )
264             { RetPtr[0] = iconDirCount;
265             }
266             else if( nIconIndex < iconDirCount )
267             { UINT16   i, icon;
268               if( n > iconDirCount - nIconIndex ) 
269                 n = iconDirCount - nIconIndex;
270
271               for( i = nIconIndex; i < nIconIndex + n; i++ ) 
272               { /* .ICO files have only one icon directory */
273
274                 if( lpiID == NULL )     /* *.ico */
275                   pCIDir = SHELL_LoadResource( hFile, pIconDir + i, *(WORD*)pData, &uSize );
276                 RetPtr[i-nIconIndex] = pLookupIconIdFromDirectoryEx( pCIDir, TRUE,  GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), 0);
277                 HeapFree(GetProcessHeap(), 0, pCIDir); 
278               }
279
280               for( icon = nIconIndex; icon < nIconIndex + n; icon++ )
281               { pCIDir = NULL;
282                 if( lpiID )
283                 { pCIDir = ICO_LoadIcon( hFile, lpiID->idEntries + RetPtr[icon-nIconIndex], &uSize);
284                 }
285                 else
286                 { for( i = 0; i < iconCount; i++ )
287                   { if( pIconStorage[i].id == (RetPtr[icon-nIconIndex] | 0x8000) )
288                     { pCIDir = SHELL_LoadResource( hFile, pIconStorage + i,*(WORD*)pData, &uSize );
289                     }
290                   }
291                 }
292                 if( pCIDir )
293                 { RetPtr[icon-nIconIndex] = (HICON) pCreateIconFromResourceEx(pCIDir,uSize,TRUE,0x00030000, cxDesired, cyDesired, LR_DEFAULTCOLOR);
294                 }
295                 else
296                 { RetPtr[icon-nIconIndex] = 0;
297                 }
298               }
299             }
300           }
301           if( lpiID ) 
302             HeapFree( GetProcessHeap(), 0, lpiID);
303           else 
304             HeapFree( GetProcessHeap(), 0, pData);
305         } 
306 /* end ico file */
307
308 /* exe/dll */
309         if( sig == IMAGE_NT_SIGNATURE)
310         { LPBYTE                idata,igdata;
311           PIMAGE_DOS_HEADER     dheader;
312           PIMAGE_NT_HEADERS     pe_header;
313           PIMAGE_SECTION_HEADER pe_sections;
314           PIMAGE_RESOURCE_DIRECTORY     rootresdir,iconresdir,icongroupresdir;
315           PIMAGE_RESOURCE_DATA_ENTRY    idataent,igdataent;
316           PIMAGE_RESOURCE_DIRECTORY_ENTRY       xresent;
317           int                   i,j;
318                   
319           if ( !(fmapping = CreateFileMappingA(hFile,NULL,PAGE_READONLY|SEC_COMMIT,0,0,NULL))) 
320           { WARN("failed to create filemap.\n");        /* FIXME, INVALID_HANDLE_VALUE? */
321             goto end_2;         /* failure */
322           }
323
324           if ( !(peimage = MapViewOfFile(fmapping,FILE_MAP_READ,0,0,0))) 
325           { WARN("failed to mmap filemap.\n");
326             goto end_2;         /* failure */
327           }
328
329           dheader = (PIMAGE_DOS_HEADER)peimage;
330           pe_header = (PIMAGE_NT_HEADERS)(peimage+dheader->e_lfanew);     /* it is a pe header, SHELL_GetResourceTable checked that */
331           pe_sections = (PIMAGE_SECTION_HEADER)(((char*)pe_header)+sizeof(*pe_header)); /* probably makes problems with short PE headers...*/
332           rootresdir = NULL;
333
334           for (i=0;i<pe_header->FileHeader.NumberOfSections;i++) 
335           { if (pe_sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
336               continue;
337             /* FIXME: doesn't work when the resources are not in a seperate section */
338             if (pe_sections[i].VirtualAddress == pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress) 
339             { rootresdir = (PIMAGE_RESOURCE_DIRECTORY)((char*)peimage+pe_sections[i].PointerToRawData);
340               break;
341             }
342           }
343
344           if (!rootresdir) 
345           { WARN("haven't found section for resource directory.\n");
346             goto end_3;         /* failure */
347           }
348   /* search the group icon dir*/
349           if (!(icongroupresdir = GetResDirEntryW(rootresdir,RT_GROUP_ICONW, (DWORD)rootresdir,FALSE))) 
350           { WARN("No Icongroupresourcedirectory!\n");
351             goto end_3;         /* failure */
352           }
353           iconDirCount = icongroupresdir->NumberOfNamedEntries+icongroupresdir->NumberOfIdEntries;
354
355   /* number of icons requested */
356           if( nIconIndex == -1 )
357           { hRet = iconDirCount;
358             goto end_3;         /* success */
359           }
360
361           if (nIconIndex >= iconDirCount) 
362           { WARN("nIconIndex %d is larger than iconDirCount %d\n",nIconIndex,iconDirCount);
363             goto end_3;         /* failure */
364           }
365
366           xresent = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(icongroupresdir+1);       /* caller just wanted the number of entries */
367
368           if( n > iconDirCount - nIconIndex )   /* assure we don't get too much ... */
369           { n = iconDirCount - nIconIndex;
370           }
371
372           xresent = xresent+nIconIndex;         /* starting from specified index ... */
373
374           for (i=0;i<n;i++,xresent++) 
375           { PIMAGE_RESOURCE_DIRECTORY   resdir;
376
377             /* go down this resource entry, name */
378             resdir = (PIMAGE_RESOURCE_DIRECTORY)((DWORD)rootresdir+(xresent->u2.s.OffsetToDirectory));
379
380             /* default language (0) */
381             resdir = GetResDirEntryW(resdir,(LPWSTR)0,(DWORD)rootresdir,TRUE);
382             igdataent = (PIMAGE_RESOURCE_DATA_ENTRY)resdir;
383
384             /* lookup address in mapped image for virtual address */
385             igdata = NULL;
386
387             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++) 
388             { if (igdataent->OffsetToData < pe_sections[j].VirtualAddress)
389                 continue;
390               if (igdataent->OffsetToData+igdataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
391                 continue;
392               igdata = peimage+(igdataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
393             }
394
395             if (!igdata) 
396             { WARN("no matching real address for icongroup!\n");
397               goto end_3;       /* failure */
398             }
399             RetPtr[i] = (HICON)pLookupIconIdFromDirectoryEx(igdata, TRUE, cxDesired, cyDesired, LR_DEFAULTCOLOR);
400           }
401
402           if (!(iconresdir=GetResDirEntryW(rootresdir,RT_ICONW,(DWORD)rootresdir,FALSE))) 
403           { WARN("No Iconresourcedirectory!\n");
404             goto end_3;         /* failure */
405           }
406
407           for (i=0;i<n;i++) 
408           { PIMAGE_RESOURCE_DIRECTORY   xresdir;
409             xresdir = GetResDirEntryW(iconresdir,(LPWSTR)(DWORD)RetPtr[i],(DWORD)rootresdir,FALSE);
410             xresdir = GetResDirEntryW(xresdir,(LPWSTR)0,(DWORD)rootresdir,TRUE);
411             idataent = (PIMAGE_RESOURCE_DATA_ENTRY)xresdir;
412             idata = NULL;
413
414             /* map virtual to address in image */
415             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++) 
416             { if (idataent->OffsetToData < pe_sections[j].VirtualAddress)
417                 continue;
418               if (idataent->OffsetToData+idataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
419                 continue;
420               idata = peimage+(idataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
421             }
422             if (!idata) 
423             { WARN("no matching real address found for icondata!\n");
424               RetPtr[i]=0;
425               continue;
426             }
427             RetPtr[i] = (HICON) pCreateIconFromResourceEx(idata,idataent->Size,TRUE,0x00030000, cxDesired, cyDesired, LR_DEFAULTCOLOR);
428           }
429           hRet = RetPtr[0];     /* return first icon */
430           goto end_3;           /* sucess */
431         }
432         goto end_1;             /* unknown filetype */
433
434 /* cleaning up (try & catch would be nicer:-) ) */
435 end_3:  UnmapViewOfFile(peimage);       /* success */
436 end_2:  CloseHandle(fmapping);
437 end_1:  _lclose( hFile);
438         return hRet;
439 }
440
441 /********************** THE ICON CACHE ********************************/
442
443 #define INVALID_INDEX -1
444
445 typedef struct
446 {       LPCSTR sSourceFile;     /* file (not path!) containing the icon */
447         DWORD dwSourceIndex;    /* index within the file, if it is a resoure ID it will be negated */
448         DWORD dwListIndex;      /* index within the iconlist */
449         DWORD dwFlags;          /* GIL_* flags */
450         DWORD dwAccessTime;
451 } SIC_ENTRY, * LPSIC_ENTRY;
452
453 static HDPA             sic_hdpa = 0;
454 static CRITICAL_SECTION SHELL32_SicCS = CRITICAL_SECTION_INIT;
455
456 /*****************************************************************************
457  * SIC_CompareEntrys                    [called by comctl32.dll]
458  *
459  * NOTES
460  *  Callback for DPA_Search
461  */
462 INT CALLBACK SIC_CompareEntrys( LPVOID p1, LPVOID p2, LPARAM lparam)
463 {       TRACE("%p %p\n", p1, p2);
464
465         if (((LPSIC_ENTRY)p1)->dwSourceIndex != ((LPSIC_ENTRY)p2)->dwSourceIndex) /* first the faster one*/
466           return 1;
467
468         if (strcasecmp(((LPSIC_ENTRY)p1)->sSourceFile,((LPSIC_ENTRY)p2)->sSourceFile))
469           return 1;
470
471         return 0;  
472 }
473 /*****************************************************************************
474  * SIC_IconAppend                       [internal]
475  *
476  * NOTES
477  *  appends a icon pair to the end of the cache
478  */
479 static INT SIC_IconAppend (LPCSTR sSourceFile, INT dwSourceIndex, HICON hSmallIcon, HICON hBigIcon)
480 {       LPSIC_ENTRY lpsice;
481         INT ret, index, index1;
482         
483         TRACE("%s %i %x %x\n", sSourceFile, dwSourceIndex, hSmallIcon ,hBigIcon);
484
485         lpsice = (LPSIC_ENTRY) SHAlloc (sizeof (SIC_ENTRY));
486
487         lpsice->sSourceFile = HEAP_strdupA (GetProcessHeap(), 0, PathFindFilenameA(sSourceFile));
488         lpsice->dwSourceIndex = dwSourceIndex;
489         
490         EnterCriticalSection(&SHELL32_SicCS);
491
492         index = pDPA_InsertPtr(sic_hdpa, 0x7fff, lpsice);
493         if ( INVALID_INDEX == index )
494         {
495           SHFree(lpsice);
496           ret = INVALID_INDEX;
497         }
498         else
499         {
500           index = pImageList_AddIcon (ShellSmallIconList, hSmallIcon);
501           index1= pImageList_AddIcon (ShellBigIconList, hBigIcon);
502
503           if (index!=index1)
504           {
505             FIXME("iconlists out of sync 0x%x 0x%x\n", index, index1);
506           }
507           lpsice->dwListIndex = index;
508           ret = lpsice->dwListIndex;
509         }
510
511         LeaveCriticalSection(&SHELL32_SicCS);
512         return ret;     
513 }
514 /****************************************************************************
515  * SIC_LoadIcon                         [internal]
516  *
517  * NOTES
518  *  gets small/big icon by number from a file
519  */
520 static INT SIC_LoadIcon (LPCSTR sSourceFile, INT dwSourceIndex)
521 {       HICON   hiconLarge=0;
522         HICON   hiconSmall=0;
523
524         ICO_ExtractIconEx(sSourceFile, &hiconLarge, dwSourceIndex, 1, 32, 32  );
525         ICO_ExtractIconEx(sSourceFile, &hiconSmall, dwSourceIndex, 1, 16, 16  );
526
527
528         if ( !hiconLarge ||  !hiconSmall)
529         {
530           WARN("failure loading icon %i from %s (%x %x)\n", dwSourceIndex, sSourceFile, hiconLarge, hiconSmall);
531           return -1;
532         }
533         return SIC_IconAppend (sSourceFile, dwSourceIndex, hiconSmall, hiconLarge);             
534 }
535 /*****************************************************************************
536  * SIC_GetIconIndex                     [internal]
537  *
538  * Parameters
539  *      sSourceFile     [IN]    filename of file containing the icon
540  *      index           [IN]    index/resID (negated) in this file
541  *
542  * NOTES
543  *  look in the cache for a proper icon. if not available the icon is taken
544  *  from the file and cached
545  */
546 INT SIC_GetIconIndex (LPCSTR sSourceFile, INT dwSourceIndex )
547 {       SIC_ENTRY sice;
548         INT ret, index = INVALID_INDEX;
549                 
550         TRACE("%s %i\n", sSourceFile, dwSourceIndex);
551
552         sice.sSourceFile = PathFindFilenameA(sSourceFile);
553         sice.dwSourceIndex = dwSourceIndex;
554         
555         EnterCriticalSection(&SHELL32_SicCS);
556
557         if (NULL != pDPA_GetPtr (sic_hdpa, 0))
558         {
559           index = pDPA_Search (sic_hdpa, &sice, -1L, SIC_CompareEntrys, 0, 0);
560         }
561
562         if ( INVALID_INDEX == index )
563         {
564           ret = SIC_LoadIcon (sSourceFile, dwSourceIndex);
565         }
566         else
567         {
568           TRACE("-- found\n");
569           ret = ((LPSIC_ENTRY)pDPA_GetPtr(sic_hdpa, index))->dwListIndex;
570         }
571
572         LeaveCriticalSection(&SHELL32_SicCS);
573         return ret;
574 }
575 /****************************************************************************
576  * SIC_LoadIcon                         [internal]
577  *
578  * NOTES
579  *  retrives the specified icon from the iconcache. if not found try's to load the icon
580  */
581 static HICON WINE_UNUSED SIC_GetIcon (LPCSTR sSourceFile, INT dwSourceIndex, BOOL bSmallIcon )
582 {       INT index;
583
584         TRACE("%s %i\n", sSourceFile, dwSourceIndex);
585
586         index = SIC_GetIconIndex(sSourceFile, dwSourceIndex);
587
588         if (INVALID_INDEX == index)
589         {
590           return INVALID_INDEX;
591         }
592
593         if (bSmallIcon)
594           return pImageList_GetIcon(ShellSmallIconList, index, ILD_NORMAL);
595         return pImageList_GetIcon(ShellBigIconList, index, ILD_NORMAL);
596         
597 }
598 /*****************************************************************************
599  * SIC_Initialize                       [internal]
600  *
601  * NOTES
602  *  hack to load the resources from the shell32.dll under a different dll name 
603  *  will be removed when the resource-compiler is ready
604  */
605 BOOL SIC_Initialize(void)
606 {
607         HICON           hSm, hLg;
608         UINT            index;
609
610         TRACE("\n");
611
612         if (sic_hdpa)   /* already initialized?*/
613           return TRUE;
614           
615         sic_hdpa = pDPA_Create(16);
616         
617         if (!sic_hdpa)
618         {
619           return(FALSE);
620         }
621
622         ShellSmallIconList = pImageList_Create(16,16,ILC_COLORDDB | ILC_MASK,0,0x20);
623         ShellBigIconList = pImageList_Create(32,32,ILC_COLORDDB | ILC_MASK,0,0x20);
624
625         pImageList_SetBkColor(ShellSmallIconList, GetSysColor(COLOR_WINDOW));
626         pImageList_SetBkColor(ShellBigIconList, GetSysColor(COLOR_WINDOW));
627
628         for (index=1; index<39; index++)
629         {
630           hSm = LoadImageA(shell32_hInstance, MAKEINTRESOURCEA(index), IMAGE_ICON, 16, 16,LR_SHARED);
631           hLg = LoadImageA(shell32_hInstance, MAKEINTRESOURCEA(index), IMAGE_ICON, 32, 32,LR_SHARED);
632
633           if(!hSm)
634           {
635             hSm = LoadImageA(shell32_hInstance, MAKEINTRESOURCEA(0), IMAGE_ICON, 16, 16,LR_SHARED);
636             hLg = LoadImageA(shell32_hInstance, MAKEINTRESOURCEA(0), IMAGE_ICON, 32, 32,LR_SHARED);
637           }
638           SIC_IconAppend ("shell32.dll", index, hSm, hLg);
639         }
640
641         TRACE("hIconSmall=%p hIconBig=%p\n",ShellSmallIconList, ShellBigIconList);
642
643         return TRUE;
644 }
645 /*************************************************************************
646  * SIC_Destroy
647  *
648  * frees the cache
649  */
650 void SIC_Destroy(void)
651 {
652         LPSIC_ENTRY lpsice;
653         int i;
654
655         TRACE("\n");
656
657         EnterCriticalSection(&SHELL32_SicCS);
658
659         if (sic_hdpa && NULL != pDPA_GetPtr (sic_hdpa, 0))
660         {
661           for (i=0; i < pDPA_GetPtrCount(sic_hdpa); ++i)
662           {
663             lpsice = pDPA_GetPtr(sic_hdpa, i); 
664             SHFree(lpsice);
665           }
666           pDPA_Destroy(sic_hdpa);
667         }
668
669         sic_hdpa = NULL;
670
671         LeaveCriticalSection(&SHELL32_SicCS);
672         DeleteCriticalSection(&SHELL32_SicCS);
673 }
674 /*************************************************************************
675  * Shell_GetImageList                   [SHELL32.71]
676  *
677  * PARAMETERS
678  *  imglist[1|2] [OUT] pointer which recive imagelist handles
679  *
680  */
681 BOOL WINAPI Shell_GetImageList(HIMAGELIST * lpBigList, HIMAGELIST * lpSmallList)
682 {       TRACE("(%p,%p)\n",lpBigList,lpSmallList);
683         if (lpBigList)
684         { *lpBigList = ShellBigIconList;
685         }
686         if (lpSmallList)
687         { *lpSmallList = ShellSmallIconList;
688         }
689
690         return TRUE;
691 }
692 /*************************************************************************
693  * PidlToSicIndex                       [INTERNAL]
694  *
695  * PARAMETERS
696  *      sh      [IN]    IShellFolder
697  *      pidl    [IN]
698  *      bBigIcon [IN]
699  *      uFlags  [IN]    GIL_*
700  *      pIndex  [OUT]   index within the SIC
701  *
702  */
703 BOOL PidlToSicIndex (
704         IShellFolder * sh,
705         LPITEMIDLIST pidl,
706         BOOL bBigIcon,
707         UINT uFlags,
708         UINT * pIndex)
709 {       
710         IExtractIconA   *ei;
711         char            szIconFile[MAX_PATH];   /* file containing the icon */
712         INT             iSourceIndex;           /* index or resID(negated) in this file */
713         BOOL            ret = FALSE;
714         UINT            dwFlags = 0;
715         
716         TRACE("sf=%p pidl=%p %s\n", sh, pidl, bBigIcon?"Big":"Small");
717
718         if (SUCCEEDED (IShellFolder_GetUIObjectOf(sh, 0, 1, &pidl, &IID_IExtractIconA, 0, (void **)&ei)))
719         {
720           if (SUCCEEDED(IExtractIconA_GetIconLocation(ei, uFlags, szIconFile, MAX_PATH, &iSourceIndex, &dwFlags)))
721           {
722             *pIndex = SIC_GetIconIndex(szIconFile, iSourceIndex);
723             ret = TRUE;
724           }
725           IExtractIconA_Release(ei);
726         }
727
728         if (INVALID_INDEX == *pIndex)   /* default icon when failed */
729           *pIndex = 1;
730
731         return ret;
732
733 }
734
735 /*************************************************************************
736  * SHMapPIDLToSystemImageListIndex      [SHELL32.77]
737  *
738  * PARAMETERS
739  *      sh      [IN]            pointer to an instance of IShellFolder 
740  *      pidl    [IN]
741  *      pIndex  [OUT][OPTIONAL] SIC index for big icon
742  *
743  */
744 UINT WINAPI SHMapPIDLToSystemImageListIndex(LPSHELLFOLDER sh, LPITEMIDLIST pidl, UINT * pIndex)
745 {
746         UINT    Index;
747
748         TRACE("(SF=%p,pidl=%p,%p)\n",sh,pidl,pIndex);
749         pdump(pidl);
750         
751         if (pIndex)
752           PidlToSicIndex ( sh, pidl, 1, 0, pIndex);
753         PidlToSicIndex ( sh, pidl, 0, 0, &Index);
754         return Index;
755 }
756
757 /*************************************************************************
758  * Shell_GetCachedImageIndex            [SHELL32.72]
759  *
760  */
761 INT WINAPI Shell_GetCachedImageIndexA(LPCSTR szPath, INT nIndex, BOOL bSimulateDoc) 
762 {
763         WARN("(%s,%08x,%08x) semi-stub.\n",debugstr_a(szPath), nIndex, bSimulateDoc);
764         return SIC_GetIconIndex(szPath, nIndex);
765 }
766
767 INT WINAPI Shell_GetCachedImageIndexW(LPCWSTR szPath, INT nIndex, BOOL bSimulateDoc) 
768 {       INT ret;
769         LPSTR sTemp = HEAP_strdupWtoA (GetProcessHeap(),0,szPath);
770         
771         WARN("(%s,%08x,%08x) semi-stub.\n",debugstr_w(szPath), nIndex, bSimulateDoc);
772
773         ret = SIC_GetIconIndex(sTemp, nIndex);
774         HeapFree(GetProcessHeap(),0,sTemp);
775         return ret;
776 }
777
778 INT WINAPI Shell_GetCachedImageIndexAW(LPCVOID szPath, INT nIndex, BOOL bSimulateDoc)
779 {       if( VERSION_OsIsUnicode())
780           return Shell_GetCachedImageIndexW(szPath, nIndex, bSimulateDoc);
781         return Shell_GetCachedImageIndexA(szPath, nIndex, bSimulateDoc);
782 }
783
784 /*************************************************************************
785  * ExtractIconEx                        [shell32.189]
786  */
787 HICON WINAPI ExtractIconExAW ( LPCVOID lpszFile, INT nIconIndex, HICON * phiconLarge, HICON * phiconSmall, UINT nIcons )
788 {       if (VERSION_OsIsUnicode())
789           return ExtractIconExW ( lpszFile, nIconIndex, phiconLarge, phiconSmall, nIcons);
790         return ExtractIconExA ( lpszFile, nIconIndex, phiconLarge, phiconSmall, nIcons);
791 }
792 /*************************************************************************
793  * ExtractIconExA                       [shell32.190]
794  * RETURNS
795  *  0 no icon found 
796  *  1 file is not valid
797  *  HICON handle of a icon (phiconLarge/Small == NULL)
798  */
799 HICON WINAPI ExtractIconExA ( LPCSTR lpszFile, INT nIconIndex, HICON * phiconLarge, HICON * phiconSmall, UINT nIcons )
800 {       HICON ret=0;
801         
802         TRACE("file=%s idx=%i %p %p num=%i\n", lpszFile, nIconIndex, phiconLarge, phiconSmall, nIcons );
803
804         if (nIconIndex==-1)     /* Number of icons requested */
805           return ICO_ExtractIconEx(lpszFile, NULL, -1, 0, 0, 0  );
806           
807         
808         if (phiconLarge)
809         { ret = ICO_ExtractIconEx(lpszFile, phiconLarge, nIconIndex, nIcons, 32, 32  );
810           if ( nIcons==1)
811           { ret = phiconLarge[0];           
812           }
813         }
814
815         /* if no pointers given and one icon expected, return the handle directly*/
816         if (!phiconLarge && ! phiconSmall && nIcons==1 )
817           phiconSmall = &ret;
818         
819         if (phiconSmall)
820         { ret = ICO_ExtractIconEx(lpszFile, phiconSmall, nIconIndex, nIcons, 16, 16  );
821           if ( nIcons==1 )
822           { ret = phiconSmall[0];
823           }
824         }
825
826         return ret;
827 }
828 /*************************************************************************
829  * ExtractIconExW                       [shell32.191]
830  */
831 HICON WINAPI ExtractIconExW ( LPCWSTR lpszFile, INT nIconIndex, HICON * phiconLarge, HICON * phiconSmall, UINT nIcons )
832 {       LPSTR sFile;
833         DWORD ret;
834         
835         TRACE("file=%s idx=%i %p %p num=%i\n", debugstr_w(lpszFile), nIconIndex, phiconLarge, phiconSmall, nIcons );
836
837         sFile = HEAP_strdupWtoA (GetProcessHeap(),0,lpszFile);
838         ret = ExtractIconExA ( sFile, nIconIndex, phiconLarge, phiconSmall, nIcons);
839         HeapFree(GetProcessHeap(),0,sFile);
840         return ret;
841 }