Fixed a race condition on RPC worker thread creation, and a typo.
[wine] / dlls / user / exticon.c
1 /*
2  *      icon extracting
3  *
4  * taken and slightly changed from shell
5  * this should replace the icon extraction code in shell32 and shell16 once
6  * it needs a serious test for compliance with the native API
7  *
8  * Copyright 2000 Juergen Schmied
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "config.h"
26
27 #include <string.h>
28 #include <stdlib.h>     /* abs() */
29 #include <sys/types.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
36 #include "winbase.h"
37 #include "windef.h"
38 #include "winerror.h"
39 #include "wingdi.h"
40 #include "winuser.h"
41 #include "wine/winbase16.h"
42 #include "cursoricon.h"
43 #include "wine/debug.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(icon);
46
47 #include "pshpack1.h"
48
49 typedef struct
50 {
51     BYTE        bWidth;          /* Width, in pixels, of the image      */
52     BYTE        bHeight;         /* Height, in pixels, of the image     */
53     BYTE        bColorCount;     /* Number of colors in image (0 if >=8bpp) */
54     BYTE        bReserved;       /* Reserved ( must be 0)               */
55     WORD        wPlanes;         /* Color Planes                        */
56     WORD        wBitCount;       /* Bits per pixel                      */
57     DWORD       dwBytesInRes;    /* How many bytes in this resource?    */
58     DWORD       dwImageOffset;   /* Where in the file is this image?    */
59 } icoICONDIRENTRY, *LPicoICONDIRENTRY;
60
61 typedef struct
62 {
63     WORD            idReserved;   /* Reserved (must be 0) */
64     WORD            idType;       /* Resource Type (RES_ICON or RES_CURSOR) */
65     WORD            idCount;      /* How many images */
66     icoICONDIRENTRY idEntries[1]; /* An entry for each image (idCount of 'em) */
67 } icoICONDIR, *LPicoICONDIR;
68
69 #include "poppack.h"
70
71 #if 0
72 static void dumpIcoDirEnty ( LPicoICONDIRENTRY entry )
73 {
74         TRACE("width = 0x%08x height = 0x%08x\n", entry->bWidth, entry->bHeight);
75         TRACE("colors = 0x%08x planes = 0x%08x\n", entry->bColorCount, entry->wPlanes);
76         TRACE("bitcount = 0x%08x bytesinres = 0x%08lx offset = 0x%08lx\n",
77         entry->wBitCount, entry->dwBytesInRes, entry->dwImageOffset);
78 }
79 static void dumpIcoDir ( LPicoICONDIR entry )
80 {
81         TRACE("type = 0x%08x count = 0x%08x\n", entry->idType, entry->idCount);
82 }
83 #endif
84
85 /**********************************************************************
86  *  find_entry_by_id
87  *
88  * Find an entry by id in a resource directory
89  * Copied from loader/pe_resource.c (FIXME: should use exported resource functions)
90  */
91 static const IMAGE_RESOURCE_DIRECTORY *find_entry_by_id( const IMAGE_RESOURCE_DIRECTORY *dir,
92                                                          WORD id, const void *root )
93 {
94     const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
95     int min, max, pos;
96
97     entry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
98     min = dir->NumberOfNamedEntries;
99     max = min + dir->NumberOfIdEntries - 1;
100     while (min <= max)
101     {
102         pos = (min + max) / 2;
103         if (entry[pos].u1.s2.Id == id)
104             return (IMAGE_RESOURCE_DIRECTORY *)((char *)root + entry[pos].u2.s3.OffsetToDirectory);
105         if (entry[pos].u1.s2.Id > id) max = pos - 1;
106         else min = pos + 1;
107     }
108     return NULL;
109 }
110
111 /**********************************************************************
112  *  find_entry_default
113  *
114  * Find a default entry in a resource directory
115  * Copied from loader/pe_resource.c (FIXME: should use exported resource functions)
116  */
117 static const IMAGE_RESOURCE_DIRECTORY *find_entry_default( const IMAGE_RESOURCE_DIRECTORY *dir,
118                                                            const void *root )
119 {
120     const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
121     entry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
122     return (IMAGE_RESOURCE_DIRECTORY *)((char *)root + entry->u2.s3.OffsetToDirectory);
123 }
124
125 /*************************************************************************
126  *                              USER32_GetResourceTable
127  */
128 static DWORD USER32_GetResourceTable(LPBYTE peimage,DWORD pesize,LPBYTE *retptr)
129 {
130         IMAGE_DOS_HEADER        * mz_header;
131
132         TRACE("%p %p\n", peimage, retptr);
133
134         *retptr = NULL;
135
136         mz_header = (IMAGE_DOS_HEADER*) peimage;
137
138         if (mz_header->e_magic != IMAGE_DOS_SIGNATURE)
139         {
140           if (mz_header->e_cblp == 1)   /* .ICO file ? */
141           {
142             *retptr = (LPBYTE)-1;       /* ICONHEADER.idType, must be 1 */
143             return 1;
144           }
145           else
146             return 0; /* failed */
147         }
148         if (mz_header->e_lfanew >= pesize) {
149             return 0; /* failed, happens with PKZIP DOS Exes for instance. */
150         }
151         if (*((DWORD*)(peimage + mz_header->e_lfanew)) == IMAGE_NT_SIGNATURE )
152           return IMAGE_NT_SIGNATURE;
153
154         if (*((WORD*)(peimage + mz_header->e_lfanew)) == IMAGE_OS2_SIGNATURE )
155         {
156           IMAGE_OS2_HEADER      * ne_header;
157
158           ne_header = (IMAGE_OS2_HEADER*)(peimage + mz_header->e_lfanew);
159
160           if (ne_header->ne_magic != IMAGE_OS2_SIGNATURE)
161             return 0;
162
163           if( (ne_header->ne_restab - ne_header->ne_rsrctab) <= sizeof(NE_TYPEINFO) )
164             *retptr = (LPBYTE)-1;
165           else
166             *retptr = peimage + mz_header->e_lfanew + ne_header->ne_rsrctab;
167
168           return IMAGE_OS2_SIGNATURE;
169         }
170         return 0; /* failed */
171 }
172 /*************************************************************************
173  *                      USER32_LoadResource
174  */
175 static BYTE * USER32_LoadResource( LPBYTE peimage, NE_NAMEINFO* pNInfo, WORD sizeShift, ULONG *uSize)
176 {
177         TRACE("%p %p 0x%08x\n", peimage, pNInfo, sizeShift);
178
179         *uSize = (DWORD)pNInfo->length << sizeShift;
180         return peimage + ((DWORD)pNInfo->offset << sizeShift);
181 }
182
183 /*************************************************************************
184  *                      ICO_LoadIcon
185  */
186 static BYTE * ICO_LoadIcon( LPBYTE peimage, LPicoICONDIRENTRY lpiIDE, ULONG *uSize)
187 {
188         TRACE("%p %p\n", peimage, lpiIDE);
189
190         *uSize = lpiIDE->dwBytesInRes;
191         return peimage + lpiIDE->dwImageOffset;
192 }
193
194 /*************************************************************************
195  *                      ICO_GetIconDirectory
196  *
197  * Reads .ico file and build phony ICONDIR struct
198  * see http://www.microsoft.com/win32dev/ui/icons.htm
199  */
200 #define HEADER_SIZE             (sizeof(CURSORICONDIR) - sizeof (CURSORICONDIRENTRY))
201 #define HEADER_SIZE_FILE        (sizeof(icoICONDIR) - sizeof (icoICONDIRENTRY))
202
203 static BYTE * ICO_GetIconDirectory( LPBYTE peimage, LPicoICONDIR* lplpiID, ULONG *uSize )
204 {
205         CURSORICONDIR   * lpcid;        /* icon resource in resource-dir format */
206         CURSORICONDIR   * lpID;         /* icon resource in resource format */
207         int             i;
208
209         TRACE("%p %p\n", peimage, lplpiID);
210
211         lpcid = (CURSORICONDIR*)peimage;
212
213         if( lpcid->idReserved || (lpcid->idType != 1) || (!lpcid->idCount) )
214           return 0;
215
216         /* allocate the phony ICONDIR structure */
217         *uSize = lpcid->idCount * sizeof(CURSORICONDIRENTRY) + HEADER_SIZE;
218         if( (lpID = (CURSORICONDIR*)HeapAlloc(GetProcessHeap(),0, *uSize) ))
219         {
220           /* copy the header */
221           lpID->idReserved = lpcid->idReserved;
222           lpID->idType = lpcid->idType;
223           lpID->idCount = lpcid->idCount;
224
225           /* copy the entries */
226           for( i=0; i < lpcid->idCount; i++ )
227           {
228             memcpy((void*)&(lpID->idEntries[i]),(void*)&(lpcid->idEntries[i]), sizeof(CURSORICONDIRENTRY) - 2);
229             lpID->idEntries[i].wResId = i;
230           }
231
232           *lplpiID = (LPicoICONDIR)peimage;
233           return (BYTE *)lpID;
234         }
235         return 0;
236 }
237
238 /*************************************************************************
239  *      ICO_ExtractIconExW              [internal]
240  *
241  * NOTES
242  *  nIcons = 0: returns number of Icons in file
243  *
244  * returns
245  *  invalid file: -1
246  *  failure:0;
247  *  success: number of icons in file (nIcons = 0) or nr of icons retrieved
248  */
249 static UINT ICO_ExtractIconExW(
250         LPCWSTR lpszExeFileName,
251         HICON * RetPtr,
252         INT nIconIndex,
253         UINT nIcons,
254         UINT cxDesired,
255         UINT cyDesired,
256         UINT *pIconId,
257         UINT flags)
258 {
259         UINT            ret = 0;
260         UINT            cx1, cx2, cy1, cy2;
261         LPBYTE          pData;
262         DWORD           sig;
263         HANDLE          hFile;
264         UINT16          iconDirCount = 0,iconCount = 0;
265         LPBYTE          peimage;
266         HANDLE          fmapping;
267         ULONG           uSize;
268         DWORD           fsizeh,fsizel;
269
270         TRACE("%s, %d, %d %p 0x%08x\n", debugstr_w(lpszExeFileName), nIconIndex, nIcons, pIconId, flags);
271
272         hFile = CreateFileW(lpszExeFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
273         if (hFile == INVALID_HANDLE_VALUE) return ret;
274         fsizel = GetFileSize(hFile,&fsizeh);
275
276         /* Map the file */
277         fmapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
278         CloseHandle(hFile);
279         if (!fmapping)
280         {
281           WARN("CreateFileMapping error %ld\n", GetLastError() );
282           return 0xFFFFFFFF;
283         }
284
285         if (!(peimage = MapViewOfFile(fmapping, FILE_MAP_READ, 0, 0, 0)))
286         {
287           WARN("MapViewOfFile error %ld\n", GetLastError() );
288           CloseHandle(fmapping);
289           return 0xFFFFFFFF;
290         }
291         CloseHandle(fmapping);
292
293         cx1 = LOWORD(cxDesired);
294         cx2 = HIWORD(cxDesired) ? HIWORD(cxDesired) : cx1;
295         cy1 = LOWORD(cyDesired);
296         cy2 = HIWORD(cyDesired) ? HIWORD(cyDesired) : cy1;
297
298         if (pIconId) /* Invalidate first icon identifier */
299                 *pIconId = 0xFFFFFFFF;
300
301         if (!pIconId) /* if no icon identifier array present use the icon handle array as intermediate storage */
302           pIconId = (UINT*)RetPtr;
303
304         sig = USER32_GetResourceTable(peimage, fsizel, &pData);
305
306 /* ico file or NE exe/dll*/
307         if (sig==IMAGE_OS2_SIGNATURE || sig==1) /* .ICO file */
308         {
309           BYTE          *pCIDir = 0;
310           NE_TYPEINFO   *pTInfo = (NE_TYPEINFO*)(pData + 2);
311           NE_NAMEINFO   *pIconStorage = NULL;
312           NE_NAMEINFO   *pIconDir = NULL;
313           LPicoICONDIR  lpiID = NULL;
314
315           TRACE("-- OS2/icon Signature (0x%08lx)\n", sig);
316
317           if (pData == (BYTE*)-1)
318           {
319             pCIDir = ICO_GetIconDirectory(peimage, &lpiID, &uSize);     /* check for .ICO file */
320             if (pCIDir)
321             {
322               iconDirCount = 1; iconCount = lpiID->idCount;
323               TRACE("-- icon found %p 0x%08lx 0x%08x 0x%08x\n", pCIDir, uSize, iconDirCount, iconCount);
324             }
325           }
326           else while (pTInfo->type_id && !(pIconStorage && pIconDir))
327           {
328             if (pTInfo->type_id == NE_RSCTYPE_GROUP_ICON)       /* find icon directory and icon repository */
329             {
330               iconDirCount = pTInfo->count;
331               pIconDir = ((NE_NAMEINFO*)(pTInfo + 1));
332               TRACE("\tfound directory - %i icon families\n", iconDirCount);
333             }
334             if (pTInfo->type_id == NE_RSCTYPE_ICON)
335             {
336               iconCount = pTInfo->count;
337               pIconStorage = ((NE_NAMEINFO*)(pTInfo + 1));
338               TRACE("\ttotal icons - %i\n", iconCount);
339             }
340             pTInfo = (NE_TYPEINFO *)((char*)(pTInfo+1)+pTInfo->count*sizeof(NE_NAMEINFO));
341           }
342
343           if ((pIconStorage && pIconDir) || lpiID)        /* load resources and create icons */
344           {
345             if (nIcons == 0)
346             {
347               ret = iconDirCount;
348               if (lpiID && pCIDir)      /* *.ico file, deallocate heap pointer*/
349                 HeapFree(GetProcessHeap(), 0, pCIDir);
350             }
351             else if (nIconIndex < iconDirCount)
352             {
353               UINT16   i, icon;
354               if (nIcons > iconDirCount - nIconIndex)
355                 nIcons = iconDirCount - nIconIndex;
356
357               for (i = 0; i < nIcons; i++)
358               {
359                 /* .ICO files have only one icon directory */
360                 if (lpiID == NULL)      /* not *.ico */
361                   pCIDir = USER32_LoadResource(peimage, pIconDir + i + nIconIndex, *(WORD*)pData, &uSize);
362                 pIconId[i] = LookupIconIdFromDirectoryEx(pCIDir, TRUE, (i & 1) ? cx2 : cx1, (i & 1) ? cy2 : cy1, flags);
363               }
364               if (lpiID && pCIDir)      /* *.ico file, deallocate heap pointer*/
365                 HeapFree(GetProcessHeap(), 0, pCIDir);
366
367               for (icon = 0; icon < nIcons; icon++)
368               {
369                 pCIDir = NULL;
370                 if (lpiID)
371                   pCIDir = ICO_LoadIcon(peimage, lpiID->idEntries + (int)pIconId[icon], &uSize);
372                 else
373                   for (i = 0; i < iconCount; i++)
374                     if (pIconStorage[i].id == ((int)pIconId[icon] | 0x8000) )
375                       pCIDir = USER32_LoadResource(peimage, pIconStorage + i, *(WORD*)pData, &uSize);
376
377                 if (pCIDir)
378                   RetPtr[icon] = (HICON)CreateIconFromResourceEx(pCIDir, uSize, TRUE, 0x00030000,
379                                                                  (icon & 1) ? cx2 : cx1, (icon & 1) ? cy2 : cy1, flags);
380                 else
381                   RetPtr[icon] = 0;
382               }
383               ret = icon;       /* return number of retrieved icons */
384             }
385           }
386         }
387 /* end ico file */
388
389 /* exe/dll */
390         else if( sig == IMAGE_NT_SIGNATURE )
391         {
392           LPBYTE                idata,igdata;
393           PIMAGE_DOS_HEADER     dheader;
394           PIMAGE_NT_HEADERS     pe_header;
395           PIMAGE_SECTION_HEADER pe_sections;
396           const IMAGE_RESOURCE_DIRECTORY *rootresdir,*iconresdir,*icongroupresdir;
397           const IMAGE_RESOURCE_DATA_ENTRY *idataent,*igdataent;
398           const IMAGE_RESOURCE_DIRECTORY_ENTRY *xresent;
399           UINT  i, j;
400
401           dheader = (PIMAGE_DOS_HEADER)peimage;
402           pe_header = (PIMAGE_NT_HEADERS)(peimage+dheader->e_lfanew);     /* it is a pe header, USER32_GetResourceTable checked that */
403           pe_sections = (PIMAGE_SECTION_HEADER)(((char*)pe_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER)
404                                                 + pe_header->FileHeader.SizeOfOptionalHeader);
405           rootresdir = NULL;
406
407           /* search for the root resource directory */
408           for (i=0;i<pe_header->FileHeader.NumberOfSections;i++)
409           {
410             if (pe_sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
411               continue;
412             if (fsizel < pe_sections[i].PointerToRawData+pe_sections[i].SizeOfRawData) {
413               FIXME("File %s too short (section is at %ld bytes, real size is %ld)\n",
414                       debugstr_w(lpszExeFileName),
415                       pe_sections[i].PointerToRawData+pe_sections[i].SizeOfRawData,
416                       fsizel
417               );
418               goto end;
419             }
420             /* FIXME: doesn't work when the resources are not in a separate section */
421             if (pe_sections[i].VirtualAddress == pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress)
422             {
423               rootresdir = (PIMAGE_RESOURCE_DIRECTORY)(peimage+pe_sections[i].PointerToRawData);
424               break;
425             }
426           }
427
428           if (!rootresdir)
429           {
430             WARN("haven't found section for resource directory.\n");
431             goto end;           /* failure */
432           }
433
434           /* search for the group icon directory */
435           if (!(icongroupresdir = find_entry_by_id(rootresdir, LOWORD(RT_GROUP_ICONW), rootresdir)))
436           {
437             WARN("No Icongroupresourcedirectory!\n");
438             goto end;           /* failure */
439           }
440           iconDirCount = icongroupresdir->NumberOfNamedEntries + icongroupresdir->NumberOfIdEntries;
441
442           /* only number of icons requested */
443           if( nIcons == 0 )
444           {
445             ret = iconDirCount;
446             goto end;           /* success */
447           }
448
449           if( nIconIndex < 0 )
450           {
451             /* search resource id */
452             int n = 0;
453             int iId = abs(nIconIndex);
454             PIMAGE_RESOURCE_DIRECTORY_ENTRY xprdeTmp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(icongroupresdir+1);
455
456             while(n<iconDirCount && xprdeTmp)
457             {
458               if(xprdeTmp->u1.s2.Id ==  iId)
459               {
460                   nIconIndex = n;
461                   break;
462               }
463               n++;
464               xprdeTmp++;
465             }
466             if (nIconIndex < 0)
467             {
468               WARN("resource id %d not found\n", iId);
469               goto end;         /* failure */
470             }
471           }
472           else
473           {
474             /* check nIconIndex to be in range */
475             if (nIconIndex >= iconDirCount)
476             {
477               WARN("nIconIndex %d is larger than iconDirCount %d\n",nIconIndex,iconDirCount);
478               goto end;         /* failure */
479             }
480           }
481
482           /* assure we don't get too much */
483           if( nIcons > iconDirCount - nIconIndex )
484             nIcons = iconDirCount - nIconIndex;
485
486           /* starting from specified index */
487           xresent = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(icongroupresdir+1) + nIconIndex;
488
489           for (i=0; i < nIcons; i++,xresent++)
490           {
491             const IMAGE_RESOURCE_DIRECTORY *resdir;
492
493             /* go down this resource entry, name */
494             resdir = (PIMAGE_RESOURCE_DIRECTORY)((DWORD)rootresdir+(xresent->u2.s3.OffsetToDirectory));
495
496             /* default language (0) */
497             resdir = find_entry_default(resdir,rootresdir);
498             igdataent = (PIMAGE_RESOURCE_DATA_ENTRY)resdir;
499
500             /* lookup address in mapped image for virtual address */
501             igdata = NULL;
502
503             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++)
504             {
505               if (igdataent->OffsetToData < pe_sections[j].VirtualAddress)
506                 continue;
507               if (igdataent->OffsetToData+igdataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
508                 continue;
509
510               if (igdataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData+igdataent->Size > fsizel) {
511                 FIXME("overflow in PE lookup (%s has len %ld, have offset %ld), short file?\n", debugstr_w(lpszExeFileName), fsizel,
512                            igdataent->OffsetToData - pe_sections[j].VirtualAddress + pe_sections[j].PointerToRawData + igdataent->Size);
513                 goto end; /* failure */
514               }
515               igdata = peimage+(igdataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
516             }
517
518             if (!igdata)
519             {
520               FIXME("no matching real address for icongroup!\n");
521               goto end; /* failure */
522             }
523             pIconId[i] = LookupIconIdFromDirectoryEx(igdata, TRUE, (i & 1) ? cx2 : cx1, (i & 1) ? cy2 : cy1, flags);
524           }
525
526           if (!(iconresdir=find_entry_by_id(rootresdir,LOWORD(RT_ICONW),rootresdir)))
527           {
528             WARN("No Iconresourcedirectory!\n");
529             goto end;           /* failure */
530           }
531
532           for (i=0; i<nIcons; i++)
533           {
534             const IMAGE_RESOURCE_DIRECTORY *xresdir;
535             xresdir = find_entry_by_id(iconresdir, LOWORD(pIconId[i]), rootresdir);
536             xresdir = find_entry_default(xresdir, rootresdir);
537             idataent = (PIMAGE_RESOURCE_DATA_ENTRY)xresdir;
538             idata = NULL;
539
540             /* map virtual to address in image */
541             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++)
542             {
543               if (idataent->OffsetToData < pe_sections[j].VirtualAddress)
544                 continue;
545               if (idataent->OffsetToData+idataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
546                 continue;
547               idata = peimage+(idataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
548             }
549             if (!idata)
550             {
551               WARN("no matching real address found for icondata!\n");
552               RetPtr[i]=0;
553               continue;
554             }
555             RetPtr[i] = (HICON) CreateIconFromResourceEx(idata,idataent->Size,TRUE,0x00030000,
556                                                          (i & 1) ? cx2 : cx1, (i & 1) ? cy2 : cy1, flags);
557           }
558           ret = i;      /* return number of retrieved icons */
559         }                       /* if(sig == IMAGE_NT_SIGNATURE) */
560
561 end:
562         UnmapViewOfFile(peimage);       /* success */
563         return ret;
564 }
565
566 /***********************************************************************
567  *           PrivateExtractIconsW                       [USER32.@]
568  *
569  * NOTES
570  *  If HIWORD(sizeX) && HIWORD(sizeY) 2 * ((nIcons + 1) MOD 2) icons are
571  *  returned, with the LOWORD size icon first and the HIWORD size icon
572  *  second.
573  *  Also the Windows equivalent does extract icons in a strange way if
574  *  nIndex is negative. Our implementation treats a negative nIndex as
575  *  looking for that resource identifier for the first icon to retrieve.
576  *
577  * FIXME:
578  *  should also support 16 bit EXE + DLLs, cursor and animated cursor as
579  *  well as bitmap files.
580  */
581
582 UINT WINAPI PrivateExtractIconsW (
583         LPCWSTR lpwstrFile,
584         int nIndex,
585         int sizeX,
586         int sizeY,
587         HICON * phicon, /* [out] pointer to array of nIcons HICON handles */
588         UINT* pIconId,  /* [out] pointer to array of nIcons icon identifiers or NULL */
589         UINT nIcons,    /* [in] number of icons to retrieve */
590         UINT flags )    /* [in] LR_* flags used by LoadImage */
591 {
592         TRACE("%s %d %dx%d %p %p %d 0x%08x\n",
593               debugstr_w(lpwstrFile), nIndex, sizeX, sizeY, phicon, pIconId, nIcons, flags);
594
595         if ((nIcons & 1) && HIWORD(sizeX) && HIWORD(sizeY))
596         {
597           WARN("Uneven number %d of icons requested for small and large icons!", nIcons);
598         }
599         return ICO_ExtractIconExW(lpwstrFile, phicon, nIndex, nIcons, sizeX, sizeY, pIconId, flags);
600 }
601
602 /***********************************************************************
603  *           PrivateExtractIconsA                       [USER32.@]
604  */
605
606 UINT WINAPI PrivateExtractIconsA (
607         LPCSTR lpstrFile,
608         int nIndex,
609         int sizeX,
610         int sizeY,
611         HICON * phicon, /* [out] pointer to array of nIcons HICON handles */
612         UINT* piconid,  /* [out] pointer to array of nIcons icon identifiers or NULL */
613         UINT nIcons,    /* [in] number of icons to retrieve */
614         UINT flags )    /* [in] LR_* flags used by LoadImage */
615 {
616     UINT ret;
617     INT len = MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, NULL, 0);
618     LPWSTR lpwstrFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
619
620     MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, lpwstrFile, len);
621     ret = PrivateExtractIconsW(lpwstrFile, nIndex, sizeX, sizeY, phicon, piconid, nIcons, flags);
622
623     HeapFree(GetProcessHeap(), 0, lpwstrFile);
624     return ret;
625 }
626
627 /***********************************************************************
628  *           PrivateExtractIconExW                      [USER32.@]
629  * NOTES
630  *  if nIndex == -1 it returns the number of icons in any case !!!
631  */
632 UINT WINAPI PrivateExtractIconExW (
633         LPCWSTR lpwstrFile,
634         int nIndex,
635         HICON * phIconLarge,
636         HICON * phIconSmall,
637         UINT nIcons )
638 {
639         DWORD cyicon, cysmicon, cxicon, cxsmicon;
640         UINT ret = 0;
641
642         TRACE("%s %d %p %p %d\n",
643         debugstr_w(lpwstrFile),nIndex,phIconLarge, phIconSmall, nIcons);
644
645         if (nIndex == -1)
646           /* get the number of icons */
647           return ICO_ExtractIconExW(lpwstrFile, NULL, 0, 0, 0, 0, NULL, LR_DEFAULTCOLOR);
648
649         if (nIcons == 1 && phIconSmall && phIconLarge)
650         {
651           HICON hIcon[2];
652           cxicon = GetSystemMetrics(SM_CXICON);
653           cyicon = GetSystemMetrics(SM_CYICON);
654           cxsmicon = GetSystemMetrics(SM_CXSMICON);
655           cysmicon = GetSystemMetrics(SM_CYSMICON);
656
657           ret = ICO_ExtractIconExW(lpwstrFile, (HICON*) &hIcon, nIndex, 2, cxicon | (cxsmicon<<16),
658                                    cyicon | (cysmicon<<16), NULL, LR_DEFAULTCOLOR);
659           *phIconLarge = hIcon[0];
660           *phIconSmall = hIcon[1];
661           return ret;
662         }
663
664         if (phIconSmall)
665         {
666           /* extract n small icons */
667           cxsmicon = GetSystemMetrics(SM_CXSMICON);
668           cysmicon = GetSystemMetrics(SM_CYSMICON);
669           ret = ICO_ExtractIconExW(lpwstrFile, phIconSmall, nIndex, nIcons, cxsmicon,
670                                    cysmicon, NULL, LR_DEFAULTCOLOR);
671         }
672        if (phIconLarge)
673         {
674           /* extract n large icons */
675           cxicon = GetSystemMetrics(SM_CXICON);
676           cyicon = GetSystemMetrics(SM_CYICON);
677          ret = ICO_ExtractIconExW(lpwstrFile, phIconLarge, nIndex, nIcons, cxicon,
678                                    cyicon, NULL, LR_DEFAULTCOLOR);
679         }
680         return ret;
681 }
682
683 /***********************************************************************
684  *           PrivateExtractIconExA                      [USER32.@]
685  */
686 UINT WINAPI PrivateExtractIconExA (
687         LPCSTR lpstrFile,
688         int nIndex,
689         HICON * phIconLarge,
690         HICON * phIconSmall,
691         UINT nIcons )
692 {
693         UINT ret;
694         INT len = MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, NULL, 0);
695         LPWSTR lpwstrFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
696
697         TRACE("%s %d %p %p %d\n", lpstrFile, nIndex, phIconLarge, phIconSmall, nIcons);
698
699         MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, lpwstrFile, len);
700         ret = PrivateExtractIconExW(lpwstrFile, nIndex, phIconLarge, phIconSmall, nIcons);
701         HeapFree(GetProcessHeap(), 0, lpwstrFile);
702         return ret;
703 }