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