wnaspi32: Make winaspi.dll into a stand-alone 16-bit module.
[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  * Copyright 2008 Damjan Jovanovic
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  *
25  *
26  *  This program is used to replicate the Windows desktop and start menu
27  * into the native desktop's copies.  Desktop entries are merged directly
28  * into the native desktop.  The Windows Start Menu corresponds to a Wine
29  * entry within the native "start" menu and replicates the whole tree
30  * structure of the Windows Start Menu.  Currently it does not differentiate
31  * between the user's desktop/start menu and the "All Users" copies.
32  *
33  *  This program will read a Windows shortcut file using the IShellLink
34  * interface, then 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 #include <intshcut.h>
77
78 #include "wine/unicode.h"
79 #include "wine/debug.h"
80 #include "wine/library.h"
81 #include "wine.xpm"
82
83 #ifdef HAVE_PNG_H
84 #undef FAR
85 #include <png.h>
86 #endif
87
88 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
89
90 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
91                                (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
92 #define in_startmenu(csidl)   ((csidl)==CSIDL_STARTMENU || \
93                                (csidl)==CSIDL_COMMON_STARTMENU)
94         
95 /* link file formats */
96
97 #include "pshpack1.h"
98
99 typedef struct
100 {
101     BYTE bWidth;
102     BYTE bHeight;
103     BYTE bColorCount;
104     BYTE bReserved;
105     WORD wPlanes;
106     WORD wBitCount;
107     DWORD dwBytesInRes;
108     WORD nID;
109 } GRPICONDIRENTRY;
110
111 typedef struct
112 {
113     WORD idReserved;
114     WORD idType;
115     WORD idCount;
116     GRPICONDIRENTRY idEntries[1];
117 } GRPICONDIR;
118
119 typedef struct
120 {
121     BYTE bWidth;
122     BYTE bHeight;
123     BYTE bColorCount;
124     BYTE bReserved;
125     WORD wPlanes;
126     WORD wBitCount;
127     DWORD dwBytesInRes;
128     DWORD dwImageOffset;
129 } ICONDIRENTRY;
130
131 typedef struct
132 {
133     WORD idReserved;
134     WORD idType;
135     WORD idCount;
136 } ICONDIR;
137
138
139 #include "poppack.h"
140
141 typedef struct
142 {
143         HRSRC *pResInfo;
144         int   nIndex;
145 } ENUMRESSTRUCT;
146
147 static char *xdg_config_dir;
148 static char *xdg_data_dir;
149
150 /* Icon extraction routines
151  *
152  * FIXME: should use PrivateExtractIcons and friends
153  * FIXME: should not use stdio
154  */
155
156 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
157
158 /* PNG-specific code */
159 #ifdef SONAME_LIBPNG
160
161 static void *libpng_handle;
162 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
163 MAKE_FUNCPTR(png_create_info_struct);
164 MAKE_FUNCPTR(png_create_write_struct);
165 MAKE_FUNCPTR(png_destroy_write_struct);
166 MAKE_FUNCPTR(png_init_io);
167 MAKE_FUNCPTR(png_set_bgr);
168 MAKE_FUNCPTR(png_set_text);
169 MAKE_FUNCPTR(png_set_IHDR);
170 MAKE_FUNCPTR(png_write_end);
171 MAKE_FUNCPTR(png_write_info);
172 MAKE_FUNCPTR(png_write_row);
173 #undef MAKE_FUNCPTR
174
175 static void *load_libpng(void)
176 {
177     if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
178     {
179 #define LOAD_FUNCPTR(f) \
180     if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
181         libpng_handle = NULL; \
182         return NULL; \
183     }
184         LOAD_FUNCPTR(png_create_info_struct);
185         LOAD_FUNCPTR(png_create_write_struct);
186         LOAD_FUNCPTR(png_destroy_write_struct);
187         LOAD_FUNCPTR(png_init_io);
188         LOAD_FUNCPTR(png_set_bgr);
189         LOAD_FUNCPTR(png_set_IHDR);
190         LOAD_FUNCPTR(png_set_text);
191         LOAD_FUNCPTR(png_write_end);
192         LOAD_FUNCPTR(png_write_info);
193         LOAD_FUNCPTR(png_write_row);
194 #undef LOAD_FUNCPTR
195     }
196     return libpng_handle;
197 }
198
199 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
200 {
201     static const char comment_key[] = "Created from";
202     FILE *fp;
203     png_structp png_ptr;
204     png_infop info_ptr;
205     png_text comment;
206     int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
207     BYTE *row, *copy = NULL;
208     const BYTE *pXOR, *pAND = NULL;
209     int nWidth  = pIcon->bmiHeader.biWidth;
210     int nHeight = pIcon->bmiHeader.biHeight;
211     int nBpp    = pIcon->bmiHeader.biBitCount;
212
213     switch (nBpp)
214     {
215     case 32:
216         color_type |= PNG_COLOR_MASK_ALPHA;
217         /* fall through */
218     case 24:
219         color_type |= PNG_COLOR_MASK_COLOR;
220         break;
221     default:
222         return FALSE;
223     }
224
225     if (!libpng_handle && !load_libpng())
226     {
227         WINE_WARN("Unable to load libpng\n");
228         return FALSE;
229     }
230
231     if (!(fp = fopen(png_filename, "w")))
232     {
233         WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
234         return FALSE;
235     }
236
237     nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
238     nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
239     pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
240     if (nHeight > nWidth)
241     {
242         nHeight /= 2;
243         pAND = pXOR + nHeight * nXORWidthBytes;
244     }
245
246     /* Apply mask if present */
247     if (pAND)
248     {
249         RGBQUAD bgColor;
250
251         /* copy bytes before modifying them */
252         copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
253         memcpy( copy, pXOR, nHeight * nXORWidthBytes );
254         pXOR = copy;
255
256         /* image and mask are upside down reversed */
257         row = copy + (nHeight - 1) * nXORWidthBytes;
258
259         /* top left corner */
260         bgColor.rgbRed   = row[0];
261         bgColor.rgbGreen = row[1];
262         bgColor.rgbBlue  = row[2];
263         bgColor.rgbReserved = 0;
264
265         for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
266             for (j = 0; j < nWidth; j++, row += nBpp >> 3)
267                 if (MASK(j, i))
268                 {
269                     RGBQUAD *pixel = (RGBQUAD *)row;
270                     pixel->rgbBlue  = bgColor.rgbBlue;
271                     pixel->rgbGreen = bgColor.rgbGreen;
272                     pixel->rgbRed   = bgColor.rgbRed;
273                     if (nBpp == 32)
274                         pixel->rgbReserved = bgColor.rgbReserved;
275                 }
276     }
277
278     comment.text = NULL;
279
280     if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
281         !(info_ptr = ppng_create_info_struct(png_ptr)))
282         goto error;
283
284     if (setjmp(png_jmpbuf(png_ptr)))
285     {
286         /* All future errors jump here */
287         WINE_ERR("png error\n");
288         goto error;
289     }
290
291     ppng_init_io(png_ptr, fp);
292     ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
293                   color_type,
294                   PNG_INTERLACE_NONE,
295                   PNG_COMPRESSION_TYPE_DEFAULT,
296                   PNG_FILTER_TYPE_DEFAULT);
297
298     /* Set comment */
299     comment.compression = PNG_TEXT_COMPRESSION_NONE;
300     comment.key = (png_charp)comment_key;
301     i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
302     comment.text = HeapAlloc(GetProcessHeap(), 0, i);
303     WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
304     comment.text_length = i - 1;
305     ppng_set_text(png_ptr, info_ptr, &comment, 1);
306
307
308     ppng_write_info(png_ptr, info_ptr);
309     ppng_set_bgr(png_ptr);
310     for (i = nHeight - 1; i >= 0 ; i--)
311         ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
312     ppng_write_end(png_ptr, info_ptr);
313
314     ppng_destroy_write_struct(&png_ptr, &info_ptr);
315     if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
316     fclose(fp);
317     HeapFree(GetProcessHeap(), 0, copy);
318     HeapFree(GetProcessHeap(), 0, comment.text);
319     return TRUE;
320
321  error:
322     if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
323     fclose(fp);
324     unlink(png_filename);
325     HeapFree(GetProcessHeap(), 0, copy);
326     HeapFree(GetProcessHeap(), 0, comment.text);
327     return FALSE;
328 }
329 #endif /* SONAME_LIBPNG */
330
331 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
332 {
333     FILE *fXPMFile;
334     int nHeight;
335     int nXORWidthBytes;
336     int nANDWidthBytes;
337     BOOL b8BitColors;
338     int nColors;
339     const BYTE *pXOR;
340     const BYTE *pAND;
341     BOOL aColorUsed[256] = {0};
342     int nColorsUsed = 0;
343     int i,j;
344     char *comment;
345
346     if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
347     {
348         WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
349         return FALSE;
350     }
351
352     if (!(fXPMFile = fopen(szXPMFileName, "w")))
353     {
354         WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
355         return FALSE;
356     }
357
358     i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
359     comment = HeapAlloc(GetProcessHeap(), 0, i);
360     WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
361
362     nHeight = pIcon->bmiHeader.biHeight / 2;
363     nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
364                           + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
365     nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
366                           + ((pIcon->bmiHeader.biWidth % 32) > 0));
367     b8BitColors = pIcon->bmiHeader.biBitCount == 8;
368     nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
369         : 1 << pIcon->bmiHeader.biBitCount;
370     pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
371     pAND = pXOR + nHeight * nXORWidthBytes;
372
373 #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)
374
375     for (i = 0; i < nHeight; i++) {
376         for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
377             if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
378             {
379                 aColorUsed[COLOR(j,i)] = TRUE;
380                 nColorsUsed++;
381             }
382         }
383     }
384
385     if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
386         goto error;
387     if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
388                 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
389         goto error;
390
391     for (i = 0; i < nColors; i++) {
392         if (aColorUsed[i])
393             if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
394                         pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
395                 goto error;
396     }
397     if (fprintf(fXPMFile, "\"   c None\"") <= 0)
398         goto error;
399
400     for (i = 0; i < nHeight; i++)
401     {
402         if (fprintf(fXPMFile, ",\n\"") <= 0)
403             goto error;
404         for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
405         {
406             if MASK(j,i)
407                 {
408                     if (fprintf(fXPMFile, "  ") <= 0)
409                         goto error;
410                 }
411             else
412                 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
413                     goto error;
414         }
415         if (fprintf(fXPMFile, "\"") <= 0)
416             goto error;
417     }
418     if (fprintf(fXPMFile, "};\n") <= 0)
419         goto error;
420
421 #undef MASK
422 #undef COLOR
423
424     HeapFree(GetProcessHeap(), 0, comment);
425     fclose(fXPMFile);
426     return TRUE;
427
428  error:
429     HeapFree(GetProcessHeap(), 0, comment);
430     fclose(fXPMFile);
431     unlink( szXPMFileName );
432     return FALSE;
433 }
434
435 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
436 {
437     ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
438
439     if (!sEnumRes->nIndex--)
440     {
441         *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
442         return FALSE;
443     }
444     else
445         return TRUE;
446 }
447
448 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
449 {
450     HMODULE hModule;
451     HRSRC hResInfo;
452     LPCWSTR lpName = NULL;
453     HGLOBAL hResData;
454     GRPICONDIR *pIconDir;
455     BITMAPINFO *pIcon;
456     ENUMRESSTRUCT sEnumRes;
457     int nMax = 0;
458     int nMaxBits = 0;
459     int i;
460     BOOL ret = FALSE;
461
462     hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
463     if (!hModule)
464     {
465         WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
466                  wine_dbgstr_w(szFileName), GetLastError());
467         return FALSE;
468     }
469
470     if (nIndex < 0)
471     {
472         hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
473         WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
474                    wine_dbgstr_w(szFileName), hResInfo, GetLastError());
475     }
476     else
477     {
478         hResInfo=NULL;
479         sEnumRes.pResInfo = &hResInfo;
480         sEnumRes.nIndex = nIndex;
481         if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
482                                 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
483             sEnumRes.nIndex != -1)
484         {
485             WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
486         }
487     }
488
489     if (hResInfo)
490     {
491         if ((hResData = LoadResource(hModule, hResInfo)))
492         {
493             if ((pIconDir = LockResource(hResData)))
494             {
495                 for (i = 0; i < pIconDir->idCount; i++)
496                 {
497                     if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
498                     {
499                         if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
500                         {
501                             lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
502                             nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
503                             nMaxBits = pIconDir->idEntries[i].wBitCount;
504                         }
505                     }               
506                 }
507             }
508
509             FreeResource(hResData);
510         }
511     }
512     else
513     {
514         WINE_WARN("found no icon\n");
515         FreeLibrary(hModule);
516         return FALSE;
517     }
518  
519     if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
520     {
521         if ((hResData = LoadResource(hModule, hResInfo)))
522         {
523             if ((pIcon = LockResource(hResData)))
524             {
525 #ifdef SONAME_LIBPNG
526                 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
527                     ret = TRUE;
528                 else
529 #endif
530                 {
531                     memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
532                     if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
533                         ret = TRUE;
534                 }
535             }
536
537             FreeResource(hResData);
538         }
539     }
540
541     FreeLibrary(hModule);
542     return ret;
543 }
544
545 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
546 {
547     if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
548         !extract_icon16(szFileName, szXPMFileName)*/)
549         return FALSE;
550     return TRUE;
551 }
552
553 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
554 {
555     FILE *fICOFile = NULL;
556     ICONDIR iconDir;
557     ICONDIRENTRY *pIconDirEntry = NULL;
558     int nMax = 0, nMaxBits = 0;
559     int nIndex = 0;
560     void *pIcon = NULL;
561     int i;
562     char *filename = NULL;
563
564     filename = wine_get_unix_file_name(szFileName);
565     if (!(fICOFile = fopen(filename, "r")))
566     {
567         WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
568         goto error;
569     }
570
571     if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
572         (iconDir.idReserved != 0) || (iconDir.idType != 1))
573     {
574         WINE_WARN("Invalid ico file format\n");
575         goto error;
576     }
577
578     if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
579         goto error;
580     if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
581         goto error;
582
583     for (i = 0; i < iconDir.idCount; i++)
584     {
585         WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
586         if (pIconDirEntry[i].wBitCount >= nMaxBits &&
587             (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
588         {
589             nIndex = i;
590             nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
591             nMaxBits = pIconDirEntry[i].wBitCount;
592         }
593     }
594     WINE_TRACE("Selected: %d\n", nIndex);
595
596     if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
597         goto error;
598     if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
599         goto error;
600     if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
601         goto error;
602
603
604     /* Prefer PNG over XPM */
605 #ifdef SONAME_LIBPNG
606     if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
607 #endif
608     {
609         memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
610         if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
611             goto error;
612     }
613
614     HeapFree(GetProcessHeap(), 0, pIcon);
615     HeapFree(GetProcessHeap(), 0, pIconDirEntry);
616     fclose(fICOFile);
617     HeapFree(GetProcessHeap(), 0, filename);
618     return 1;
619
620  error:
621     HeapFree(GetProcessHeap(), 0, pIcon);
622     HeapFree(GetProcessHeap(), 0, pIconDirEntry);
623     if (fICOFile) fclose(fICOFile);
624     HeapFree(GetProcessHeap(), 0, filename);
625     return 0;
626 }
627
628 static BOOL create_default_icon( const char *filename, const char* comment )
629 {
630     FILE *fXPM;
631     unsigned int i;
632
633     if (!(fXPM = fopen(filename, "w"))) return FALSE;
634     if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
635         goto error;
636     for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
637         if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
638             goto error;
639     }
640     if (fprintf( fXPM, "};\n" ) <=0)
641         goto error;
642     fclose( fXPM );
643     return TRUE;
644  error:
645     fclose( fXPM );
646     unlink( filename );
647     return FALSE;
648
649 }
650
651 static unsigned short crc16(const char* string)
652 {
653     unsigned short crc = 0;
654     int i, j, xor_poly;
655
656     for (i = 0; string[i] != 0; i++)
657     {
658         char c = string[i];
659         for (j = 0; j < 8; c >>= 1, j++)
660         {
661             xor_poly = (c ^ crc) & 1;
662             crc >>= 1;
663             if (xor_poly)
664                 crc ^= 0xa001;
665         }
666     }
667     return crc;
668 }
669
670 static char* heap_printf(const char *format, ...)
671 {
672     va_list args;
673     int size = 4096;
674     char *buffer;
675     int n;
676
677     va_start(args, format);
678     while (1)
679     {
680         buffer = HeapAlloc(GetProcessHeap(), 0, size);
681         if (buffer == NULL)
682             break;
683         n = vsnprintf(buffer, size, format, args);
684         if (n == -1)
685             size *= 2;
686         else if (n >= size)
687             size = n + 1;
688         else
689             break;
690         HeapFree(GetProcessHeap(), 0, buffer);
691     }
692     va_end(args);
693     return buffer;
694 }
695
696 static BOOL create_directories(char *directory)
697 {
698     BOOL ret = TRUE;
699     int i;
700
701     for (i = 0; directory[i]; i++)
702     {
703         if (i > 0 && directory[i] == '/')
704         {
705             directory[i] = 0;
706             mkdir(directory, 0777);
707             directory[i] = '/';
708         }
709     }
710     if (mkdir(directory, 0777) && errno != EEXIST)
711        ret = FALSE;
712
713     return ret;
714 }
715
716 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
717 static char *extract_icon( LPCWSTR path, int index, BOOL bWait )
718 {
719     unsigned short crc;
720     char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
721     char* s;
722     int n;
723
724     /* Where should we save the icon? */
725     WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
726     iconsdir = heap_printf("%s/icons", xdg_data_dir);
727     if (iconsdir)
728     {
729         if (mkdir(iconsdir, 0777) && errno != EEXIST)
730         {
731             WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
732             goto end;
733         }
734     }
735     else
736     {
737         WINE_TRACE("no icon created\n");
738         return NULL;
739     }
740     
741     /* Determine the icon base name */
742     n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
743     ico_path = HeapAlloc(GetProcessHeap(), 0, n);
744     WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
745     s=ico_name=ico_path;
746     while (*s!='\0') {
747         if (*s=='/' || *s=='\\') {
748             *s='\\';
749             ico_name=s;
750         } else {
751             *s=tolower(*s);
752         }
753         s++;
754     }
755     if (*ico_name=='\\') *ico_name++='\0';
756     s=strrchr(ico_name,'.');
757     if (s) *s='\0';
758
759     /* Compute the source-path hash */
760     crc=crc16(ico_path);
761
762     /* Try to treat the source file as an exe */
763     xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
764     sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
765     if (ExtractFromEXEDLL( path, index, xpm_path ))
766         goto end;
767
768     /* Must be something else, ignore the index in that case */
769     sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
770     if (ExtractFromICO( path, xpm_path))
771         goto end;
772     if (!bWait)
773     {
774         sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
775         if (create_default_icon( xpm_path, ico_path ))
776             goto end;
777     }
778
779     HeapFree( GetProcessHeap(), 0, xpm_path );
780     xpm_path=NULL;
781
782  end:
783     HeapFree(GetProcessHeap(), 0, iconsdir);
784     HeapFree(GetProcessHeap(), 0, ico_path);
785     return xpm_path;
786 }
787
788 static BOOL write_desktop_entry(const char *location, const char *linkname, const char *path,
789                                 const char *args, const char *descr, const char *workdir,
790                                 const char *icon)
791 {
792     FILE *file;
793
794     WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(location),
795                wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
796                wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
797
798     file = fopen(location, "w");
799     if (file == NULL)
800         return FALSE;
801
802     fprintf(file, "[Desktop Entry]\n");
803     fprintf(file, "Name=%s\n", linkname);
804     fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
805             wine_get_config_dir(), path, args);
806     fprintf(file, "Type=Application\n");
807     fprintf(file, "StartupNotify=true\n");
808     if (descr && lstrlenA(descr))
809         fprintf(file, "Comment=%s\n", descr);
810     if (workdir && lstrlenA(workdir))
811         fprintf(file, "Path=%s\n", workdir);
812     if (icon && lstrlenA(icon))
813         fprintf(file, "Icon=%s\n", icon);
814
815     fclose(file);
816     return TRUE;
817 }
818
819 static BOOL write_directory_entry(const char *directory, const char *location)
820 {
821     FILE *file;
822
823     WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
824
825     file = fopen(location, "w");
826     if (file == NULL)
827         return FALSE;
828
829     fprintf(file, "[Desktop Entry]\n");
830     fprintf(file, "Type=Directory\n");
831     if (strcmp(directory, "wine") == 0)
832     {
833         fprintf(file, "Name=Wine\n");
834         fprintf(file, "Icon=wine\n");
835     }
836     else
837     {
838         fprintf(file, "Name=%s\n", directory);
839         fprintf(file, "Icon=folder\n");
840     }
841
842     fclose(file);
843     return TRUE;
844 }
845
846 static BOOL write_menu_file(const char *filename)
847 {
848     char *tempfilename;
849     FILE *tempfile = NULL;
850     char *lastEntry;
851     char *name = NULL;
852     char *menuPath = NULL;
853     int i;
854     int count = 0;
855     BOOL ret = FALSE;
856
857     WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
858
859     while (1)
860     {
861         tempfilename = tempnam(xdg_config_dir, "_wine");
862         if (tempfilename)
863         {
864             int tempfd = open(tempfilename, O_EXCL | O_CREAT | O_WRONLY, 0666);
865             if (tempfd >= 0)
866             {
867                 tempfile = fdopen(tempfd, "w");
868                 if (tempfile)
869                     break;
870                 close(tempfd);
871                 goto end;
872             }
873             else if (errno == EEXIST)
874             {
875                 free(tempfilename);
876                 continue;
877             }
878             free(tempfilename);
879         }
880         return FALSE;
881     }
882
883     fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
884     fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
885     fprintf(tempfile, "<Menu>\n");
886     fprintf(tempfile, "  <Name>Applications</Name>\n");
887
888     name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
889     if (name == NULL) goto end;
890     lastEntry = name;
891     for (i = 0; filename[i]; i++)
892     {
893         name[i] = filename[i];
894         if (filename[i] == '/')
895         {
896             char *dir_file_name;
897             struct stat st;
898             name[i] = 0;
899             fprintf(tempfile, "  <Menu>\n");
900             fprintf(tempfile, "    <Name>%s%s</Name>\n", count ? "" : "wine-", name);
901             fprintf(tempfile, "    <Directory>%s%s.directory</Directory>\n", count ? "" : "wine-", name);
902             dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
903                 xdg_data_dir, count ? "" : "wine-", name);
904             if (dir_file_name)
905             {
906                 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
907                     write_directory_entry(lastEntry, dir_file_name);
908                 HeapFree(GetProcessHeap(), 0, dir_file_name);
909             }
910             name[i] = '-';
911             lastEntry = &name[i+1];
912             ++count;
913         }
914     }
915     name[i] = 0;
916
917     fprintf(tempfile, "    <Include>\n");
918     fprintf(tempfile, "      <Filename>%s</Filename>\n", name);
919     fprintf(tempfile, "    </Include>\n");
920     for (i = 0; i < count; i++)
921          fprintf(tempfile, "  </Menu>\n");
922     fprintf(tempfile, "</Menu>\n");
923
924     menuPath = heap_printf("%s/%s", xdg_config_dir, name);
925     if (menuPath == NULL) goto end;
926     strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
927     ret = TRUE;
928
929 end:
930     if (tempfile)
931         fclose(tempfile);
932     if (ret)
933         ret = (rename(tempfilename, menuPath) == 0);
934     if (!ret && tempfilename)
935         remove(tempfilename);
936     free(tempfilename);
937     HeapFree(GetProcessHeap(), 0, name);
938     HeapFree(GetProcessHeap(), 0, menuPath);
939     return ret;
940 }
941
942 static BOOL write_menu_entry(const char *link, const char *path, const char *args,
943                              const char *descr, const char *workdir, const char *icon)
944 {
945     const char *linkname;
946     char *desktopPath = NULL;
947     char *desktopDir;
948     char *filename = NULL;
949     BOOL ret = TRUE;
950
951     WINE_TRACE("(%s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(link), wine_dbgstr_a(path),
952                wine_dbgstr_a(args), wine_dbgstr_a(descr), wine_dbgstr_a(workdir),
953                wine_dbgstr_a(icon));
954
955     linkname = strrchr(link, '/');
956     if (linkname == NULL)
957         linkname = link;
958     else
959         ++linkname;
960
961     desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
962     if (!desktopPath)
963     {
964         WINE_WARN("out of memory creating menu entry\n");
965         ret = FALSE;
966         goto end;
967     }
968     desktopDir = strrchr(desktopPath, '/');
969     *desktopDir = 0;
970     if (!create_directories(desktopPath))
971     {
972         WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
973         ret = FALSE;
974         goto end;
975     }
976     *desktopDir = '/';
977     if (!write_desktop_entry(desktopPath, linkname, path, args, descr, workdir, icon))
978     {
979         WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
980         ret = FALSE;
981         goto end;
982     }
983
984     filename = heap_printf("wine/%s.desktop", link);
985     if (!filename || !write_menu_file(filename))
986     {
987         WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
988         ret = FALSE;
989     }
990
991 end:
992     HeapFree(GetProcessHeap(), 0, desktopPath);
993     HeapFree(GetProcessHeap(), 0, filename);
994     return ret;
995 }
996
997 /* This escapes \ in filenames */
998 static LPSTR escape(LPCWSTR arg)
999 {
1000     LPSTR narg, x;
1001     LPCWSTR esc;
1002     int len = 0, n;
1003
1004     esc = arg;
1005     while((esc = strchrW(esc, '\\')))
1006     {
1007         esc++;
1008         len++;
1009     }
1010
1011     len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1012     narg = HeapAlloc(GetProcessHeap(), 0, len);
1013
1014     x = narg;
1015     while (*arg)
1016     {
1017         n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1018         x += n;
1019         len -= n;
1020         if (*arg == '\\')
1021             *x++='\\'; /* escape \ */
1022         arg++;
1023     }
1024     *x = 0;
1025     return narg;
1026 }
1027
1028 /* Return a heap-allocated copy of the unix format difference between the two
1029  * Windows-format paths.
1030  * locn is the owning location
1031  * link is within locn
1032  */
1033 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1034 {
1035     char *unix_locn, *unix_link;
1036     char *relative = NULL;
1037
1038     unix_locn = wine_get_unix_file_name(locn);
1039     unix_link = wine_get_unix_file_name(link);
1040     if (unix_locn && unix_link)
1041     {
1042         size_t len_unix_locn, len_unix_link;
1043         len_unix_locn = strlen (unix_locn);
1044         len_unix_link = strlen (unix_link);
1045         if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1046         {
1047             size_t len_rel;
1048             char *p = strrchr (unix_link + len_unix_locn, '/');
1049             p = strrchr (p, '.');
1050             if (p)
1051             {
1052                 *p = '\0';
1053                 len_unix_link = p - unix_link;
1054             }
1055             len_rel = len_unix_link - len_unix_locn;
1056             relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1057             if (relative)
1058             {
1059                 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1060             }
1061         }
1062     }
1063     if (!relative)
1064         WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1065     HeapFree(GetProcessHeap(), 0, unix_locn);
1066     HeapFree(GetProcessHeap(), 0, unix_link);
1067     return relative;
1068 }
1069
1070 /***********************************************************************
1071  *
1072  *           GetLinkLocation
1073  *
1074  * returns TRUE if successful
1075  * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1076  * *relative will contain the address of a heap-allocated copy of the portion
1077  * of the filename that is within the specified location, in unix form
1078  */
1079 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1080 {
1081     WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1082     DWORD len, i, r, filelen;
1083     const DWORD locations[] = {
1084         CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1085         CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1086         CSIDL_COMMON_STARTMENU };
1087
1088     WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1089     filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1090     if (filelen==0 || filelen>MAX_PATH)
1091         return FALSE;
1092
1093     WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1094
1095     /* the CSLU Toolkit uses a short path name when creating .lnk files;
1096      * expand or our hardcoded list won't match.
1097      */
1098     filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1099     if (filelen==0 || filelen>MAX_PATH)
1100         return FALSE;
1101
1102     WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1103
1104     for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1105     {
1106         if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1107             continue;
1108
1109         len = lstrlenW(buffer);
1110         if (len >= MAX_PATH)
1111             continue; /* We've just trashed memory! Hopefully we are OK */
1112
1113         if (len > filelen || filename[len]!='\\')
1114             continue;
1115         /* do a lstrcmpinW */
1116         filename[len] = 0;
1117         r = lstrcmpiW( filename, buffer );
1118         filename[len] = '\\';
1119         if ( r )
1120             continue;
1121
1122         /* return the remainder of the string and link type */
1123         *loc = locations[i];
1124         *relative = relative_path (filename, buffer);
1125         return (*relative != NULL);
1126     }
1127
1128     return FALSE;
1129 }
1130
1131 /* gets the target path directly or through MSI */
1132 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1133                             LPWSTR szArgs, DWORD argsSize)
1134 {
1135     IShellLinkDataList *dl = NULL;
1136     EXP_DARWIN_LINK *dar = NULL;
1137     HRESULT hr;
1138
1139     szPath[0] = 0;
1140     szArgs[0] = 0;
1141
1142     hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1143     if (hr == S_OK && szPath[0])
1144     {
1145         IShellLinkW_GetArguments( sl, szArgs, argsSize );
1146         return hr;
1147     }
1148
1149     hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1150     if (FAILED(hr))
1151         return hr;
1152
1153     hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1154     if (SUCCEEDED(hr))
1155     {
1156         WCHAR* szCmdline;
1157         DWORD cmdSize;
1158
1159         cmdSize=0;
1160         hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1161         if (hr == ERROR_SUCCESS)
1162         {
1163             cmdSize++;
1164             szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1165             hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1166             WINE_TRACE("      command    : %s\n", wine_dbgstr_w(szCmdline));
1167             if (hr == ERROR_SUCCESS)
1168             {
1169                 WCHAR *s, *d;
1170                 int bcount, in_quotes;
1171
1172                 /* Extract the application path */
1173                 bcount=0;
1174                 in_quotes=0;
1175                 s=szCmdline;
1176                 d=szPath;
1177                 while (*s)
1178                 {
1179                     if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1180                     {
1181                         /* skip the remaining spaces */
1182                         do {
1183                             s++;
1184                         } while (*s==0x0009 || *s==0x0020);
1185                         break;
1186                     }
1187                     else if (*s==0x005c)
1188                     {
1189                         /* '\\' */
1190                         *d++=*s++;
1191                         bcount++;
1192                     }
1193                     else if (*s==0x0022)
1194                     {
1195                         /* '"' */
1196                         if ((bcount & 1)==0)
1197                         {
1198                             /* Preceded by an even number of '\', this is
1199                              * half that number of '\', plus a quote which
1200                              * we erase.
1201                              */
1202                             d-=bcount/2;
1203                             in_quotes=!in_quotes;
1204                             s++;
1205                         }
1206                         else
1207                         {
1208                             /* Preceded by an odd number of '\', this is
1209                              * half that number of '\' followed by a '"'
1210                              */
1211                             d=d-bcount/2-1;
1212                             *d++='"';
1213                             s++;
1214                         }
1215                         bcount=0;
1216                     }
1217                     else
1218                     {
1219                         /* a regular character */
1220                         *d++=*s++;
1221                         bcount=0;
1222                     }
1223                     if ((d-szPath) == pathSize)
1224                     {
1225                         /* Keep processing the path till we get to the
1226                          * arguments, but 'stand still'
1227                          */
1228                         d--;
1229                     }
1230                 }
1231                 /* Close the application path */
1232                 *d=0;
1233
1234                 lstrcpynW(szArgs, s, argsSize);
1235             }
1236             HeapFree( GetProcessHeap(), 0, szCmdline );
1237         }
1238         LocalFree( dar );
1239     }
1240
1241     IShellLinkDataList_Release( dl );
1242     return hr;
1243 }
1244
1245 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1246 {
1247     static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1248                                    '\\','s','t','a','r','t','.','e','x','e',0};
1249     char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1250     char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1251     WCHAR szTmp[INFOTIPSIZE];
1252     WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1253     WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1254     int iIconId = 0, r = -1;
1255     DWORD csidl = -1;
1256     HANDLE hsem = NULL;
1257
1258     if ( !link )
1259     {
1260         WINE_ERR("Link name is null\n");
1261         return FALSE;
1262     }
1263
1264     if( !GetLinkLocation( link, &csidl, &link_name ) )
1265     {
1266         WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1267         return TRUE;
1268     }
1269     if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1270     {
1271         WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1272         return TRUE;
1273     }
1274     WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));
1275
1276     szTmp[0] = 0;
1277     IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1278     ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1279     WINE_TRACE("workdir    : %s\n", wine_dbgstr_w(szWorkDir));
1280
1281     szTmp[0] = 0;
1282     IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1283     ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1284     WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1285
1286     get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1287     WINE_TRACE("path       : %s\n", wine_dbgstr_w(szPath));
1288     WINE_TRACE("args       : %s\n", wine_dbgstr_w(szArgs));
1289
1290     szTmp[0] = 0;
1291     IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1292     ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1293     WINE_TRACE("icon file  : %s\n", wine_dbgstr_w(szIconPath) );
1294
1295     if( !szPath[0] )
1296     {
1297         LPITEMIDLIST pidl = NULL;
1298         IShellLinkW_GetIDList( sl, &pidl );
1299         if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1300             WINE_TRACE("pidl path  : %s\n", wine_dbgstr_w(szPath));
1301     }
1302
1303     /* extract the icon */
1304     if( szIconPath[0] )
1305         icon_name = extract_icon( szIconPath , iIconId, bWait );
1306     else
1307         icon_name = extract_icon( szPath, iIconId, bWait );
1308
1309     /* fail - try once again after parent process exit */
1310     if( !icon_name )
1311     {
1312         if (bWait)
1313         {
1314             WINE_WARN("Unable to extract icon, deferring.\n");
1315             goto cleanup;
1316         }
1317         WINE_ERR("failed to extract icon from %s\n",
1318                  wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
1319     }
1320
1321     /* check the path */
1322     if( szPath[0] )
1323     {
1324         static const WCHAR exeW[] = {'.','e','x','e',0};
1325         WCHAR *p;
1326
1327         /* check for .exe extension */
1328         if (!(p = strrchrW( szPath, '.' )) ||
1329             strchrW( p, '\\' ) || strchrW( p, '/' ) ||
1330             lstrcmpiW( p, exeW ))
1331         {
1332             /* Not .exe - use 'start.exe' to launch this file */
1333             p = szArgs + lstrlenW(szPath) + 2;
1334             if (szArgs[0])
1335             {
1336                 p[0] = ' ';
1337                 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
1338                                            sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
1339             }
1340             else
1341                 p[0] = 0;
1342
1343             szArgs[0] = '"';
1344             lstrcpyW(szArgs + 1, szPath);
1345             p[-1] = '"';
1346
1347             GetWindowsDirectoryW(szPath, MAX_PATH);
1348             lstrcatW(szPath, startW);
1349         }
1350
1351         /* convert app working dir */
1352         if (szWorkDir[0])
1353             work_dir = wine_get_unix_file_name( szWorkDir );
1354     }
1355     else
1356     {
1357         /* if there's no path... try run the link itself */
1358         lstrcpynW(szArgs, link, MAX_PATH);
1359         GetWindowsDirectoryW(szPath, MAX_PATH);
1360         lstrcatW(szPath, startW);
1361     }
1362
1363     /* escape the path and parameters */
1364     escaped_path = escape(szPath);
1365     escaped_args = escape(szArgs);
1366     escaped_description = escape(szDescription);
1367
1368     /* building multiple menus concurrently has race conditions */
1369     hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1370     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
1371     {
1372         WINE_ERR("failed wait for semaphore\n");
1373         goto cleanup;
1374     }
1375
1376     if (in_desktop_dir(csidl))
1377     {
1378         char *location;
1379         const char *lastEntry;
1380         lastEntry = strrchr(link_name, '/');
1381         if (lastEntry == NULL)
1382             lastEntry = link_name;
1383         else
1384             ++lastEntry;
1385         location = heap_printf("%s/Desktop/%s.desktop", getenv("HOME"), lastEntry);
1386         if (location)
1387         {
1388             r = !write_desktop_entry(location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
1389             HeapFree(GetProcessHeap(), 0, location);
1390         }
1391     }
1392     else
1393         r = !write_menu_entry(link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
1394
1395     ReleaseSemaphore( hsem, 1, NULL );
1396
1397 cleanup:
1398     if (hsem) CloseHandle( hsem );
1399     HeapFree( GetProcessHeap(), 0, icon_name );
1400     HeapFree( GetProcessHeap(), 0, work_dir );
1401     HeapFree( GetProcessHeap(), 0, link_name );
1402     HeapFree( GetProcessHeap(), 0, escaped_args );
1403     HeapFree( GetProcessHeap(), 0, escaped_path );
1404     HeapFree( GetProcessHeap(), 0, escaped_description );
1405
1406     if (r && !bWait)
1407         WINE_ERR("failed to build the menu\n" );
1408
1409     return ( r == 0 );
1410 }
1411
1412 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
1413 {
1414     char *link_name = NULL;
1415     DWORD csidl = -1;
1416     LPWSTR urlPath;
1417     char *escaped_urlPath = NULL;
1418     HRESULT hr;
1419     HANDLE hSem = NULL;
1420     BOOL ret = TRUE;
1421     int r = -1;
1422
1423     if ( !link )
1424     {
1425         WINE_ERR("Link name is null\n");
1426         return TRUE;
1427     }
1428
1429     if( !GetLinkLocation( link, &csidl, &link_name ) )
1430     {
1431         WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1432         return TRUE;
1433     }
1434     if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1435     {
1436         WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1437         ret = TRUE;
1438         goto cleanup;
1439     }
1440     WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));
1441
1442     hr = url->lpVtbl->GetURL(url, &urlPath);
1443     if (FAILED(hr))
1444     {
1445         ret = TRUE;
1446         goto cleanup;
1447     }
1448     WINE_TRACE("path       : %s\n", wine_dbgstr_w(urlPath));
1449
1450     escaped_urlPath = escape(urlPath);
1451
1452     hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1453     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
1454     {
1455         WINE_ERR("failed wait for semaphore\n");
1456         goto cleanup;
1457     }
1458     if (in_desktop_dir(csidl))
1459     {
1460         char *location;
1461         const char *lastEntry;
1462         lastEntry = strrchr(link_name, '/');
1463         if (lastEntry == NULL)
1464             lastEntry = link_name;
1465         else
1466             ++lastEntry;
1467         location = heap_printf("%s/Desktop/%s.desktop", getenv("HOME"), lastEntry);
1468         if (location)
1469         {
1470             r = !write_desktop_entry(location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
1471             HeapFree(GetProcessHeap(), 0, location);
1472         }
1473     }
1474     else
1475         r = !write_menu_entry(link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
1476     ret = (r != 0);
1477     ReleaseSemaphore(hSem, 1, NULL);
1478
1479 cleanup:
1480     if (hSem)
1481         CloseHandle(hSem);
1482     HeapFree(GetProcessHeap(), 0, link_name);
1483     CoTaskMemFree( urlPath );
1484     HeapFree(GetProcessHeap(), 0, escaped_urlPath);
1485     return ret;
1486 }
1487
1488 static BOOL WaitForParentProcess( void )
1489 {
1490     PROCESSENTRY32 procentry;
1491     HANDLE hsnapshot = NULL, hprocess = NULL;
1492     DWORD ourpid = GetCurrentProcessId();
1493     BOOL ret = FALSE, rc;
1494
1495     WINE_TRACE("Waiting for parent process\n");
1496     if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
1497         INVALID_HANDLE_VALUE)
1498     {
1499         WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
1500         goto done;
1501     }
1502
1503     procentry.dwSize = sizeof(PROCESSENTRY32);
1504     rc = Process32First( hsnapshot, &procentry );
1505     while (rc)
1506     {
1507         if (procentry.th32ProcessID == ourpid) break;
1508         rc = Process32Next( hsnapshot, &procentry );
1509     }
1510     if (!rc)
1511     {
1512         WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
1513         goto done;
1514     }
1515
1516     if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
1517         NULL)
1518     {
1519         WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
1520                  GetLastError());
1521         goto done;
1522     }
1523
1524     if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
1525         ret = TRUE;
1526     else
1527         WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
1528
1529 done:
1530     if (hprocess) CloseHandle( hprocess );
1531     if (hsnapshot) CloseHandle( hsnapshot );
1532     return ret;
1533 }
1534
1535 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
1536 {
1537     IShellLinkW *sl;
1538     IPersistFile *pf;
1539     HRESULT r;
1540     WCHAR fullname[MAX_PATH];
1541     DWORD len;
1542
1543     WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
1544
1545     if( !linkname[0] )
1546     {
1547         WINE_ERR("link name missing\n");
1548         return 1;
1549     }
1550
1551     len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1552     if (len==0 || len>MAX_PATH)
1553     {
1554         WINE_ERR("couldn't get full path of link file\n");
1555         return 1;
1556     }
1557
1558     r = CoInitialize( NULL );
1559     if( FAILED( r ) )
1560     {
1561         WINE_ERR("CoInitialize failed\n");
1562         return 1;
1563     }
1564
1565     r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1566                           &IID_IShellLinkW, (LPVOID *) &sl );
1567     if( FAILED( r ) )
1568     {
1569         WINE_ERR("No IID_IShellLink\n");
1570         return 1;
1571     }
1572
1573     r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1574     if( FAILED( r ) )
1575     {
1576         WINE_ERR("No IID_IPersistFile\n");
1577         return 1;
1578     }
1579
1580     r = IPersistFile_Load( pf, fullname, STGM_READ );
1581     if( SUCCEEDED( r ) )
1582     {
1583         /* If something fails (eg. Couldn't extract icon)
1584          * wait for parent process and try again
1585          */
1586         if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
1587         {
1588             WaitForParentProcess();
1589             InvokeShellLinker( sl, fullname, FALSE );
1590         }
1591     }
1592     else
1593     {
1594         WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
1595     }
1596
1597     IPersistFile_Release( pf );
1598     IShellLinkW_Release( sl );
1599
1600     CoUninitialize();
1601
1602     return !r;
1603 }
1604
1605 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
1606 {
1607     IUniformResourceLocatorW *url;
1608     IPersistFile *pf;
1609     HRESULT r;
1610     WCHAR fullname[MAX_PATH];
1611     DWORD len;
1612
1613     WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
1614
1615     if( !urlname[0] )
1616     {
1617         WINE_ERR("URL name missing\n");
1618         return 1;
1619     }
1620
1621     len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
1622     if (len==0 || len>MAX_PATH)
1623     {
1624         WINE_ERR("couldn't get full path of URL file\n");
1625         return 1;
1626     }
1627
1628     r = CoInitialize( NULL );
1629     if( FAILED( r ) )
1630     {
1631         WINE_ERR("CoInitialize failed\n");
1632         return 1;
1633     }
1634
1635     r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
1636                           &IID_IUniformResourceLocatorW, (LPVOID *) &url );
1637     if( FAILED( r ) )
1638     {
1639         WINE_ERR("No IID_IUniformResourceLocatorW\n");
1640         return 1;
1641     }
1642
1643     r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
1644     if( FAILED( r ) )
1645     {
1646         WINE_ERR("No IID_IPersistFile\n");
1647         return 1;
1648     }
1649     r = IPersistFile_Load( pf, fullname, STGM_READ );
1650     if( SUCCEEDED( r ) )
1651     {
1652         /* If something fails (eg. Couldn't extract icon)
1653          * wait for parent process and try again
1654          */
1655         if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
1656         {
1657             WaitForParentProcess();
1658             InvokeShellLinkerForURL( url, fullname, FALSE );
1659         }
1660     }
1661
1662     IPersistFile_Release( pf );
1663     url->lpVtbl->Release( url );
1664
1665     CoUninitialize();
1666
1667     return !r;
1668 }
1669
1670 static CHAR *next_token( LPSTR *p )
1671 {
1672     LPSTR token = NULL, t = *p;
1673
1674     if( !t )
1675         return NULL;
1676
1677     while( t && !token )
1678     {
1679         switch( *t )
1680         {
1681         case ' ':
1682             t++;
1683             continue;
1684         case '"':
1685             /* unquote the token */
1686             token = ++t;
1687             t = strchr( token, '"' );
1688             if( t )
1689                  *t++ = 0;
1690             break;
1691         case 0:
1692             t = NULL;
1693             break;
1694         default:
1695             token = t;
1696             t = strchr( token, ' ' );
1697             if( t )
1698                  *t++ = 0;
1699             break;
1700         }
1701     }
1702     *p = t;
1703     return token;
1704 }
1705
1706 static BOOL init_xdg(void)
1707 {
1708     if (getenv("XDG_CONFIG_HOME"))
1709         xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
1710     else
1711         xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
1712     if (xdg_config_dir)
1713     {
1714         create_directories(xdg_config_dir);
1715         if (getenv("XDG_DATA_HOME"))
1716             xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
1717         else
1718             xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
1719         if (xdg_data_dir)
1720         {
1721             char *buffer;
1722             create_directories(xdg_data_dir);
1723             buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
1724             if (buffer)
1725             {
1726                 mkdir(buffer, 0777);
1727                 HeapFree(GetProcessHeap(), 0, buffer);
1728             }
1729             return TRUE;
1730         }
1731         HeapFree(GetProcessHeap(), 0, xdg_config_dir);
1732     }
1733     return FALSE;
1734 }
1735
1736 /***********************************************************************
1737  *
1738  *           WinMain
1739  */
1740 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1741 {
1742     LPSTR token = NULL, p;
1743     BOOL bWait = FALSE;
1744     BOOL bURL = FALSE;
1745     int ret = 0;
1746
1747     init_xdg();
1748
1749     for( p = cmdline; p && *p; )
1750     {
1751         token = next_token( &p );
1752         if( !token )
1753             break;
1754         if( !lstrcmpA( token, "-w" ) )
1755             bWait = TRUE;
1756         else if ( !lstrcmpA( token, "-u" ) )
1757             bURL = TRUE;
1758         else if( token[0] == '-' )
1759         {
1760             WINE_ERR( "unknown option %s\n",token);
1761         }
1762         else
1763         {
1764             WCHAR link[MAX_PATH];
1765             BOOL bRet;
1766
1767             MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1768             if (bURL)
1769                 bRet = Process_URL( link, bWait );
1770             else
1771                 bRet = Process_Link( link, bWait );
1772             if (!bRet)
1773             {
1774                 WINE_ERR( "failed to build menu item for %s\n",token);
1775                 ret = 1;
1776             }
1777         }
1778     }
1779
1780     return ret;
1781 }