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