quartz: Make dwSamplesProcessed a longlong.
[wine] / programs / winemenubuilder / winemenubuilder.c
1 /*
2  * Helper program to build unix menu entries
3  *
4  * Copyright 1997 Marcus Meissner
5  * Copyright 1998 Juergen Schmied
6  * Copyright 2003 Mike McCormack for CodeWeavers
7  * Copyright 2004 Dmitry Timoshkov
8  * Copyright 2005 Bill Medland
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  *
24  *
25  *  This program is used to replicate the Windows desktop and start menu
26  * into the native desktop's copies.  Desktop entries are merged directly
27  * into the native desktop.  The Windows Start Menu corresponds to a Wine
28  * entry within the native "start" menu and replicates the whole tree
29  * structure of the Windows Start Menu.  Currently it does not differentiate
30  * between the user's desktop/start menu and the "All Users" copies.
31  *
32  *  This program will read a Windows shortcut file using the IShellLink
33  * interface, then invoke wineshelllink with the appropriate arguments
34  * to create a KDE/Gnome menu entry for the shortcut.
35  *
36  *  winemenubuilder [ -w ] <shortcut.lnk>
37  *
38  *  If the -w parameter is passed, and the shortcut cannot be created,
39  * this program will wait for the parent process to finish and then try
40  * again. This covers the case when a ShortCut is created before the
41  * executable containing its icon.
42  *
43  * TODO
44  *  Handle data lnk files. There is no icon in the file; the icon is in 
45  * the handler for the file type (or pointed to by the lnk file).  Also it 
46  * might be better to use a native handler (e.g. a native acroread for pdf
47  * files).  
48  *  Differentiate between the user's entries and the "All Users" entries.
49  * If it is possible to add the desktop files to the native system's
50  * shared location for an "All Users" entry then do so.  As a suggestion the
51  * shared menu Wine base could be writable to the wine group, or a wineadm 
52  * group.
53  * 
54  */
55
56 #include "config.h"
57 #include "wine/port.h"
58
59 #include <ctype.h>
60 #include <stdio.h>
61 #include <string.h>
62 #ifdef HAVE_UNISTD_H
63 #include <unistd.h>
64 #endif
65 #include <errno.h>
66 #include <stdarg.h>
67
68 #define COBJMACROS
69
70 #include <windows.h>
71 #include <shlobj.h>
72 #include <objidl.h>
73 #include <shlguid.h>
74 #include <appmgmt.h>
75 #include <tlhelp32.h>
76
77 #include "wine/unicode.h"
78 #include "wine/debug.h"
79 #include "wine/library.h"
80 #include "wine.xpm"
81
82 #ifdef HAVE_PNG_H
83 #undef FAR
84 #include <png.h>
85 #endif
86
87 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
88
89 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
90                                (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
91 #define in_startmenu(csidl)   ((csidl)==CSIDL_STARTMENU || \
92                                (csidl)==CSIDL_COMMON_STARTMENU)
93         
94 /* link file formats */
95
96 #include "pshpack1.h"
97
98 typedef struct
99 {
100     BYTE bWidth;
101     BYTE bHeight;
102     BYTE bColorCount;
103     BYTE bReserved;
104     WORD wPlanes;
105     WORD wBitCount;
106     DWORD dwBytesInRes;
107     WORD nID;
108 } GRPICONDIRENTRY;
109
110 typedef struct
111 {
112     WORD idReserved;
113     WORD idType;
114     WORD idCount;
115     GRPICONDIRENTRY idEntries[1];
116 } GRPICONDIR;
117
118 typedef struct
119 {
120     BYTE bWidth;
121     BYTE bHeight;
122     BYTE bColorCount;
123     BYTE bReserved;
124     WORD wPlanes;
125     WORD wBitCount;
126     DWORD dwBytesInRes;
127     DWORD dwImageOffset;
128 } ICONDIRENTRY;
129
130 typedef struct
131 {
132     WORD idReserved;
133     WORD idType;
134     WORD idCount;
135 } ICONDIR;
136
137
138 #include "poppack.h"
139
140 typedef struct
141 {
142         HRSRC *pResInfo;
143         int   nIndex;
144 } ENUMRESSTRUCT;
145
146
147 /* Icon extraction routines
148  *
149  * FIXME: should use PrivateExtractIcons and friends
150  * FIXME: should not use stdio
151  */
152
153 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
154
155 /* PNG-specific code */
156 #ifdef SONAME_LIBPNG
157
158 static void *libpng_handle;
159 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
160 MAKE_FUNCPTR(png_create_info_struct);
161 MAKE_FUNCPTR(png_create_write_struct);
162 MAKE_FUNCPTR(png_destroy_write_struct);
163 MAKE_FUNCPTR(png_init_io);
164 MAKE_FUNCPTR(png_set_bgr);
165 MAKE_FUNCPTR(png_set_text);
166 MAKE_FUNCPTR(png_set_IHDR);
167 MAKE_FUNCPTR(png_write_end);
168 MAKE_FUNCPTR(png_write_info);
169 MAKE_FUNCPTR(png_write_row);
170 #undef MAKE_FUNCPTR
171
172 static void *load_libpng(void)
173 {
174     if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
175     {
176 #define LOAD_FUNCPTR(f) \
177     if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
178         libpng_handle = NULL; \
179         return NULL; \
180     }
181         LOAD_FUNCPTR(png_create_info_struct);
182         LOAD_FUNCPTR(png_create_write_struct);
183         LOAD_FUNCPTR(png_destroy_write_struct);
184         LOAD_FUNCPTR(png_init_io);
185         LOAD_FUNCPTR(png_set_bgr);
186         LOAD_FUNCPTR(png_set_IHDR);
187         LOAD_FUNCPTR(png_set_text);
188         LOAD_FUNCPTR(png_write_end);
189         LOAD_FUNCPTR(png_write_info);
190         LOAD_FUNCPTR(png_write_row);
191 #undef LOAD_FUNCPTR
192     }
193     return libpng_handle;
194 }
195
196 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
197 {
198     static const char comment_key[] = "Created from";
199     FILE *fp;
200     png_structp png_ptr;
201     png_infop info_ptr;
202     png_text comment;
203     int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
204     BYTE *pXOR, *row;
205     const BYTE *pAND = NULL;
206     int nWidth  = pIcon->bmiHeader.biWidth;
207     int nHeight = pIcon->bmiHeader.biHeight;
208     int nBpp    = pIcon->bmiHeader.biBitCount;
209
210     switch (nBpp)
211     {
212     case 32:
213         color_type |= PNG_COLOR_MASK_ALPHA;
214         /* fall through */
215     case 24:
216         color_type |= PNG_COLOR_MASK_COLOR;
217         break;
218     default:
219         return FALSE;
220     }
221
222     if (!libpng_handle && !load_libpng())
223     {
224         WINE_WARN("Unable to load libpng\n");
225         return FALSE;
226     }
227
228     if (!(fp = fopen(png_filename, "w")))
229     {
230         WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
231         return FALSE;
232     }
233
234     nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
235     nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
236     pXOR = (BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
237     if (nHeight > nWidth)
238     {
239         nHeight /= 2;
240         pAND = pXOR + nHeight * nXORWidthBytes;
241     }
242
243     /* image and mask are upside down reversed */
244     row = pXOR + (nHeight - 1) * nXORWidthBytes;
245
246     /* Apply mask if present */
247     if (pAND)
248     {
249         RGBQUAD bgColor;
250
251         /* top left corner */
252         bgColor.rgbRed   = row[0];
253         bgColor.rgbGreen = row[1];
254         bgColor.rgbBlue  = row[2];
255         bgColor.rgbReserved = 0;
256
257         for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
258             for (j = 0; j < nWidth; j++, row += nBpp >> 3)
259                 if (MASK(j, i))
260                 {
261                     RGBQUAD *pixel = (RGBQUAD *)row;
262                     pixel->rgbBlue  = bgColor.rgbBlue;
263                     pixel->rgbGreen = bgColor.rgbGreen;
264                     pixel->rgbRed   = bgColor.rgbRed;
265                     if (nBpp == 32)
266                         pixel->rgbReserved = bgColor.rgbReserved;
267                 }
268     }
269
270     comment.text = NULL;
271
272     if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
273         !(info_ptr = ppng_create_info_struct(png_ptr)))
274         goto error;
275
276     if (setjmp(png_jmpbuf(png_ptr)))
277     {
278         /* All future errors jump here */
279         WINE_ERR("png error\n");
280         goto error;
281     }
282
283     ppng_init_io(png_ptr, fp);
284     ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
285                   color_type,
286                   PNG_INTERLACE_NONE,
287                   PNG_COMPRESSION_TYPE_DEFAULT,
288                   PNG_FILTER_TYPE_DEFAULT);
289
290     /* Set comment */
291     comment.compression = PNG_TEXT_COMPRESSION_NONE;
292     comment.key = (png_charp)comment_key;
293     i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
294     comment.text = HeapAlloc(GetProcessHeap(), 0, i);
295     WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
296     comment.text_length = i - 1;
297     ppng_set_text(png_ptr, info_ptr, &comment, 1);
298
299
300     ppng_write_info(png_ptr, info_ptr);
301     ppng_set_bgr(png_ptr);
302     for (i = nHeight - 1; i >= 0 ; i--)
303         ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
304     ppng_write_end(png_ptr, info_ptr);
305
306     ppng_destroy_write_struct(&png_ptr, &info_ptr);
307     if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
308     fclose(fp);
309     HeapFree(GetProcessHeap(), 0, comment.text);
310     return TRUE;
311
312  error:
313     if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
314     fclose(fp);
315     unlink(png_filename);
316     HeapFree(GetProcessHeap(), 0, comment.text);
317     return FALSE;
318 }
319 #endif /* SONAME_LIBPNG */
320
321 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
322 {
323     FILE *fXPMFile;
324     int nHeight;
325     int nXORWidthBytes;
326     int nANDWidthBytes;
327     BOOL b8BitColors;
328     int nColors;
329     const BYTE *pXOR;
330     const BYTE *pAND;
331     BOOL aColorUsed[256] = {0};
332     int nColorsUsed = 0;
333     int i,j;
334     char *comment;
335
336     if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
337     {
338         WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
339         return FALSE;
340     }
341
342     if (!(fXPMFile = fopen(szXPMFileName, "w")))
343     {
344         WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
345         return FALSE;
346     }
347
348     i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
349     comment = HeapAlloc(GetProcessHeap(), 0, i);
350     WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
351
352     nHeight = pIcon->bmiHeader.biHeight / 2;
353     nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
354                           + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
355     nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
356                           + ((pIcon->bmiHeader.biWidth % 32) > 0));
357     b8BitColors = pIcon->bmiHeader.biBitCount == 8;
358     nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
359         : 1 << pIcon->bmiHeader.biBitCount;
360     pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
361     pAND = pXOR + nHeight * nXORWidthBytes;
362
363 #define COLOR(x,y) (b8BitColors ? pXOR[(x) + (nHeight - (y) - 1) * nXORWidthBytes] : (x) % 2 ? pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF : (pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF0) >> 4)
364
365     for (i = 0; i < nHeight; i++) {
366         for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
367             if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
368             {
369                 aColorUsed[COLOR(j,i)] = TRUE;
370                 nColorsUsed++;
371             }
372         }
373     }
374
375     if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
376         goto error;
377     if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
378                 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
379         goto error;
380
381     for (i = 0; i < nColors; i++) {
382         if (aColorUsed[i])
383             if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
384                         pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
385                 goto error;
386     }
387     if (fprintf(fXPMFile, "\"   c None\"") <= 0)
388         goto error;
389
390     for (i = 0; i < nHeight; i++)
391     {
392         if (fprintf(fXPMFile, ",\n\"") <= 0)
393             goto error;
394         for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
395         {
396             if MASK(j,i)
397                 {
398                     if (fprintf(fXPMFile, "  ") <= 0)
399                         goto error;
400                 }
401             else
402                 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
403                     goto error;
404         }
405         if (fprintf(fXPMFile, "\"") <= 0)
406             goto error;
407     }
408     if (fprintf(fXPMFile, "};\n") <= 0)
409         goto error;
410
411 #undef MASK
412 #undef COLOR
413
414     HeapFree(GetProcessHeap(), 0, comment);
415     fclose(fXPMFile);
416     return TRUE;
417
418  error:
419     HeapFree(GetProcessHeap(), 0, comment);
420     fclose(fXPMFile);
421     unlink( szXPMFileName );
422     return FALSE;
423 }
424
425 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
426 {
427     ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
428
429     if (!sEnumRes->nIndex--)
430     {
431         *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
432         return FALSE;
433     }
434     else
435         return TRUE;
436 }
437
438 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
439 {
440     HMODULE hModule;
441     HRSRC hResInfo;
442     LPCWSTR lpName = NULL;
443     HGLOBAL hResData;
444     GRPICONDIR *pIconDir;
445     BITMAPINFO *pIcon;
446     ENUMRESSTRUCT sEnumRes;
447     int nMax = 0;
448     int nMaxBits = 0;
449     int i;
450     BOOL ret = FALSE;
451
452     hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
453     if (!hModule)
454     {
455         WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
456                  wine_dbgstr_w(szFileName), GetLastError());
457         return FALSE;
458     }
459
460     if (nIndex < 0)
461     {
462         hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
463         WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
464                    wine_dbgstr_w(szFileName), hResInfo, GetLastError());
465     }
466     else
467     {
468         hResInfo=NULL;
469         sEnumRes.pResInfo = &hResInfo;
470         sEnumRes.nIndex = nIndex;
471         if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
472                                 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
473             sEnumRes.nIndex != 0)
474         {
475             WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
476         }
477     }
478
479     if (hResInfo)
480     {
481         if ((hResData = LoadResource(hModule, hResInfo)))
482         {
483             if ((pIconDir = LockResource(hResData)))
484             {
485                 for (i = 0; i < pIconDir->idCount; i++)
486                 {
487                     if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
488                     {
489                         nMaxBits = pIconDir->idEntries[i].wBitCount;
490
491                         if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
492                         {
493                             lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
494                             nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
495                         }
496                     }               
497                 }
498             }
499
500             FreeResource(hResData);
501         }
502     }
503     else
504     {
505         WINE_WARN("found no icon\n");
506         FreeLibrary(hModule);
507         return FALSE;
508     }
509  
510     if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
511     {
512         if ((hResData = LoadResource(hModule, hResInfo)))
513         {
514             if ((pIcon = LockResource(hResData)))
515             {
516 #ifdef SONAME_LIBPNG
517                 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
518                     ret = TRUE;
519                 else
520 #endif
521                 {
522                     memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
523                     if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
524                         ret = TRUE;
525                 }
526             }
527
528             FreeResource(hResData);
529         }
530     }
531
532     FreeLibrary(hModule);
533     return ret;
534 }
535
536 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
537 {
538     if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
539         !extract_icon16(szFileName, szXPMFileName)*/)
540         return FALSE;
541     return TRUE;
542 }
543
544 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
545 {
546     FILE *fICOFile = NULL;
547     ICONDIR iconDir;
548     ICONDIRENTRY *pIconDirEntry = NULL;
549     int nMax = 0, nMaxBits = 0;
550     int nIndex = 0;
551     void *pIcon = NULL;
552     int i;
553     char *filename = NULL;
554
555     filename = wine_get_unix_file_name(szFileName);
556     if (!(fICOFile = fopen(filename, "r")))
557     {
558         WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
559         goto error;
560     }
561
562     if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
563         (iconDir.idReserved != 0) || (iconDir.idType != 1))
564     {
565         WINE_WARN("Invalid ico file format\n");
566         goto error;
567     }
568
569     if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
570         goto error;
571     if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
572         goto error;
573
574     for (i = 0; i < iconDir.idCount; i++)
575     {
576         WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
577         if (pIconDirEntry[i].wBitCount >= nMaxBits &&
578             (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
579         {
580             nIndex = i;
581             nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
582             nMaxBits = pIconDirEntry[i].wBitCount;
583         }
584     }
585     WINE_TRACE("Selected: %d\n", nIndex);
586
587     if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
588         goto error;
589     if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
590         goto error;
591     if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
592         goto error;
593
594
595     /* Prefer PNG over XPM */
596 #ifdef SONAME_LIBPNG
597     if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
598 #endif
599     {
600         memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
601         if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
602             goto error;
603     }
604
605     HeapFree(GetProcessHeap(), 0, pIcon);
606     HeapFree(GetProcessHeap(), 0, pIconDirEntry);
607     fclose(fICOFile);
608     HeapFree(GetProcessHeap(), 0, filename);
609     return 1;
610
611  error:
612     HeapFree(GetProcessHeap(), 0, pIcon);
613     HeapFree(GetProcessHeap(), 0, pIconDirEntry);
614     if (fICOFile) fclose(fICOFile);
615     HeapFree(GetProcessHeap(), 0, filename);
616     return 0;
617 }
618
619 static BOOL create_default_icon( const char *filename, const char* comment )
620 {
621     FILE *fXPM;
622     unsigned int i;
623
624     if (!(fXPM = fopen(filename, "w"))) return FALSE;
625     if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
626         goto error;
627     for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
628         if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
629             goto error;
630     }
631     if (fprintf( fXPM, "};\n" ) <=0)
632         goto error;
633     fclose( fXPM );
634     return TRUE;
635  error:
636     fclose( fXPM );
637     unlink( filename );
638     return FALSE;
639
640 }
641
642 static unsigned short crc16(const char* string)
643 {
644     unsigned short crc = 0;
645     int i, j, xor_poly;
646
647     for (i = 0; string[i] != 0; i++)
648     {
649         char c = string[i];
650         for (j = 0; j < 8; c >>= 1, j++)
651         {
652             xor_poly = (c ^ crc) & 1;
653             crc >>= 1;
654             if (xor_poly)
655                 crc ^= 0xa001;
656         }
657     }
658     return crc;
659 }
660
661 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
662 static char *extract_icon( LPCWSTR path, int index, BOOL bWait )
663 {
664     unsigned short crc;
665     char *iconsdir, *ico_path, *ico_name, *xpm_path;
666     char* s;
667     HKEY hkey;
668     int n;
669
670     /* Where should we save the icon? */
671     WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
672     iconsdir=NULL;  /* Default is no icon */
673     /* @@ Wine registry key: HKCU\Software\Wine\WineMenuBuilder */
674     if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\WineMenuBuilder", &hkey ))
675     {
676         static const WCHAR IconsDirW[] = {'I','c','o','n','s','D','i','r',0};
677         LPWSTR iconsdirW;
678         DWORD size = 0;
679
680         if (!RegQueryValueExW(hkey, IconsDirW, 0, NULL, NULL, &size))
681         {
682             iconsdirW = HeapAlloc(GetProcessHeap(), 0, size);
683             RegQueryValueExW(hkey, IconsDirW, 0, NULL, (LPBYTE)iconsdirW, &size);
684
685             if (!(iconsdir = wine_get_unix_file_name(iconsdirW)))
686             {
687                 int n = WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, NULL, 0, NULL, NULL);
688                 iconsdir = HeapAlloc(GetProcessHeap(), 0, n);
689                 WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, iconsdir, n, NULL, NULL);
690             }
691             HeapFree(GetProcessHeap(), 0, iconsdirW);
692         }
693         RegCloseKey( hkey );
694     }
695
696     if (!iconsdir)
697     {
698         WCHAR path[MAX_PATH];
699         if (GetTempPathW(MAX_PATH, path))
700             iconsdir = wine_get_unix_file_name(path);
701         if (!iconsdir)
702         {
703             WINE_TRACE("no IconsDir\n");
704             return NULL;  /* No icon created */
705         }
706     }
707     
708     if (!*iconsdir)
709     {
710         WINE_TRACE("icon generation disabled\n");
711         HeapFree(GetProcessHeap(), 0, iconsdir);
712         return NULL;  /* No icon created */
713     }
714
715     /* Determine the icon base name */
716     n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
717     ico_path = HeapAlloc(GetProcessHeap(), 0, n);
718     WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
719     s=ico_name=ico_path;
720     while (*s!='\0') {
721         if (*s=='/' || *s=='\\') {
722             *s='\\';
723             ico_name=s;
724         } else {
725             *s=tolower(*s);
726         }
727         s++;
728     }
729     if (*ico_name=='\\') *ico_name++='\0';
730     s=strrchr(ico_name,'.');
731     if (s) *s='\0';
732
733     /* Compute the source-path hash */
734     crc=crc16(ico_path);
735
736     /* Try to treat the source file as an exe */
737     xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
738     sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
739     if (ExtractFromEXEDLL( path, index, xpm_path ))
740         goto end;
741
742     /* Must be something else, ignore the index in that case */
743     sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
744     if (ExtractFromICO( path, xpm_path))
745         goto end;
746     if (!bWait)
747     {
748         sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
749         if (create_default_icon( xpm_path, ico_path ))
750             goto end;
751     }
752
753     HeapFree( GetProcessHeap(), 0, xpm_path );
754     xpm_path=NULL;
755
756  end:
757     HeapFree(GetProcessHeap(), 0, iconsdir);
758     HeapFree(GetProcessHeap(), 0, ico_path);
759     return xpm_path;
760 }
761
762 /* This escapes \ in filenames */
763 static LPSTR escape(LPCWSTR arg)
764 {
765     LPSTR narg, x;
766     LPCWSTR esc;
767     int len = 0, n;
768
769     esc = arg;
770     while((esc = strchrW(esc, '\\')))
771     {
772         esc++;
773         len++;
774     }
775
776     len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
777     narg = HeapAlloc(GetProcessHeap(), 0, len);
778
779     x = narg;
780     while (*arg)
781     {
782         n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
783         x += n;
784         len -= n;
785         if (*arg == '\\')
786             *x++='\\'; /* escape \ */
787         arg++;
788     }
789     *x = 0;
790     return narg;
791 }
792
793 static int fork_and_wait( const char *linker, const char *link_name, const char *path,
794                           int desktop, const char *args, const char *icon_name,
795                           const char *workdir, const char *description )
796 {
797     int pos = 0;
798     const char *argv[20];
799     int retcode;
800
801     WINE_TRACE( "linker app='%s' link='%s' mode=%s "
802         "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
803         linker, link_name, desktop ? "desktop" : "menu",
804         path, args, icon_name, workdir, description  );
805
806     argv[pos++] = linker ;
807     argv[pos++] = "--link";
808     argv[pos++] = link_name;
809     argv[pos++] = "--path";
810     argv[pos++] = path;
811     argv[pos++] = desktop ? "--desktop" : "--menu";
812     if (args && strlen(args))
813     {
814         argv[pos++] = "--args";
815         argv[pos++] = args;
816     }
817     if (icon_name)
818     {
819         argv[pos++] = "--icon";
820         argv[pos++] = icon_name;
821     }
822     if (workdir && strlen(workdir))
823     {
824         argv[pos++] = "--workdir";
825         argv[pos++] = workdir;
826     }
827     if (description && strlen(description))
828     {
829         argv[pos++] = "--descr";
830         argv[pos++] = description;
831     }
832     argv[pos] = NULL;
833
834     retcode=spawnvp( _P_WAIT, linker, argv );
835     if (retcode!=0)
836         WINE_ERR("%s returned %d\n",linker,retcode);
837     return retcode;
838 }
839
840 /* Return a heap-allocated copy of the unix format difference between the two
841  * Windows-format paths.
842  * locn is the owning location
843  * link is within locn
844  */
845 static char *relative_path( LPCWSTR link, LPCWSTR locn )
846 {
847     char *unix_locn, *unix_link;
848     char *relative = NULL;
849
850     unix_locn = wine_get_unix_file_name(locn);
851     unix_link = wine_get_unix_file_name(link);
852     if (unix_locn && unix_link)
853     {
854         size_t len_unix_locn, len_unix_link;
855         len_unix_locn = strlen (unix_locn);
856         len_unix_link = strlen (unix_link);
857         if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
858         {
859             size_t len_rel;
860             char *p = strrchr (unix_link + len_unix_locn, '/');
861             p = strrchr (p, '.');
862             if (p)
863             {
864                 *p = '\0';
865                 len_unix_link = p - unix_link;
866             }
867             len_rel = len_unix_link - len_unix_locn;
868             relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
869             if (relative)
870             {
871                 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
872             }
873         }
874     }
875     if (!relative)
876         WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
877     HeapFree(GetProcessHeap(), 0, unix_locn);
878     HeapFree(GetProcessHeap(), 0, unix_link);
879     return relative;
880 }
881
882 /***********************************************************************
883  *
884  *           GetLinkLocation
885  *
886  * returns TRUE if successful
887  * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
888  * *relative will contain the address of a heap-allocated copy of the portion
889  * of the filename that is within the specified location, in unix form
890  */
891 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
892 {
893     WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
894     DWORD len, i, r, filelen;
895     const DWORD locations[] = {
896         CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
897         CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
898         CSIDL_COMMON_STARTMENU };
899
900     WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
901     filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
902     if (filelen==0 || filelen>MAX_PATH)
903         return FALSE;
904
905     WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
906
907     /* the CSLU Toolkit uses a short path name when creating .lnk files;
908      * expand or our hardcoded list won't match.
909      */
910     filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
911     if (filelen==0 || filelen>MAX_PATH)
912         return FALSE;
913
914     WINE_TRACE("%s\n", wine_dbgstr_w(filename));
915
916     for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
917     {
918         if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
919             continue;
920
921         len = lstrlenW(buffer);
922         if (len >= MAX_PATH)
923             continue; /* We've just trashed memory! Hopefully we are OK */
924
925         if (len > filelen || filename[len]!='\\')
926             continue;
927         /* do a lstrcmpinW */
928         filename[len] = 0;
929         r = lstrcmpiW( filename, buffer );
930         filename[len] = '\\';
931         if ( r )
932             continue;
933
934         /* return the remainder of the string and link type */
935         *loc = locations[i];
936         *relative = relative_path (filename, buffer);
937         return (*relative != NULL);
938     }
939
940     return FALSE;
941 }
942
943 /* gets the target path directly or through MSI */
944 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
945                             LPWSTR szArgs, DWORD argsSize)
946 {
947     IShellLinkDataList *dl = NULL;
948     EXP_DARWIN_LINK *dar = NULL;
949     HRESULT hr;
950
951     szPath[0] = 0;
952     szArgs[0] = 0;
953
954     hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
955     if (hr == S_OK && szPath[0])
956     {
957         IShellLinkW_GetArguments( sl, szArgs, argsSize );
958         return hr;
959     }
960
961     hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
962     if (FAILED(hr))
963         return hr;
964
965     hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
966     if (SUCCEEDED(hr))
967     {
968         WCHAR* szCmdline;
969         DWORD cmdSize;
970
971         cmdSize=0;
972         hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
973         if (hr == ERROR_SUCCESS)
974         {
975             cmdSize++;
976             szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
977             hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
978             WINE_TRACE("      command    : %s\n", wine_dbgstr_w(szCmdline));
979             if (hr == ERROR_SUCCESS)
980             {
981                 WCHAR *s, *d;
982                 int bcount, in_quotes;
983
984                 /* Extract the application path */
985                 bcount=0;
986                 in_quotes=0;
987                 s=szCmdline;
988                 d=szPath;
989                 while (*s)
990                 {
991                     if ((*s==0x0009 || *s==0x0020) && !in_quotes)
992                     {
993                         /* skip the remaining spaces */
994                         do {
995                             s++;
996                         } while (*s==0x0009 || *s==0x0020);
997                         break;
998                     }
999                     else if (*s==0x005c)
1000                     {
1001                         /* '\\' */
1002                         *d++=*s++;
1003                         bcount++;
1004                     }
1005                     else if (*s==0x0022)
1006                     {
1007                         /* '"' */
1008                         if ((bcount & 1)==0)
1009                         {
1010                             /* Preceded by an even number of '\', this is
1011                              * half that number of '\', plus a quote which
1012                              * we erase.
1013                              */
1014                             d-=bcount/2;
1015                             in_quotes=!in_quotes;
1016                             s++;
1017                         }
1018                         else
1019                         {
1020                             /* Preceded by an odd number of '\', this is
1021                              * half that number of '\' followed by a '"'
1022                              */
1023                             d=d-bcount/2-1;
1024                             *d++='"';
1025                             s++;
1026                         }
1027                         bcount=0;
1028                     }
1029                     else
1030                     {
1031                         /* a regular character */
1032                         *d++=*s++;
1033                         bcount=0;
1034                     }
1035                     if ((d-szPath) == pathSize)
1036                     {
1037                         /* Keep processing the path till we get to the
1038                          * arguments, but 'stand still'
1039                          */
1040                         d--;
1041                     }
1042                 }
1043                 /* Close the application path */
1044                 *d=0;
1045
1046                 lstrcpynW(szArgs, s, argsSize);
1047             }
1048             HeapFree( GetProcessHeap(), 0, szCmdline );
1049         }
1050         LocalFree( dar );
1051     }
1052
1053     IShellLinkDataList_Release( dl );
1054     return hr;
1055 }
1056
1057 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1058 {
1059     static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1060                                    '\\','s','t','a','r','t','.','e','x','e',0};
1061     char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1062     char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1063     WCHAR szTmp[INFOTIPSIZE];
1064     WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1065     WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1066     int iIconId = 0, r = -1;
1067     DWORD csidl = -1;
1068     HANDLE hsem = NULL;
1069
1070     if ( !link )
1071     {
1072         WINE_ERR("Link name is null\n");
1073         return FALSE;
1074     }
1075
1076     if( !GetLinkLocation( link, &csidl, &link_name ) )
1077     {
1078         WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1079         return TRUE;
1080     }
1081     if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1082     {
1083         WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1084         return TRUE;
1085     }
1086     WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));
1087
1088     szTmp[0] = 0;
1089     IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1090     ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1091     WINE_TRACE("workdir    : %s\n", wine_dbgstr_w(szWorkDir));
1092
1093     szTmp[0] = 0;
1094     IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1095     ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1096     WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1097
1098     get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1099     WINE_TRACE("path       : %s\n", wine_dbgstr_w(szPath));
1100     WINE_TRACE("args       : %s\n", wine_dbgstr_w(szArgs));
1101
1102     szTmp[0] = 0;
1103     IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1104     ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1105     WINE_TRACE("icon file  : %s\n", wine_dbgstr_w(szIconPath) );
1106
1107     if( !szPath[0] )
1108     {
1109         LPITEMIDLIST pidl = NULL;
1110         IShellLinkW_GetIDList( sl, &pidl );
1111         if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1112             WINE_TRACE("pidl path  : %s\n", wine_dbgstr_w(szPath));
1113     }
1114
1115     /* extract the icon */
1116     if( szIconPath[0] )
1117         icon_name = extract_icon( szIconPath , iIconId, bWait );
1118     else
1119         icon_name = extract_icon( szPath, iIconId, bWait );
1120
1121     /* fail - try once again after parent process exit */
1122     if( !icon_name )
1123     {
1124         if (bWait)
1125         {
1126             WINE_WARN("Unable to extract icon, deferring.\n");
1127             goto cleanup;
1128         }
1129         WINE_ERR("failed to extract icon from %s\n",
1130                  wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
1131     }
1132
1133     /* check the path */
1134     if( szPath[0] )
1135     {
1136         static const WCHAR exeW[] = {'.','e','x','e',0};
1137         WCHAR *p;
1138
1139         /* check for .exe extension */
1140         if (!(p = strrchrW( szPath, '.' )) ||
1141             strchrW( p, '\\' ) || strchrW( p, '/' ) ||
1142             lstrcmpiW( p, exeW ))
1143         {
1144             /* Not .exe - use 'start.exe' to launch this file */
1145             p = szArgs + lstrlenW(szPath) + 2;
1146             if (szArgs[0])
1147             {
1148                 p[0] = ' ';
1149                 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
1150                                            sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
1151             }
1152             else
1153                 p[0] = 0;
1154
1155             szArgs[0] = '"';
1156             lstrcpyW(szArgs + 1, szPath);
1157             p[-1] = '"';
1158
1159             GetWindowsDirectoryW(szPath, MAX_PATH);
1160             lstrcatW(szPath, startW);
1161         }
1162
1163         /* convert app working dir */
1164         if (szWorkDir[0])
1165             work_dir = wine_get_unix_file_name( szWorkDir );
1166     }
1167     else
1168     {
1169         /* if there's no path... try run the link itself */
1170         lstrcpynW(szArgs, link, MAX_PATH);
1171         GetWindowsDirectoryW(szPath, MAX_PATH);
1172         lstrcatW(szPath, startW);
1173     }
1174
1175     /* escape the path and parameters */
1176     escaped_path = escape(szPath);
1177     escaped_args = escape(szArgs);
1178     escaped_description = escape(szDescription);
1179
1180     /* running multiple instances of wineshelllink
1181        at the same time may be dangerous */
1182     hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1183     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
1184     {
1185         WINE_ERR("failed wait for semaphore\n");
1186         goto cleanup;
1187     }
1188
1189     r = fork_and_wait("wineshelllink", link_name, escaped_path,
1190                       in_desktop_dir(csidl), escaped_args, icon_name,
1191                       work_dir ? work_dir : "", escaped_description);
1192
1193     ReleaseSemaphore( hsem, 1, NULL );
1194
1195 cleanup:
1196     if (hsem) CloseHandle( hsem );
1197     HeapFree( GetProcessHeap(), 0, icon_name );
1198     HeapFree( GetProcessHeap(), 0, work_dir );
1199     HeapFree( GetProcessHeap(), 0, link_name );
1200     HeapFree( GetProcessHeap(), 0, escaped_args );
1201     HeapFree( GetProcessHeap(), 0, escaped_path );
1202     HeapFree( GetProcessHeap(), 0, escaped_description );
1203
1204     if (r && !bWait)
1205         WINE_ERR("failed to fork and exec wineshelllink\n" );
1206
1207     return ( r == 0 );
1208 }
1209
1210 static BOOL WaitForParentProcess( void )
1211 {
1212     PROCESSENTRY32 procentry;
1213     HANDLE hsnapshot = NULL, hprocess = NULL;
1214     DWORD ourpid = GetCurrentProcessId();
1215     BOOL ret = FALSE, rc;
1216
1217     WINE_TRACE("Waiting for parent process\n");
1218     if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
1219         INVALID_HANDLE_VALUE)
1220     {
1221         WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
1222         goto done;
1223     }
1224
1225     procentry.dwSize = sizeof(PROCESSENTRY32);
1226     rc = Process32First( hsnapshot, &procentry );
1227     while (rc)
1228     {
1229         if (procentry.th32ProcessID == ourpid) break;
1230         rc = Process32Next( hsnapshot, &procentry );
1231     }
1232     if (!rc)
1233     {
1234         WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
1235         goto done;
1236     }
1237
1238     if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
1239         NULL)
1240     {
1241         WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
1242                  GetLastError());
1243         goto done;
1244     }
1245
1246     if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
1247         ret = TRUE;
1248     else
1249         WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
1250
1251 done:
1252     if (hprocess) CloseHandle( hprocess );
1253     if (hsnapshot) CloseHandle( hsnapshot );
1254     return ret;
1255 }
1256
1257 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
1258 {
1259     IShellLinkW *sl;
1260     IPersistFile *pf;
1261     HRESULT r;
1262     WCHAR fullname[MAX_PATH];
1263     DWORD len;
1264
1265     WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
1266
1267     if( !linkname[0] )
1268     {
1269         WINE_ERR("link name missing\n");
1270         return 1;
1271     }
1272
1273     len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1274     if (len==0 || len>MAX_PATH)
1275     {
1276         WINE_ERR("couldn't get full path of link file\n");
1277         return 1;
1278     }
1279
1280     r = CoInitialize( NULL );
1281     if( FAILED( r ) )
1282     {
1283         WINE_ERR("CoInitialize failed\n");
1284         return 1;
1285     }
1286
1287     r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1288                           &IID_IShellLinkW, (LPVOID *) &sl );
1289     if( FAILED( r ) )
1290     {
1291         WINE_ERR("No IID_IShellLink\n");
1292         return 1;
1293     }
1294
1295     r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1296     if( FAILED( r ) )
1297     {
1298         WINE_ERR("No IID_IPersistFile\n");
1299         return 1;
1300     }
1301
1302     r = IPersistFile_Load( pf, fullname, STGM_READ );
1303     if( SUCCEEDED( r ) )
1304     {
1305         /* If something fails (eg. Couldn't extract icon)
1306          * wait for parent process and try again
1307          */
1308         if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
1309         {
1310             WaitForParentProcess();
1311             InvokeShellLinker( sl, fullname, FALSE );
1312         }
1313     }
1314
1315     IPersistFile_Release( pf );
1316     IShellLinkW_Release( sl );
1317
1318     CoUninitialize();
1319
1320     return !r;
1321 }
1322
1323
1324 static CHAR *next_token( LPSTR *p )
1325 {
1326     LPSTR token = NULL, t = *p;
1327
1328     if( !t )
1329         return NULL;
1330
1331     while( t && !token )
1332     {
1333         switch( *t )
1334         {
1335         case ' ':
1336             t++;
1337             continue;
1338         case '"':
1339             /* unquote the token */
1340             token = ++t;
1341             t = strchr( token, '"' );
1342             if( t )
1343                  *t++ = 0;
1344             break;
1345         case 0:
1346             t = NULL;
1347             break;
1348         default:
1349             token = t;
1350             t = strchr( token, ' ' );
1351             if( t )
1352                  *t++ = 0;
1353             break;
1354         }
1355     }
1356     *p = t;
1357     return token;
1358 }
1359
1360 /***********************************************************************
1361  *
1362  *           WinMain
1363  */
1364 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1365 {
1366     LPSTR token = NULL, p;
1367     BOOL bWait = FALSE;
1368     int ret = 0;
1369
1370     for( p = cmdline; p && *p; )
1371     {
1372         token = next_token( &p );
1373         if( !token )
1374             break;
1375         if( !lstrcmpA( token, "-w" ) )
1376             bWait = TRUE;
1377         else if( token[0] == '-' )
1378         {
1379             WINE_ERR( "unknown option %s\n",token);
1380         }
1381         else
1382         {
1383             WCHAR link[MAX_PATH];
1384
1385             MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1386             if( !Process_Link( link, bWait ) )
1387             {
1388                 WINE_ERR( "failed to build menu item for %s\n",token);
1389                 ret = 1;
1390             }
1391         }
1392     }
1393
1394     return ret;
1395 }