winemenubuilder: Use a unicode WinMain.
[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  *  Clean up fd.o menu icons and .directory files when the menu is deleted
54  * in Windows.
55  *  Generate icons for file open handlers to go into the "Open with..."
56  * list. What does Windows use, the default icon for the .EXE file? It's
57  * not in the registry.
58  *  Associate applications under HKCR\Applications to open any MIME type
59  * (by associating with application/octet-stream, or how?).
60  *  Clean up fd.o MIME types when they are deleted in Windows, their icons
61  * too. Very hard - once we associate them with fd.o, we can't tell whether
62  * they are ours or not, and the extension <-> MIME type mapping isn't
63  * one-to-one either.
64  *  Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
65  * that write associations there won't associate (#17019).
66  */
67
68 #include "config.h"
69 #include "wine/port.h"
70
71 #include <ctype.h>
72 #include <stdio.h>
73 #include <string.h>
74 #ifdef HAVE_UNISTD_H
75 #include <unistd.h>
76 #endif
77 #include <errno.h>
78 #include <stdarg.h>
79 #ifdef HAVE_FNMATCH_H
80 #include <fnmatch.h>
81 #endif
82
83 #define COBJMACROS
84
85 #include <windows.h>
86 #include <shlobj.h>
87 #include <objidl.h>
88 #include <shlguid.h>
89 #include <appmgmt.h>
90 #include <tlhelp32.h>
91 #include <intshcut.h>
92 #include <shlwapi.h>
93
94 #include "wine/unicode.h"
95 #include "wine/debug.h"
96 #include "wine/library.h"
97 #include "wine/list.h"
98 #include "wine.xpm"
99
100 #ifdef HAVE_PNG_H
101 #undef FAR
102 #include <png.h>
103 #endif
104
105 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
106
107 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
108                                (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
109 #define in_startmenu(csidl)   ((csidl)==CSIDL_STARTMENU || \
110                                (csidl)==CSIDL_COMMON_STARTMENU)
111         
112 /* link file formats */
113
114 #include "pshpack1.h"
115
116 typedef struct
117 {
118     BYTE bWidth;
119     BYTE bHeight;
120     BYTE bColorCount;
121     BYTE bReserved;
122     WORD wPlanes;
123     WORD wBitCount;
124     DWORD dwBytesInRes;
125     WORD nID;
126 } GRPICONDIRENTRY;
127
128 typedef struct
129 {
130     WORD idReserved;
131     WORD idType;
132     WORD idCount;
133     GRPICONDIRENTRY idEntries[1];
134 } GRPICONDIR;
135
136 typedef struct
137 {
138     BYTE bWidth;
139     BYTE bHeight;
140     BYTE bColorCount;
141     BYTE bReserved;
142     WORD wPlanes;
143     WORD wBitCount;
144     DWORD dwBytesInRes;
145     DWORD dwImageOffset;
146 } ICONDIRENTRY;
147
148 typedef struct
149 {
150     WORD idReserved;
151     WORD idType;
152     WORD idCount;
153 } ICONDIR;
154
155
156 #include "poppack.h"
157
158 typedef struct
159 {
160         HRSRC *pResInfo;
161         int   nIndex;
162 } ENUMRESSTRUCT;
163
164 struct xdg_mime_type
165 {
166     char *mimeType;
167     char *glob;
168     struct list entry;
169 };
170
171 static char *xdg_config_dir;
172 static char *xdg_data_dir;
173 static char *xdg_desktop_dir;
174
175 /* Icon extraction routines
176  *
177  * FIXME: should use PrivateExtractIcons and friends
178  * FIXME: should not use stdio
179  */
180
181 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
182
183 /* PNG-specific code */
184 #ifdef SONAME_LIBPNG
185
186 static void *libpng_handle;
187 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
188 MAKE_FUNCPTR(png_create_info_struct);
189 MAKE_FUNCPTR(png_create_write_struct);
190 MAKE_FUNCPTR(png_destroy_write_struct);
191 MAKE_FUNCPTR(png_get_error_ptr);
192 MAKE_FUNCPTR(png_init_io);
193 MAKE_FUNCPTR(png_set_bgr);
194 MAKE_FUNCPTR(png_set_error_fn);
195 MAKE_FUNCPTR(png_set_text);
196 MAKE_FUNCPTR(png_set_IHDR);
197 MAKE_FUNCPTR(png_write_end);
198 MAKE_FUNCPTR(png_write_info);
199 MAKE_FUNCPTR(png_write_row);
200 #undef MAKE_FUNCPTR
201
202 static void *load_libpng(void)
203 {
204     if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
205     {
206 #define LOAD_FUNCPTR(f) \
207     if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
208         libpng_handle = NULL; \
209         return NULL; \
210     }
211         LOAD_FUNCPTR(png_create_info_struct);
212         LOAD_FUNCPTR(png_create_write_struct);
213         LOAD_FUNCPTR(png_destroy_write_struct);
214         LOAD_FUNCPTR(png_get_error_ptr);
215         LOAD_FUNCPTR(png_init_io);
216         LOAD_FUNCPTR(png_set_bgr);
217         LOAD_FUNCPTR(png_set_error_fn);
218         LOAD_FUNCPTR(png_set_IHDR);
219         LOAD_FUNCPTR(png_set_text);
220         LOAD_FUNCPTR(png_write_end);
221         LOAD_FUNCPTR(png_write_info);
222         LOAD_FUNCPTR(png_write_row);
223 #undef LOAD_FUNCPTR
224     }
225     return libpng_handle;
226 }
227
228 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
229 {
230     jmp_buf *pjmpbuf;
231
232     /* This uses setjmp/longjmp just like the default. We can't use the
233      * default because there's no way to access the jmp buffer in the png_struct
234      * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
235     WINE_ERR("PNG error: %s\n", wine_dbgstr_an(error_message, -1));
236     pjmpbuf = ppng_get_error_ptr(png_ptr);
237     longjmp(*pjmpbuf, 1);
238 }
239
240 static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
241 {
242     WINE_WARN("PNG warning: %s\n", wine_dbgstr_an(warning_message, -1));
243 }
244
245 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
246 {
247     static const char comment_key[] = "Created from";
248     FILE *fp;
249     png_structp png_ptr;
250     png_infop info_ptr;
251     png_text comment;
252     int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
253     BYTE *row, *copy = NULL;
254     const BYTE *pXOR, *pAND = NULL;
255     int nWidth  = pIcon->bmiHeader.biWidth;
256     int nHeight = pIcon->bmiHeader.biHeight;
257     int nBpp    = pIcon->bmiHeader.biBitCount;
258     jmp_buf jmpbuf;
259
260     switch (nBpp)
261     {
262     case 32:
263         color_type |= PNG_COLOR_MASK_ALPHA;
264         /* fall through */
265     case 24:
266         color_type |= PNG_COLOR_MASK_COLOR;
267         break;
268     default:
269         return FALSE;
270     }
271
272     if (!libpng_handle && !load_libpng())
273     {
274         WINE_WARN("Unable to load libpng\n");
275         return FALSE;
276     }
277
278     if (!(fp = fopen(png_filename, "w")))
279     {
280         WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
281         return FALSE;
282     }
283
284     nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
285     nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
286     pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
287     if (nHeight > nWidth)
288     {
289         nHeight /= 2;
290         pAND = pXOR + nHeight * nXORWidthBytes;
291     }
292
293     /* Apply mask if present */
294     if (pAND)
295     {
296         RGBQUAD bgColor;
297
298         /* copy bytes before modifying them */
299         copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
300         memcpy( copy, pXOR, nHeight * nXORWidthBytes );
301         pXOR = copy;
302
303         /* image and mask are upside down reversed */
304         row = copy + (nHeight - 1) * nXORWidthBytes;
305
306         /* top left corner */
307         bgColor.rgbRed   = row[0];
308         bgColor.rgbGreen = row[1];
309         bgColor.rgbBlue  = row[2];
310         bgColor.rgbReserved = 0;
311
312         for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
313             for (j = 0; j < nWidth; j++, row += nBpp >> 3)
314                 if (MASK(j, i))
315                 {
316                     RGBQUAD *pixel = (RGBQUAD *)row;
317                     pixel->rgbBlue  = bgColor.rgbBlue;
318                     pixel->rgbGreen = bgColor.rgbGreen;
319                     pixel->rgbRed   = bgColor.rgbRed;
320                     if (nBpp == 32)
321                         pixel->rgbReserved = bgColor.rgbReserved;
322                 }
323     }
324
325     comment.text = NULL;
326
327     if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
328         !(info_ptr = ppng_create_info_struct(png_ptr)))
329         goto error;
330
331     if (setjmp(jmpbuf))
332     {
333         /* All future errors jump here */
334         goto error;
335     }
336     ppng_set_error_fn(png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
337
338     ppng_init_io(png_ptr, fp);
339     ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
340                   color_type,
341                   PNG_INTERLACE_NONE,
342                   PNG_COMPRESSION_TYPE_DEFAULT,
343                   PNG_FILTER_TYPE_DEFAULT);
344
345     /* Set comment */
346     comment.compression = PNG_TEXT_COMPRESSION_NONE;
347     comment.key = (png_charp)comment_key;
348     i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
349     comment.text = HeapAlloc(GetProcessHeap(), 0, i);
350     WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
351     comment.text_length = i - 1;
352     ppng_set_text(png_ptr, info_ptr, &comment, 1);
353
354
355     ppng_write_info(png_ptr, info_ptr);
356     ppng_set_bgr(png_ptr);
357     for (i = nHeight - 1; i >= 0 ; i--)
358         ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
359     ppng_write_end(png_ptr, info_ptr);
360
361     ppng_destroy_write_struct(&png_ptr, &info_ptr);
362     if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
363     fclose(fp);
364     HeapFree(GetProcessHeap(), 0, copy);
365     HeapFree(GetProcessHeap(), 0, comment.text);
366     return TRUE;
367
368  error:
369     if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
370     fclose(fp);
371     unlink(png_filename);
372     HeapFree(GetProcessHeap(), 0, copy);
373     HeapFree(GetProcessHeap(), 0, comment.text);
374     return FALSE;
375 }
376 #endif /* SONAME_LIBPNG */
377
378 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
379 {
380     FILE *fXPMFile;
381     int nHeight;
382     int nXORWidthBytes;
383     int nANDWidthBytes;
384     BOOL b8BitColors;
385     int nColors;
386     const BYTE *pXOR;
387     const BYTE *pAND;
388     BOOL aColorUsed[256] = {0};
389     int nColorsUsed = 0;
390     int i,j;
391     char *comment;
392
393     if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
394     {
395         WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
396         return FALSE;
397     }
398
399     if (!(fXPMFile = fopen(szXPMFileName, "w")))
400     {
401         WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
402         return FALSE;
403     }
404
405     i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
406     comment = HeapAlloc(GetProcessHeap(), 0, i);
407     WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
408
409     nHeight = pIcon->bmiHeader.biHeight / 2;
410     nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
411                           + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
412     nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
413                           + ((pIcon->bmiHeader.biWidth % 32) > 0));
414     b8BitColors = pIcon->bmiHeader.biBitCount == 8;
415     nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
416         : 1 << pIcon->bmiHeader.biBitCount;
417     pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
418     pAND = pXOR + nHeight * nXORWidthBytes;
419
420 #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)
421
422     for (i = 0; i < nHeight; i++) {
423         for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
424             if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
425             {
426                 aColorUsed[COLOR(j,i)] = TRUE;
427                 nColorsUsed++;
428             }
429         }
430     }
431
432     if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
433         goto error;
434     if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
435                 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
436         goto error;
437
438     for (i = 0; i < nColors; i++) {
439         if (aColorUsed[i])
440             if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
441                         pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
442                 goto error;
443     }
444     if (fprintf(fXPMFile, "\"   c None\"") <= 0)
445         goto error;
446
447     for (i = 0; i < nHeight; i++)
448     {
449         if (fprintf(fXPMFile, ",\n\"") <= 0)
450             goto error;
451         for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
452         {
453             if MASK(j,i)
454                 {
455                     if (fprintf(fXPMFile, "  ") <= 0)
456                         goto error;
457                 }
458             else
459                 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
460                     goto error;
461         }
462         if (fprintf(fXPMFile, "\"") <= 0)
463             goto error;
464     }
465     if (fprintf(fXPMFile, "};\n") <= 0)
466         goto error;
467
468 #undef MASK
469 #undef COLOR
470
471     HeapFree(GetProcessHeap(), 0, comment);
472     fclose(fXPMFile);
473     return TRUE;
474
475  error:
476     HeapFree(GetProcessHeap(), 0, comment);
477     fclose(fXPMFile);
478     unlink( szXPMFileName );
479     return FALSE;
480 }
481
482 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
483 {
484     ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
485
486     if (!sEnumRes->nIndex--)
487     {
488         *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
489         return FALSE;
490     }
491     else
492         return TRUE;
493 }
494
495 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
496 {
497     HMODULE hModule;
498     HRSRC hResInfo;
499     LPCWSTR lpName = NULL;
500     HGLOBAL hResData;
501     GRPICONDIR *pIconDir;
502     BITMAPINFO *pIcon;
503     ENUMRESSTRUCT sEnumRes;
504     int nMax = 0;
505     int nMaxBits = 0;
506     int i;
507     BOOL ret = FALSE;
508
509     hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
510     if (!hModule)
511     {
512         WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
513                  wine_dbgstr_w(szFileName), GetLastError());
514         return FALSE;
515     }
516
517     if (nIndex < 0)
518     {
519         hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
520         WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
521                    wine_dbgstr_w(szFileName), hResInfo, GetLastError());
522     }
523     else
524     {
525         hResInfo=NULL;
526         sEnumRes.pResInfo = &hResInfo;
527         sEnumRes.nIndex = nIndex;
528         if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
529                                 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
530             sEnumRes.nIndex != -1)
531         {
532             WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
533         }
534     }
535
536     if (hResInfo)
537     {
538         if ((hResData = LoadResource(hModule, hResInfo)))
539         {
540             if ((pIconDir = LockResource(hResData)))
541             {
542                 for (i = 0; i < pIconDir->idCount; i++)
543                 {
544                     if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
545                     {
546                         if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
547                         {
548                             lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
549                             nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
550                             nMaxBits = pIconDir->idEntries[i].wBitCount;
551                         }
552                     }               
553                 }
554             }
555
556             FreeResource(hResData);
557         }
558     }
559     else
560     {
561         WINE_WARN("found no icon\n");
562         FreeLibrary(hModule);
563         return FALSE;
564     }
565  
566     if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
567     {
568         if ((hResData = LoadResource(hModule, hResInfo)))
569         {
570             if ((pIcon = LockResource(hResData)))
571             {
572 #ifdef SONAME_LIBPNG
573                 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
574                     ret = TRUE;
575                 else
576 #endif
577                 {
578                     memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
579                     if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
580                         ret = TRUE;
581                 }
582             }
583
584             FreeResource(hResData);
585         }
586     }
587
588     FreeLibrary(hModule);
589     return ret;
590 }
591
592 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
593 {
594     if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
595         !extract_icon16(szFileName, szXPMFileName)*/)
596         return FALSE;
597     return TRUE;
598 }
599
600 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
601 {
602     FILE *fICOFile = NULL;
603     ICONDIR iconDir;
604     ICONDIRENTRY *pIconDirEntry = NULL;
605     int nMax = 0, nMaxBits = 0;
606     int nIndex = 0;
607     void *pIcon = NULL;
608     int i;
609     char *filename = NULL;
610
611     filename = wine_get_unix_file_name(szFileName);
612     if (!(fICOFile = fopen(filename, "r")))
613     {
614         WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
615         goto error;
616     }
617
618     if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
619         (iconDir.idReserved != 0) || (iconDir.idType != 1))
620     {
621         WINE_WARN("Invalid ico file format\n");
622         goto error;
623     }
624
625     if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
626         goto error;
627     if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
628         goto error;
629
630     for (i = 0; i < iconDir.idCount; i++)
631     {
632         WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
633         if (pIconDirEntry[i].wBitCount >= nMaxBits &&
634             (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
635         {
636             nIndex = i;
637             nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
638             nMaxBits = pIconDirEntry[i].wBitCount;
639         }
640     }
641     WINE_TRACE("Selected: %d\n", nIndex);
642
643     if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
644         goto error;
645     if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
646         goto error;
647     if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
648         goto error;
649
650
651     /* Prefer PNG over XPM */
652 #ifdef SONAME_LIBPNG
653     if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
654 #endif
655     {
656         memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
657         if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
658             goto error;
659     }
660
661     HeapFree(GetProcessHeap(), 0, pIcon);
662     HeapFree(GetProcessHeap(), 0, pIconDirEntry);
663     fclose(fICOFile);
664     HeapFree(GetProcessHeap(), 0, filename);
665     return 1;
666
667  error:
668     HeapFree(GetProcessHeap(), 0, pIcon);
669     HeapFree(GetProcessHeap(), 0, pIconDirEntry);
670     if (fICOFile) fclose(fICOFile);
671     HeapFree(GetProcessHeap(), 0, filename);
672     return 0;
673 }
674
675 static BOOL create_default_icon( const char *filename, const char* comment )
676 {
677     FILE *fXPM;
678     unsigned int i;
679
680     if (!(fXPM = fopen(filename, "w"))) return FALSE;
681     if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
682         goto error;
683     for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
684         if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
685             goto error;
686     }
687     if (fprintf( fXPM, "};\n" ) <=0)
688         goto error;
689     fclose( fXPM );
690     return TRUE;
691  error:
692     fclose( fXPM );
693     unlink( filename );
694     return FALSE;
695
696 }
697
698 static unsigned short crc16(const char* string)
699 {
700     unsigned short crc = 0;
701     int i, j, xor_poly;
702
703     for (i = 0; string[i] != 0; i++)
704     {
705         char c = string[i];
706         for (j = 0; j < 8; c >>= 1, j++)
707         {
708             xor_poly = (c ^ crc) & 1;
709             crc >>= 1;
710             if (xor_poly)
711                 crc ^= 0xa001;
712         }
713     }
714     return crc;
715 }
716
717 static char *strdupA( const char *str )
718 {
719     char *ret;
720
721     if (!str) return NULL;
722     if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
723     return ret;
724 }
725
726 static char* heap_printf(const char *format, ...)
727 {
728     va_list args;
729     int size = 4096;
730     char *buffer, *ret;
731     int n;
732
733     va_start(args, format);
734     while (1)
735     {
736         buffer = HeapAlloc(GetProcessHeap(), 0, size);
737         if (buffer == NULL)
738             break;
739         n = vsnprintf(buffer, size, format, args);
740         if (n == -1)
741             size *= 2;
742         else if (n >= size)
743             size = n + 1;
744         else
745             break;
746         HeapFree(GetProcessHeap(), 0, buffer);
747     }
748     va_end(args);
749     if (!buffer) return NULL;
750     ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
751     if (!ret) ret = buffer;
752     return ret;
753 }
754
755 static void write_xml_text(FILE *file, const char *text)
756 {
757     int i;
758     for (i = 0; text[i]; i++)
759     {
760         if (text[i] == '&')
761             fputs("&amp;", file);
762         else if (text[i] == '<')
763             fputs("&lt;", file);
764         else if (text[i] == '>')
765             fputs("&gt;", file);
766         else if (text[i] == '\'')
767             fputs("&apos;", file);
768         else if (text[i] == '"')
769             fputs("&quot;", file);
770         else
771             fputc(text[i], file);
772     }
773 }
774
775 static BOOL create_directories(char *directory)
776 {
777     BOOL ret = TRUE;
778     int i;
779
780     for (i = 0; directory[i]; i++)
781     {
782         if (i > 0 && directory[i] == '/')
783         {
784             directory[i] = 0;
785             mkdir(directory, 0777);
786             directory[i] = '/';
787         }
788     }
789     if (mkdir(directory, 0777) && errno != EEXIST)
790        ret = FALSE;
791
792     return ret;
793 }
794
795 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
796 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
797 {
798     unsigned short crc;
799     char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
800     char* s;
801     int n;
802
803     /* Where should we save the icon? */
804     WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
805     iconsdir = heap_printf("%s/icons", xdg_data_dir);
806     if (iconsdir)
807     {
808         if (mkdir(iconsdir, 0777) && errno != EEXIST)
809         {
810             WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
811             goto end;
812         }
813     }
814     else
815     {
816         WINE_TRACE("no icon created\n");
817         return NULL;
818     }
819     
820     /* Determine the icon base name */
821     n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
822     ico_path = HeapAlloc(GetProcessHeap(), 0, n);
823     WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
824     s=ico_name=ico_path;
825     while (*s!='\0') {
826         if (*s=='/' || *s=='\\') {
827             *s='\\';
828             ico_name=s;
829         } else {
830             *s=tolower(*s);
831         }
832         s++;
833     }
834     if (*ico_name=='\\') *ico_name++='\0';
835     s=strrchr(ico_name,'.');
836     if (s) *s='\0';
837
838     /* Compute the source-path hash */
839     crc=crc16(ico_path);
840
841     /* Try to treat the source file as an exe */
842     if (destFilename)
843         xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
844     else
845         xpm_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
846     if (xpm_path == NULL)
847     {
848         WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
849         return NULL;
850     }
851
852     if (ExtractFromEXEDLL( path, index, xpm_path ))
853         goto end;
854
855     /* Must be something else, ignore the index in that case */
856     if (destFilename)
857         sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
858     else
859         sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
860     if (ExtractFromICO( path, xpm_path))
861         goto end;
862     if (!bWait)
863     {
864         if (destFilename)
865             sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
866         else
867             sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
868         if (create_default_icon( xpm_path, ico_path ))
869             goto end;
870     }
871
872     HeapFree( GetProcessHeap(), 0, xpm_path );
873     xpm_path=NULL;
874
875  end:
876     HeapFree(GetProcessHeap(), 0, iconsdir);
877     HeapFree(GetProcessHeap(), 0, ico_path);
878     return xpm_path;
879 }
880
881 static HKEY open_menus_reg_key(void)
882 {
883     static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
884         'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
885     HKEY assocKey;
886     DWORD ret;
887     ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
888     if (ret == ERROR_SUCCESS)
889         return assocKey;
890     SetLastError(ret);
891     return NULL;
892 }
893
894 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
895 {
896     WCHAR *unix_fileW;
897     WCHAR *windows_fileW;
898     INT size;
899     DWORD ret;
900
901     size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
902     unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
903     if (unix_fileW)
904     {
905         MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
906         size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
907         windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
908         if (windows_fileW)
909         {
910             HKEY hkey;
911             MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
912             hkey = open_menus_reg_key();
913             if (hkey)
914             {
915                 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
916                     (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
917                 RegCloseKey(hkey);
918             }
919             else
920                 ret = GetLastError();
921             HeapFree(GetProcessHeap(), 0, windows_fileW);
922         }
923         else
924             ret = ERROR_NOT_ENOUGH_MEMORY;
925         HeapFree(GetProcessHeap(), 0, unix_fileW);
926     }
927     else
928         ret = ERROR_NOT_ENOUGH_MEMORY;
929     return ret;
930 }
931
932 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
933                                 const char *path, const char *args, const char *descr,
934                                 const char *workdir, const char *icon)
935 {
936     FILE *file;
937
938     WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
939                wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
940                wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
941
942     file = fopen(location, "w");
943     if (file == NULL)
944         return FALSE;
945
946     fprintf(file, "[Desktop Entry]\n");
947     fprintf(file, "Name=%s\n", linkname);
948     fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
949             wine_get_config_dir(), path, args);
950     fprintf(file, "Type=Application\n");
951     fprintf(file, "StartupNotify=true\n");
952     if (descr && lstrlenA(descr))
953         fprintf(file, "Comment=%s\n", descr);
954     if (workdir && lstrlenA(workdir))
955         fprintf(file, "Path=%s\n", workdir);
956     if (icon && lstrlenA(icon))
957         fprintf(file, "Icon=%s\n", icon);
958
959     fclose(file);
960
961     if (unix_link)
962     {
963         DWORD ret = register_menus_entry(location, unix_link);
964         if (ret != ERROR_SUCCESS)
965             return FALSE;
966     }
967
968     return TRUE;
969 }
970
971 static BOOL write_directory_entry(const char *directory, const char *location)
972 {
973     FILE *file;
974
975     WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
976
977     file = fopen(location, "w");
978     if (file == NULL)
979         return FALSE;
980
981     fprintf(file, "[Desktop Entry]\n");
982     fprintf(file, "Type=Directory\n");
983     if (strcmp(directory, "wine") == 0)
984     {
985         fprintf(file, "Name=Wine\n");
986         fprintf(file, "Icon=wine\n");
987     }
988     else
989     {
990         fprintf(file, "Name=%s\n", directory);
991         fprintf(file, "Icon=folder\n");
992     }
993
994     fclose(file);
995     return TRUE;
996 }
997
998 static BOOL write_menu_file(const char *unix_link, const char *filename)
999 {
1000     char *tempfilename;
1001     FILE *tempfile = NULL;
1002     char *lastEntry;
1003     char *name = NULL;
1004     char *menuPath = NULL;
1005     int i;
1006     int count = 0;
1007     BOOL ret = FALSE;
1008
1009     WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1010
1011     while (1)
1012     {
1013         tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1014         if (tempfilename)
1015         {
1016             int tempfd = mkstemps(tempfilename, 0);
1017             if (tempfd >= 0)
1018             {
1019                 tempfile = fdopen(tempfd, "w");
1020                 if (tempfile)
1021                     break;
1022                 close(tempfd);
1023                 goto end;
1024             }
1025             else if (errno == EEXIST)
1026             {
1027                 HeapFree(GetProcessHeap(), 0, tempfilename);
1028                 continue;
1029             }
1030             HeapFree(GetProcessHeap(), 0, tempfilename);
1031         }
1032         return FALSE;
1033     }
1034
1035     fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1036     fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1037     fprintf(tempfile, "<Menu>\n");
1038     fprintf(tempfile, "  <Name>Applications</Name>\n");
1039
1040     name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1041     if (name == NULL) goto end;
1042     lastEntry = name;
1043     for (i = 0; filename[i]; i++)
1044     {
1045         name[i] = filename[i];
1046         if (filename[i] == '/')
1047         {
1048             char *dir_file_name;
1049             struct stat st;
1050             name[i] = 0;
1051             fprintf(tempfile, "  <Menu>\n");
1052             fprintf(tempfile, "    <Name>%s", count ? "" : "wine-");
1053             write_xml_text(tempfile, name);
1054             fprintf(tempfile, "</Name>\n");
1055             fprintf(tempfile, "    <Directory>%s", count ? "" : "wine-");
1056             write_xml_text(tempfile, name);
1057             fprintf(tempfile, ".directory</Directory>\n");
1058             dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1059                 xdg_data_dir, count ? "" : "wine-", name);
1060             if (dir_file_name)
1061             {
1062                 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1063                     write_directory_entry(lastEntry, dir_file_name);
1064                 HeapFree(GetProcessHeap(), 0, dir_file_name);
1065             }
1066             name[i] = '-';
1067             lastEntry = &name[i+1];
1068             ++count;
1069         }
1070     }
1071     name[i] = 0;
1072
1073     fprintf(tempfile, "    <Include>\n");
1074     fprintf(tempfile, "      <Filename>");
1075     write_xml_text(tempfile, name);
1076     fprintf(tempfile, "</Filename>\n");
1077     fprintf(tempfile, "    </Include>\n");
1078     for (i = 0; i < count; i++)
1079          fprintf(tempfile, "  </Menu>\n");
1080     fprintf(tempfile, "</Menu>\n");
1081
1082     menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1083     if (menuPath == NULL) goto end;
1084     strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1085     ret = TRUE;
1086
1087 end:
1088     if (tempfile)
1089         fclose(tempfile);
1090     if (ret)
1091         ret = (rename(tempfilename, menuPath) == 0);
1092     if (!ret && tempfilename)
1093         remove(tempfilename);
1094     HeapFree(GetProcessHeap(), 0, tempfilename);
1095     if (ret)
1096         register_menus_entry(menuPath, unix_link);
1097     HeapFree(GetProcessHeap(), 0, name);
1098     HeapFree(GetProcessHeap(), 0, menuPath);
1099     return ret;
1100 }
1101
1102 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1103                              const char *descr, const char *workdir, const char *icon)
1104 {
1105     const char *linkname;
1106     char *desktopPath = NULL;
1107     char *desktopDir;
1108     char *filename = NULL;
1109     BOOL ret = TRUE;
1110
1111     WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1112                wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1113                wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1114
1115     linkname = strrchr(link, '/');
1116     if (linkname == NULL)
1117         linkname = link;
1118     else
1119         ++linkname;
1120
1121     desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1122     if (!desktopPath)
1123     {
1124         WINE_WARN("out of memory creating menu entry\n");
1125         ret = FALSE;
1126         goto end;
1127     }
1128     desktopDir = strrchr(desktopPath, '/');
1129     *desktopDir = 0;
1130     if (!create_directories(desktopPath))
1131     {
1132         WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1133         ret = FALSE;
1134         goto end;
1135     }
1136     *desktopDir = '/';
1137     if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1138     {
1139         WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1140         ret = FALSE;
1141         goto end;
1142     }
1143
1144     filename = heap_printf("wine/%s.desktop", link);
1145     if (!filename || !write_menu_file(unix_link, filename))
1146     {
1147         WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1148         ret = FALSE;
1149     }
1150
1151 end:
1152     HeapFree(GetProcessHeap(), 0, desktopPath);
1153     HeapFree(GetProcessHeap(), 0, filename);
1154     return ret;
1155 }
1156
1157 /* This escapes \ in filenames */
1158 static LPSTR escape(LPCWSTR arg)
1159 {
1160     LPSTR narg, x;
1161     LPCWSTR esc;
1162     int len = 0, n;
1163
1164     esc = arg;
1165     while((esc = strchrW(esc, '\\')))
1166     {
1167         esc++;
1168         len++;
1169     }
1170
1171     len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1172     narg = HeapAlloc(GetProcessHeap(), 0, len);
1173
1174     x = narg;
1175     while (*arg)
1176     {
1177         n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1178         x += n;
1179         len -= n;
1180         if (*arg == '\\')
1181             *x++='\\'; /* escape \ */
1182         arg++;
1183     }
1184     *x = 0;
1185     return narg;
1186 }
1187
1188 /* Return a heap-allocated copy of the unix format difference between the two
1189  * Windows-format paths.
1190  * locn is the owning location
1191  * link is within locn
1192  */
1193 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1194 {
1195     char *unix_locn, *unix_link;
1196     char *relative = NULL;
1197
1198     unix_locn = wine_get_unix_file_name(locn);
1199     unix_link = wine_get_unix_file_name(link);
1200     if (unix_locn && unix_link)
1201     {
1202         size_t len_unix_locn, len_unix_link;
1203         len_unix_locn = strlen (unix_locn);
1204         len_unix_link = strlen (unix_link);
1205         if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1206         {
1207             size_t len_rel;
1208             char *p = strrchr (unix_link + len_unix_locn, '/');
1209             p = strrchr (p, '.');
1210             if (p)
1211             {
1212                 *p = '\0';
1213                 len_unix_link = p - unix_link;
1214             }
1215             len_rel = len_unix_link - len_unix_locn;
1216             relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1217             if (relative)
1218             {
1219                 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1220             }
1221         }
1222     }
1223     if (!relative)
1224         WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1225     HeapFree(GetProcessHeap(), 0, unix_locn);
1226     HeapFree(GetProcessHeap(), 0, unix_link);
1227     return relative;
1228 }
1229
1230 /***********************************************************************
1231  *
1232  *           GetLinkLocation
1233  *
1234  * returns TRUE if successful
1235  * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1236  * *relative will contain the address of a heap-allocated copy of the portion
1237  * of the filename that is within the specified location, in unix form
1238  */
1239 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1240 {
1241     WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1242     DWORD len, i, r, filelen;
1243     const DWORD locations[] = {
1244         CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1245         CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1246         CSIDL_COMMON_STARTMENU };
1247
1248     WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1249     filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1250     if (filelen==0 || filelen>MAX_PATH)
1251         return FALSE;
1252
1253     WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1254
1255     /* the CSLU Toolkit uses a short path name when creating .lnk files;
1256      * expand or our hardcoded list won't match.
1257      */
1258     filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1259     if (filelen==0 || filelen>MAX_PATH)
1260         return FALSE;
1261
1262     WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1263
1264     for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1265     {
1266         if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1267             continue;
1268
1269         len = lstrlenW(buffer);
1270         if (len >= MAX_PATH)
1271             continue; /* We've just trashed memory! Hopefully we are OK */
1272
1273         if (len > filelen || filename[len]!='\\')
1274             continue;
1275         /* do a lstrcmpinW */
1276         filename[len] = 0;
1277         r = lstrcmpiW( filename, buffer );
1278         filename[len] = '\\';
1279         if ( r )
1280             continue;
1281
1282         /* return the remainder of the string and link type */
1283         *loc = locations[i];
1284         *relative = relative_path (filename, buffer);
1285         return (*relative != NULL);
1286     }
1287
1288     return FALSE;
1289 }
1290
1291 /* gets the target path directly or through MSI */
1292 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1293                             LPWSTR szArgs, DWORD argsSize)
1294 {
1295     IShellLinkDataList *dl = NULL;
1296     EXP_DARWIN_LINK *dar = NULL;
1297     HRESULT hr;
1298
1299     szPath[0] = 0;
1300     szArgs[0] = 0;
1301
1302     hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1303     if (hr == S_OK && szPath[0])
1304     {
1305         IShellLinkW_GetArguments( sl, szArgs, argsSize );
1306         return hr;
1307     }
1308
1309     hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1310     if (FAILED(hr))
1311         return hr;
1312
1313     hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1314     if (SUCCEEDED(hr))
1315     {
1316         WCHAR* szCmdline;
1317         DWORD cmdSize;
1318
1319         cmdSize=0;
1320         hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1321         if (hr == ERROR_SUCCESS)
1322         {
1323             cmdSize++;
1324             szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1325             hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1326             WINE_TRACE("      command    : %s\n", wine_dbgstr_w(szCmdline));
1327             if (hr == ERROR_SUCCESS)
1328             {
1329                 WCHAR *s, *d;
1330                 int bcount, in_quotes;
1331
1332                 /* Extract the application path */
1333                 bcount=0;
1334                 in_quotes=0;
1335                 s=szCmdline;
1336                 d=szPath;
1337                 while (*s)
1338                 {
1339                     if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1340                     {
1341                         /* skip the remaining spaces */
1342                         do {
1343                             s++;
1344                         } while (*s==0x0009 || *s==0x0020);
1345                         break;
1346                     }
1347                     else if (*s==0x005c)
1348                     {
1349                         /* '\\' */
1350                         *d++=*s++;
1351                         bcount++;
1352                     }
1353                     else if (*s==0x0022)
1354                     {
1355                         /* '"' */
1356                         if ((bcount & 1)==0)
1357                         {
1358                             /* Preceded by an even number of '\', this is
1359                              * half that number of '\', plus a quote which
1360                              * we erase.
1361                              */
1362                             d-=bcount/2;
1363                             in_quotes=!in_quotes;
1364                             s++;
1365                         }
1366                         else
1367                         {
1368                             /* Preceded by an odd number of '\', this is
1369                              * half that number of '\' followed by a '"'
1370                              */
1371                             d=d-bcount/2-1;
1372                             *d++='"';
1373                             s++;
1374                         }
1375                         bcount=0;
1376                     }
1377                     else
1378                     {
1379                         /* a regular character */
1380                         *d++=*s++;
1381                         bcount=0;
1382                     }
1383                     if ((d-szPath) == pathSize)
1384                     {
1385                         /* Keep processing the path till we get to the
1386                          * arguments, but 'stand still'
1387                          */
1388                         d--;
1389                     }
1390                 }
1391                 /* Close the application path */
1392                 *d=0;
1393
1394                 lstrcpynW(szArgs, s, argsSize);
1395             }
1396             HeapFree( GetProcessHeap(), 0, szCmdline );
1397         }
1398         LocalFree( dar );
1399     }
1400
1401     IShellLinkDataList_Release( dl );
1402     return hr;
1403 }
1404
1405 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1406 {
1407     HRESULT hr;
1408     WCHAR *value = NULL;
1409     DWORD size = 0;
1410     hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1411     if (SUCCEEDED(hr))
1412     {
1413         value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1414         if (value)
1415         {
1416             hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1417             if (FAILED(hr))
1418             {
1419                 HeapFree(GetProcessHeap(), 0, value);
1420                 value = NULL;
1421             }
1422         }
1423     }
1424     return value;
1425 }
1426
1427 static char* wchars_to_utf8_chars(LPCWSTR string)
1428 {
1429     char *ret;
1430     INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
1431     ret = HeapAlloc(GetProcessHeap(), 0, size);
1432     if (ret)
1433         WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
1434     return ret;
1435 }
1436
1437 static char* wchars_to_unix_chars(LPCWSTR string)
1438 {
1439     char *ret;
1440     INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
1441     ret = HeapAlloc(GetProcessHeap(), 0, size);
1442     if (ret)
1443         WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
1444     return ret;
1445 }
1446
1447 static char *slashes_to_minuses(const char *string)
1448 {
1449     int i;
1450     char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1451     if (ret)
1452     {
1453         for (i = 0; string[i]; i++)
1454         {
1455             if (string[i] == '/')
1456                 ret[i] = '-';
1457             else
1458                 ret[i] = string[i];
1459         }
1460         ret[i] = 0;
1461         return ret;
1462     }
1463     return NULL;
1464 }
1465
1466 static BOOL next_line(FILE *file, char **line, int *size)
1467 {
1468     int pos = 0;
1469     char *cr;
1470     if (*line == NULL)
1471     {
1472         *size = 4096;
1473         *line = HeapAlloc(GetProcessHeap(), 0, *size);
1474     }
1475     while (*line != NULL)
1476     {
1477         if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1478         {
1479             HeapFree(GetProcessHeap(), 0, *line);
1480             *line = NULL;
1481             if (feof(file))
1482                 return TRUE;
1483             return FALSE;
1484         }
1485         pos = strlen(*line);
1486         cr = strchr(*line, '\n');
1487         if (cr == NULL)
1488         {
1489             char *line2;
1490             (*size) *= 2;
1491             line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1492             if (line2)
1493                 *line = line2;
1494             else
1495             {
1496                 HeapFree(GetProcessHeap(), 0, *line);
1497                 *line = NULL;
1498             }
1499         }
1500         else
1501         {
1502             *cr = 0;
1503             return TRUE;
1504         }
1505     }
1506     return FALSE;
1507 }
1508
1509 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1510 {
1511     char *globs_filename = NULL;
1512     BOOL ret = TRUE;
1513     globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1514     if (globs_filename)
1515     {
1516         FILE *globs_file = fopen(globs_filename, "r");
1517         if (globs_file) /* doesn't have to exist */
1518         {
1519             char *line = NULL;
1520             int size = 0;
1521             while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1522             {
1523                 char *pos;
1524                 struct xdg_mime_type *mime_type_entry = NULL;
1525                 if (line[0] != '#' && (pos = strchr(line, ':')))
1526                 {
1527                     mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1528                     if (mime_type_entry)
1529                     {
1530                         *pos = 0;
1531                         mime_type_entry->mimeType = strdupA(line);
1532                         mime_type_entry->glob = strdupA(pos + 1);
1533                         if (mime_type_entry->mimeType && mime_type_entry->glob)
1534                             list_add_tail(mime_types, &mime_type_entry->entry);
1535                         else
1536                         {
1537                             HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1538                             HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1539                             HeapFree(GetProcessHeap(), 0, mime_type_entry);
1540                             ret = FALSE;
1541                         }
1542                     }
1543                     else
1544                         ret = FALSE;
1545                 }
1546             }
1547             HeapFree(GetProcessHeap(), 0, line);
1548             fclose(globs_file);
1549         }
1550         HeapFree(GetProcessHeap(), 0, globs_filename);
1551     }
1552     else
1553         ret = FALSE;
1554     return ret;
1555 }
1556
1557 static void free_native_mime_types(struct list *native_mime_types)
1558 {
1559     struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1560
1561     LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1562     {
1563         list_remove(&mime_type_entry->entry);
1564         HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1565         HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1566         HeapFree(GetProcessHeap(), 0, mime_type_entry);
1567     }
1568     HeapFree(GetProcessHeap(), 0, native_mime_types);
1569 }
1570
1571 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1572 {
1573     char *xdg_data_dirs;
1574     BOOL ret;
1575
1576     *mime_types = NULL;
1577
1578     xdg_data_dirs = getenv("XDG_DATA_DIRS");
1579     if (xdg_data_dirs == NULL)
1580         xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1581     else
1582         xdg_data_dirs = strdupA(xdg_data_dirs);
1583
1584     if (xdg_data_dirs)
1585     {
1586         *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1587         if (*mime_types)
1588         {
1589             const char *begin;
1590             char *end;
1591
1592             list_init(*mime_types);
1593             ret = add_mimes(xdg_data_home, *mime_types);
1594             if (ret)
1595             {
1596                 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1597                 {
1598                     *end = '\0';
1599                     ret = add_mimes(begin, *mime_types);
1600                     *end = ':';
1601                     if (!ret)
1602                         break;
1603                 }
1604                 if (ret)
1605                     ret = add_mimes(begin, *mime_types);
1606             }
1607         }
1608         else
1609             ret = FALSE;
1610         HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1611     }
1612     else
1613         ret = FALSE;
1614     if (!ret && *mime_types)
1615     {
1616         free_native_mime_types(*mime_types);
1617         *mime_types = NULL;
1618     }
1619     return ret;
1620 }
1621
1622 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1623                        char **match)
1624 {
1625 #ifdef HAVE_FNMATCH
1626     struct xdg_mime_type *mime_type_entry;
1627     int matchLength = 0;
1628
1629     *match = NULL;
1630
1631     LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1632     {
1633         if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1634         {
1635             if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1636             {
1637                 *match = mime_type_entry->mimeType;
1638                 matchLength = strlen(mime_type_entry->glob);
1639             }
1640         }
1641     }
1642
1643     if (*match != NULL)
1644     {
1645         *match = strdupA(*match);
1646         if (*match == NULL)
1647             return FALSE;
1648     }
1649 #else
1650     *match = NULL;
1651 #endif
1652     return TRUE;
1653 }
1654
1655 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1656                                                 const char *extensionA,
1657                                                 LPCWSTR extensionW,
1658                                                 char **mime_type)
1659 {
1660     WCHAR *lower_extensionW;
1661     INT len;
1662     BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1663     if (ret == FALSE || *mime_type != NULL)
1664         return ret;
1665     len = strlenW(extensionW);
1666     lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1667     if (lower_extensionW)
1668     {
1669         char *lower_extensionA;
1670         memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1671         strlwrW(lower_extensionW);
1672         lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1673         if (lower_extensionA)
1674         {
1675             ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1676             HeapFree(GetProcessHeap(), 0, lower_extensionA);
1677         }
1678         else
1679         {
1680             ret = FALSE;
1681             WINE_FIXME("out of memory\n");
1682         }
1683         HeapFree(GetProcessHeap(), 0, lower_extensionW);
1684     }
1685     else
1686     {
1687         ret = FALSE;
1688         WINE_FIXME("out of memory\n");
1689     }
1690     return ret;
1691 }
1692
1693 static CHAR* reg_get_valA(HKEY key, LPCSTR subkey, LPCSTR name)
1694 {
1695     DWORD size;
1696     if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1697     {
1698         CHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1699         if (ret)
1700         {
1701             if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1702                 return ret;
1703         }
1704         HeapFree(GetProcessHeap(), 0, ret);
1705     }
1706     return NULL;
1707 }
1708
1709 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1710 {
1711     DWORD size;
1712     if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1713     {
1714         WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1715         if (ret)
1716         {
1717             if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1718                 return ret;
1719         }
1720         HeapFree(GetProcessHeap(), 0, ret);
1721     }
1722     return NULL;
1723 }
1724
1725 static HKEY open_associations_reg_key(void)
1726 {
1727     static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1728         'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','F','i','l','e','O','p','e','n','A','s','s','o','c','i','a','t','i','o','n','s',0};
1729     HKEY assocKey;
1730     if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1731         return assocKey;
1732     return NULL;
1733 }
1734
1735 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1736 {
1737     static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1738     static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1739     HKEY assocKey;
1740     BOOL ret;
1741
1742     if ((assocKey = open_associations_reg_key()))
1743     {
1744         CHAR *valueA;
1745         WCHAR *value;
1746
1747         ret = FALSE;
1748
1749         valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1750         if (!valueA || lstrcmpA(valueA, mimeType))
1751             ret = TRUE;
1752         HeapFree(GetProcessHeap(), 0, valueA);
1753
1754         value = reg_get_valW(assocKey, extensionW, ProgIDW);
1755         if (!value || strcmpW(value, progId))
1756             ret = TRUE;
1757         HeapFree(GetProcessHeap(), 0, value);
1758
1759         valueA = reg_get_valA(assocKey, extensionA, "AppName");
1760         if (!valueA || lstrcmpA(valueA, appName))
1761             ret = TRUE;
1762         HeapFree(GetProcessHeap(), 0, valueA);
1763
1764         value = reg_get_valW(assocKey, extensionW, DocNameW);
1765         if (docName && (!value || strcmpW(value, docName)))
1766             ret = TRUE;
1767         HeapFree(GetProcessHeap(), 0, value);
1768
1769         RegCloseKey(assocKey);
1770     }
1771     else
1772     {
1773         WINE_ERR("error opening associations registry key\n");
1774         ret = FALSE;
1775     }
1776     return ret;
1777 }
1778
1779 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1780 {
1781     static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1782     static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1783     HKEY assocKey;
1784
1785     if ((assocKey = open_associations_reg_key()))
1786     {
1787         HKEY subkey;
1788         if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1789         {
1790             RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (const BYTE*) mimeType, lstrlenA(mimeType) + 1);
1791             RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1792             RegSetValueExA(subkey, "AppName", 0, REG_SZ, (const BYTE*) appName, lstrlenA(appName) + 1);
1793             if (docName)
1794                 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1795             RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (const BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1796             RegCloseKey(subkey);
1797         }
1798         else
1799             WINE_ERR("could not create extension subkey\n");
1800         RegCloseKey(assocKey);
1801     }
1802     else
1803         WINE_ERR("could not open file associations key\n");
1804 }
1805
1806 static BOOL cleanup_associations(void)
1807 {
1808     static const WCHAR openW[] = {'o','p','e','n',0};
1809     HKEY assocKey;
1810     BOOL hasChanged = FALSE;
1811     if ((assocKey = open_associations_reg_key()))
1812     {
1813         int i;
1814         BOOL done = FALSE;
1815         for (i = 0; !done; i++)
1816         {
1817             WCHAR *extensionW = NULL;
1818             char *extensionA = NULL;
1819             DWORD size = 1024;
1820             LSTATUS ret;
1821
1822             do
1823             {
1824                 HeapFree(GetProcessHeap(), 0, extensionW);
1825                 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1826                 if (extensionW == NULL)
1827                 {
1828                     WINE_ERR("out of memory\n");
1829                     ret = ERROR_OUTOFMEMORY;
1830                     break;
1831                 }
1832                 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1833                 size *= 2;
1834             } while (ret == ERROR_MORE_DATA);
1835
1836             if (ret == ERROR_SUCCESS)
1837             {
1838                 WCHAR *command;
1839                 extensionA = wchars_to_utf8_chars(extensionW);
1840                 if (extensionA == NULL)
1841                 {
1842                     WINE_ERR("out of memory\n");
1843                     done = TRUE;
1844                     goto end;
1845                 }
1846                 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1847                 if (command == NULL)
1848                 {
1849                     char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1850                     if (desktopFile)
1851                     {
1852                         WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1853                         remove(desktopFile);
1854                     }
1855                     RegDeleteKeyW(assocKey, extensionW);
1856                     hasChanged = TRUE;
1857                     HeapFree(GetProcessHeap(), 0, desktopFile);
1858                 }
1859                 HeapFree(GetProcessHeap(), 0, command);
1860             }
1861             else
1862             {
1863                 if (ret != ERROR_NO_MORE_ITEMS)
1864                     WINE_ERR("error %d while reading registry\n", ret);
1865                 done = TRUE;
1866             }
1867         end:
1868             HeapFree(GetProcessHeap(), 0, extensionA);
1869             HeapFree(GetProcessHeap(), 0, extensionW);
1870         }
1871         RegCloseKey(assocKey);
1872     }
1873     else
1874         WINE_ERR("could not open file associations key\n");
1875     return hasChanged;
1876 }
1877
1878 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1879                                               const char *mime_type, const char *comment)
1880 {
1881     BOOL ret = FALSE;
1882     char *filename;
1883
1884     WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1885                wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1886
1887     filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1888     if (filename)
1889     {
1890         FILE *packageFile = fopen(filename, "w");
1891         if (packageFile)
1892         {
1893             fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1894             fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1895             fprintf(packageFile, "  <mime-type type=\"");
1896             write_xml_text(packageFile, mime_type);
1897             fprintf(packageFile, "\">\n");
1898             fprintf(packageFile, "    <glob pattern=\"*");
1899             write_xml_text(packageFile, dot_extension);
1900             fprintf(packageFile, "\"/>\n");
1901             if (comment)
1902             {
1903                 fprintf(packageFile, "    <comment>");
1904                 write_xml_text(packageFile, comment);
1905                 fprintf(packageFile, "</comment>\n");
1906             }
1907             fprintf(packageFile, "  </mime-type>\n");
1908             fprintf(packageFile, "</mime-info>\n");
1909             ret = TRUE;
1910             fclose(packageFile);
1911         }
1912         else
1913             WINE_ERR("error writing file %s\n", filename);
1914         HeapFree(GetProcessHeap(), 0, filename);
1915     }
1916     else
1917         WINE_ERR("out of memory\n");
1918     return ret;
1919 }
1920
1921 static BOOL is_extension_blacklisted(LPCWSTR extension)
1922 {
1923     /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1924     static const WCHAR comW[] = {'.','c','o','m',0};
1925     static const WCHAR exeW[] = {'.','e','x','e',0};
1926     static const WCHAR msiW[] = {'.','m','s','i',0};
1927
1928     if (!strcmpiW(extension, comW) ||
1929         !strcmpiW(extension, exeW) ||
1930         !strcmpiW(extension, msiW))
1931         return TRUE;
1932     return FALSE;
1933 }
1934
1935 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1936                                                 const char *friendlyAppName, const char *mimeType,
1937                                                 const char *progId)
1938 {
1939     BOOL ret = FALSE;
1940     FILE *desktop;
1941
1942     WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1943                wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1944                wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1945
1946     desktop = fopen(desktopPath, "w");
1947     if (desktop)
1948     {
1949         fprintf(desktop, "[Desktop Entry]\n");
1950         fprintf(desktop, "Type=Application\n");
1951         fprintf(desktop, "Name=%s\n", friendlyAppName);
1952         fprintf(desktop, "MimeType=%s\n", mimeType);
1953         fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1954         fprintf(desktop, "NoDisplay=true\n");
1955         fprintf(desktop, "StartupNotify=true\n");
1956         ret = TRUE;
1957         fclose(desktop);
1958     }
1959     else
1960         WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1961     return ret;
1962 }
1963
1964 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1965 {
1966     static const WCHAR openW[] = {'o','p','e','n',0};
1967     struct list *nativeMimeTypes = NULL;
1968     LSTATUS ret = 0;
1969     int i;
1970     BOOL hasChanged = FALSE;
1971
1972     if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1973     {
1974         WINE_ERR("could not build native MIME types\n");
1975         return FALSE;
1976     }
1977
1978     for (i = 0; ; i++)
1979     {
1980         WCHAR *extensionW = NULL;
1981         DWORD size = 1024;
1982
1983         do
1984         {
1985             HeapFree(GetProcessHeap(), 0, extensionW);
1986             extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1987             if (extensionW == NULL)
1988             {
1989                 WINE_ERR("out of memory\n");
1990                 ret = ERROR_OUTOFMEMORY;
1991                 break;
1992             }
1993             ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1994             size *= 2;
1995         } while (ret == ERROR_MORE_DATA);
1996
1997         if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1998         {
1999             char *extensionA = NULL;
2000             WCHAR *commandW = NULL;
2001             WCHAR *friendlyDocNameW = NULL;
2002             char *friendlyDocNameA = NULL;
2003             WCHAR *iconW = NULL;
2004             char *iconA = NULL;
2005             WCHAR *contentTypeW = NULL;
2006             char *mimeTypeA = NULL;
2007             WCHAR *friendlyAppNameW = NULL;
2008             char *friendlyAppNameA = NULL;
2009             WCHAR *progIdW = NULL;
2010             char *progIdA = NULL;
2011
2012             extensionA = wchars_to_utf8_chars(extensionW);
2013             if (extensionA == NULL)
2014             {
2015                 WINE_ERR("out of memory\n");
2016                 goto end;
2017             }
2018
2019             friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2020             if (friendlyDocNameW)
2021             {
2022                 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2023                 if (friendlyDocNameA == NULL)
2024                 {
2025                     WINE_ERR("out of memory\n");
2026                     goto end;
2027                 }
2028             }
2029
2030             iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2031
2032             contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2033
2034             if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2035                 goto end;
2036
2037             if (mimeTypeA == NULL)
2038             {
2039                 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2040                     mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2041                 else
2042                     mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2043
2044                 if (mimeTypeA != NULL)
2045                 {
2046                     /* Gnome seems to ignore the <icon> tag in MIME packages,
2047                      * and the default name is more intuitive anyway.
2048                      */
2049                     if (iconW)
2050                     {
2051                         char *flattened_mime = slashes_to_minuses(mimeTypeA);
2052                         if (flattened_mime)
2053                         {
2054                             int index = 0;
2055                             WCHAR *comma = strrchrW(iconW, ',');
2056                             if (comma)
2057                             {
2058                                 *comma = 0;
2059                                 index = atoiW(comma + 1);
2060                             }
2061                             iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2062                             HeapFree(GetProcessHeap(), 0, flattened_mime);
2063                         }
2064                     }
2065
2066                     write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2067                     hasChanged = TRUE;
2068                 }
2069                 else
2070                 {
2071                     WINE_FIXME("out of memory\n");
2072                     goto end;
2073                 }
2074             }
2075
2076             commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2077             if (commandW == NULL)
2078                 /* no command => no application is associated */
2079                 goto end;
2080
2081             friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2082             if (friendlyAppNameW)
2083             {
2084                 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2085                 if (friendlyAppNameA == NULL)
2086                 {
2087                     WINE_ERR("out of memory\n");
2088                     goto end;
2089                 }
2090             }
2091             else
2092             {
2093                 friendlyAppNameA = heap_printf("A Wine application");
2094                 if (friendlyAppNameA == NULL)
2095                 {
2096                     WINE_ERR("out of memory\n");
2097                     goto end;
2098                 }
2099             }
2100
2101             progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2102             if (progIdW)
2103             {
2104                 progIdA = wchars_to_utf8_chars(progIdW);
2105                 if (progIdA == NULL)
2106                 {
2107                     WINE_ERR("out of memory\n");
2108                     goto end;
2109                 }
2110             }
2111             else
2112                 goto end; /* no progID => not a file type association */
2113
2114             if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2115             {
2116                 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2117                 if (desktopPath)
2118                 {
2119                     if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2120                     {
2121                         hasChanged = TRUE;
2122                         update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2123                     }
2124                     HeapFree(GetProcessHeap(), 0, desktopPath);
2125                 }
2126             }
2127
2128         end:
2129             HeapFree(GetProcessHeap(), 0, extensionA);
2130             HeapFree(GetProcessHeap(), 0, commandW);
2131             HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2132             HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2133             HeapFree(GetProcessHeap(), 0, iconW);
2134             HeapFree(GetProcessHeap(), 0, iconA);
2135             HeapFree(GetProcessHeap(), 0, contentTypeW);
2136             HeapFree(GetProcessHeap(), 0, mimeTypeA);
2137             HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2138             HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2139             HeapFree(GetProcessHeap(), 0, progIdW);
2140             HeapFree(GetProcessHeap(), 0, progIdA);
2141         }
2142         HeapFree(GetProcessHeap(), 0, extensionW);
2143         if (ret != ERROR_SUCCESS)
2144             break;
2145     }
2146
2147     free_native_mime_types(nativeMimeTypes);
2148     return hasChanged;
2149 }
2150
2151 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2152 {
2153     static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2154                                    '\\','s','t','a','r','t','.','e','x','e',0};
2155     char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2156     char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
2157     WCHAR szTmp[INFOTIPSIZE];
2158     WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2159     WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2160     int iIconId = 0, r = -1;
2161     DWORD csidl = -1;
2162     HANDLE hsem = NULL;
2163     char *unix_link = NULL;
2164
2165     if ( !link )
2166     {
2167         WINE_ERR("Link name is null\n");
2168         return FALSE;
2169     }
2170
2171     if( !GetLinkLocation( link, &csidl, &link_name ) )
2172     {
2173         WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2174         return TRUE;
2175     }
2176     if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2177     {
2178         WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2179         return TRUE;
2180     }
2181     WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));
2182
2183     szTmp[0] = 0;
2184     IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2185     ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2186     WINE_TRACE("workdir    : %s\n", wine_dbgstr_w(szWorkDir));
2187
2188     szTmp[0] = 0;
2189     IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2190     ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2191     WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2192
2193     get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
2194     WINE_TRACE("path       : %s\n", wine_dbgstr_w(szPath));
2195     WINE_TRACE("args       : %s\n", wine_dbgstr_w(szArgs));
2196
2197     szTmp[0] = 0;
2198     IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2199     ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2200     WINE_TRACE("icon file  : %s\n", wine_dbgstr_w(szIconPath) );
2201
2202     if( !szPath[0] )
2203     {
2204         LPITEMIDLIST pidl = NULL;
2205         IShellLinkW_GetIDList( sl, &pidl );
2206         if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2207             WINE_TRACE("pidl path  : %s\n", wine_dbgstr_w(szPath));
2208     }
2209
2210     /* extract the icon */
2211     if( szIconPath[0] )
2212         icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2213     else
2214         icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2215
2216     /* fail - try once again after parent process exit */
2217     if( !icon_name )
2218     {
2219         if (bWait)
2220         {
2221             WINE_WARN("Unable to extract icon, deferring.\n");
2222             goto cleanup;
2223         }
2224         WINE_ERR("failed to extract icon from %s\n",
2225                  wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2226     }
2227
2228     unix_link = wine_get_unix_file_name(link);
2229     if (unix_link == NULL)
2230     {
2231         WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2232         goto cleanup;
2233     }
2234
2235     /* check the path */
2236     if( szPath[0] )
2237     {
2238         static const WCHAR exeW[] = {'.','e','x','e',0};
2239         WCHAR *p;
2240
2241         /* check for .exe extension */
2242         if (!(p = strrchrW( szPath, '.' )) ||
2243             strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2244             lstrcmpiW( p, exeW ))
2245         {
2246             /* Not .exe - use 'start.exe' to launch this file */
2247             p = szArgs + lstrlenW(szPath) + 2;
2248             if (szArgs[0])
2249             {
2250                 p[0] = ' ';
2251                 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2252                                            sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2253             }
2254             else
2255                 p[0] = 0;
2256
2257             szArgs[0] = '"';
2258             lstrcpyW(szArgs + 1, szPath);
2259             p[-1] = '"';
2260
2261             GetWindowsDirectoryW(szPath, MAX_PATH);
2262             lstrcatW(szPath, startW);
2263         }
2264
2265         /* convert app working dir */
2266         if (szWorkDir[0])
2267             work_dir = wine_get_unix_file_name( szWorkDir );
2268     }
2269     else
2270     {
2271         /* if there's no path... try run the link itself */
2272         lstrcpynW(szArgs, link, MAX_PATH);
2273         GetWindowsDirectoryW(szPath, MAX_PATH);
2274         lstrcatW(szPath, startW);
2275     }
2276
2277     /* escape the path and parameters */
2278     escaped_path = escape(szPath);
2279     escaped_args = escape(szArgs);
2280     escaped_description = escape(szDescription);
2281
2282     /* building multiple menus concurrently has race conditions */
2283     hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2284     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2285     {
2286         WINE_ERR("failed wait for semaphore\n");
2287         goto cleanup;
2288     }
2289
2290     if (in_desktop_dir(csidl))
2291     {
2292         char *location;
2293         const char *lastEntry;
2294         lastEntry = strrchr(link_name, '/');
2295         if (lastEntry == NULL)
2296             lastEntry = link_name;
2297         else
2298             ++lastEntry;
2299         location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2300         if (location)
2301         {
2302             r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2303             HeapFree(GetProcessHeap(), 0, location);
2304         }
2305     }
2306     else
2307         r = !write_menu_entry(unix_link, link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2308
2309     ReleaseSemaphore( hsem, 1, NULL );
2310
2311 cleanup:
2312     if (hsem) CloseHandle( hsem );
2313     HeapFree( GetProcessHeap(), 0, icon_name );
2314     HeapFree( GetProcessHeap(), 0, work_dir );
2315     HeapFree( GetProcessHeap(), 0, link_name );
2316     HeapFree( GetProcessHeap(), 0, escaped_args );
2317     HeapFree( GetProcessHeap(), 0, escaped_path );
2318     HeapFree( GetProcessHeap(), 0, escaped_description );
2319     HeapFree( GetProcessHeap(), 0, unix_link);
2320
2321     if (r && !bWait)
2322         WINE_ERR("failed to build the menu\n" );
2323
2324     return ( r == 0 );
2325 }
2326
2327 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2328 {
2329     char *link_name = NULL;
2330     DWORD csidl = -1;
2331     LPWSTR urlPath;
2332     char *escaped_urlPath = NULL;
2333     HRESULT hr;
2334     HANDLE hSem = NULL;
2335     BOOL ret = TRUE;
2336     int r = -1;
2337     char *unix_link = NULL;
2338
2339     if ( !link )
2340     {
2341         WINE_ERR("Link name is null\n");
2342         return TRUE;
2343     }
2344
2345     if( !GetLinkLocation( link, &csidl, &link_name ) )
2346     {
2347         WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2348         return TRUE;
2349     }
2350     if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2351     {
2352         WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2353         ret = TRUE;
2354         goto cleanup;
2355     }
2356     WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));
2357
2358     hr = url->lpVtbl->GetURL(url, &urlPath);
2359     if (FAILED(hr))
2360     {
2361         ret = TRUE;
2362         goto cleanup;
2363     }
2364     WINE_TRACE("path       : %s\n", wine_dbgstr_w(urlPath));
2365
2366     unix_link = wine_get_unix_file_name(link);
2367     if (unix_link == NULL)
2368     {
2369         WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2370         goto cleanup;
2371     }
2372
2373     escaped_urlPath = escape(urlPath);
2374
2375     hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2376     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2377     {
2378         WINE_ERR("failed wait for semaphore\n");
2379         goto cleanup;
2380     }
2381     if (in_desktop_dir(csidl))
2382     {
2383         char *location;
2384         const char *lastEntry;
2385         lastEntry = strrchr(link_name, '/');
2386         if (lastEntry == NULL)
2387             lastEntry = link_name;
2388         else
2389             ++lastEntry;
2390         location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2391         if (location)
2392         {
2393             r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2394             HeapFree(GetProcessHeap(), 0, location);
2395         }
2396     }
2397     else
2398         r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2399     ret = (r != 0);
2400     ReleaseSemaphore(hSem, 1, NULL);
2401
2402 cleanup:
2403     if (hSem)
2404         CloseHandle(hSem);
2405     HeapFree(GetProcessHeap(), 0, link_name);
2406     CoTaskMemFree( urlPath );
2407     HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2408     HeapFree(GetProcessHeap(), 0, unix_link);
2409     return ret;
2410 }
2411
2412 static BOOL WaitForParentProcess( void )
2413 {
2414     PROCESSENTRY32 procentry;
2415     HANDLE hsnapshot = NULL, hprocess = NULL;
2416     DWORD ourpid = GetCurrentProcessId();
2417     BOOL ret = FALSE, rc;
2418
2419     WINE_TRACE("Waiting for parent process\n");
2420     if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2421         INVALID_HANDLE_VALUE)
2422     {
2423         WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2424         goto done;
2425     }
2426
2427     procentry.dwSize = sizeof(PROCESSENTRY32);
2428     rc = Process32First( hsnapshot, &procentry );
2429     while (rc)
2430     {
2431         if (procentry.th32ProcessID == ourpid) break;
2432         rc = Process32Next( hsnapshot, &procentry );
2433     }
2434     if (!rc)
2435     {
2436         WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2437         goto done;
2438     }
2439
2440     if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2441         NULL)
2442     {
2443         WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2444                  GetLastError());
2445         goto done;
2446     }
2447
2448     if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2449         ret = TRUE;
2450     else
2451         WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2452
2453 done:
2454     if (hprocess) CloseHandle( hprocess );
2455     if (hsnapshot) CloseHandle( hsnapshot );
2456     return ret;
2457 }
2458
2459 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2460 {
2461     IShellLinkW *sl;
2462     IPersistFile *pf;
2463     HRESULT r;
2464     WCHAR fullname[MAX_PATH];
2465     DWORD len;
2466
2467     WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2468
2469     if( !linkname[0] )
2470     {
2471         WINE_ERR("link name missing\n");
2472         return 1;
2473     }
2474
2475     len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2476     if (len==0 || len>MAX_PATH)
2477     {
2478         WINE_ERR("couldn't get full path of link file\n");
2479         return 1;
2480     }
2481
2482     r = CoInitialize( NULL );
2483     if( FAILED( r ) )
2484     {
2485         WINE_ERR("CoInitialize failed\n");
2486         return 1;
2487     }
2488
2489     r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2490                           &IID_IShellLinkW, (LPVOID *) &sl );
2491     if( FAILED( r ) )
2492     {
2493         WINE_ERR("No IID_IShellLink\n");
2494         return 1;
2495     }
2496
2497     r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2498     if( FAILED( r ) )
2499     {
2500         WINE_ERR("No IID_IPersistFile\n");
2501         return 1;
2502     }
2503
2504     r = IPersistFile_Load( pf, fullname, STGM_READ );
2505     if( SUCCEEDED( r ) )
2506     {
2507         /* If something fails (eg. Couldn't extract icon)
2508          * wait for parent process and try again
2509          */
2510         if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2511         {
2512             WaitForParentProcess();
2513             InvokeShellLinker( sl, fullname, FALSE );
2514         }
2515     }
2516     else
2517     {
2518         WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2519     }
2520
2521     IPersistFile_Release( pf );
2522     IShellLinkW_Release( sl );
2523
2524     CoUninitialize();
2525
2526     return !r;
2527 }
2528
2529 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2530 {
2531     IUniformResourceLocatorW *url;
2532     IPersistFile *pf;
2533     HRESULT r;
2534     WCHAR fullname[MAX_PATH];
2535     DWORD len;
2536
2537     WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2538
2539     if( !urlname[0] )
2540     {
2541         WINE_ERR("URL name missing\n");
2542         return 1;
2543     }
2544
2545     len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2546     if (len==0 || len>MAX_PATH)
2547     {
2548         WINE_ERR("couldn't get full path of URL file\n");
2549         return 1;
2550     }
2551
2552     r = CoInitialize( NULL );
2553     if( FAILED( r ) )
2554     {
2555         WINE_ERR("CoInitialize failed\n");
2556         return 1;
2557     }
2558
2559     r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2560                           &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2561     if( FAILED( r ) )
2562     {
2563         WINE_ERR("No IID_IUniformResourceLocatorW\n");
2564         return 1;
2565     }
2566
2567     r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2568     if( FAILED( r ) )
2569     {
2570         WINE_ERR("No IID_IPersistFile\n");
2571         return 1;
2572     }
2573     r = IPersistFile_Load( pf, fullname, STGM_READ );
2574     if( SUCCEEDED( r ) )
2575     {
2576         /* If something fails (eg. Couldn't extract icon)
2577          * wait for parent process and try again
2578          */
2579         if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2580         {
2581             WaitForParentProcess();
2582             InvokeShellLinkerForURL( url, fullname, FALSE );
2583         }
2584     }
2585
2586     IPersistFile_Release( pf );
2587     url->lpVtbl->Release( url );
2588
2589     CoUninitialize();
2590
2591     return !r;
2592 }
2593
2594 static void RefreshFileTypeAssociations(void)
2595 {
2596     HANDLE hSem = NULL;
2597     char *mime_dir = NULL;
2598     char *packages_dir = NULL;
2599     char *applications_dir = NULL;
2600     BOOL hasChanged;
2601
2602     hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2603     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2604     {
2605         WINE_ERR("failed wait for semaphore\n");
2606         CloseHandle(hSem);
2607         hSem = NULL;
2608         goto end;
2609     }
2610
2611     mime_dir = heap_printf("%s/mime", xdg_data_dir);
2612     if (mime_dir == NULL)
2613     {
2614         WINE_ERR("out of memory\n");
2615         goto end;
2616     }
2617     create_directories(mime_dir);
2618
2619     packages_dir = heap_printf("%s/packages", mime_dir);
2620     if (packages_dir == NULL)
2621     {
2622         WINE_ERR("out of memory\n");
2623         goto end;
2624     }
2625     create_directories(packages_dir);
2626
2627     applications_dir = heap_printf("%s/applications", xdg_data_dir);
2628     if (applications_dir == NULL)
2629     {
2630         WINE_ERR("out of memory\n");
2631         goto end;
2632     }
2633     create_directories(applications_dir);
2634
2635     hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2636     hasChanged |= cleanup_associations();
2637     if (hasChanged)
2638     {
2639         const char *argv[3];
2640
2641         argv[0] = "update-mime-database";
2642         argv[1] = mime_dir;
2643         argv[2] = NULL;
2644         spawnvp( _P_NOWAIT, argv[0], argv );
2645
2646         argv[0] = "update-desktop-database";
2647         argv[1] = applications_dir;
2648         spawnvp( _P_NOWAIT, argv[0], argv );
2649     }
2650
2651 end:
2652     if (hSem)
2653     {
2654         ReleaseSemaphore(hSem, 1, NULL);
2655         CloseHandle(hSem);
2656     }
2657     HeapFree(GetProcessHeap(), 0, mime_dir);
2658     HeapFree(GetProcessHeap(), 0, packages_dir);
2659     HeapFree(GetProcessHeap(), 0, applications_dir);
2660 }
2661
2662 static void cleanup_menus(void)
2663 {
2664     HKEY hkey;
2665
2666     hkey = open_menus_reg_key();
2667     if (hkey)
2668     {
2669         int i;
2670         LSTATUS lret = ERROR_SUCCESS;
2671         for (i = 0; lret == ERROR_SUCCESS; )
2672         {
2673             WCHAR *value = NULL;
2674             WCHAR *data = NULL;
2675             DWORD valueSize = 4096;
2676             DWORD dataSize = 4096;
2677             while (1)
2678             {
2679                 lret = ERROR_OUTOFMEMORY;
2680                 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
2681                 if (value == NULL)
2682                     break;
2683                 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
2684                 if (data == NULL)
2685                     break;
2686                 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2687                 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2688                     break;
2689                 valueSize *= 2;
2690                 dataSize *= 2;
2691                 HeapFree(GetProcessHeap(), 0, value);
2692                 HeapFree(GetProcessHeap(), 0, data);
2693                 value = data = NULL;
2694             }
2695             if (lret == ERROR_SUCCESS)
2696             {
2697                 char *unix_file;
2698                 char *windows_file;
2699                 unix_file = wchars_to_unix_chars(value);
2700                 windows_file = wchars_to_unix_chars(data);
2701                 if (unix_file != NULL && windows_file != NULL)
2702                 {
2703                     struct stat filestats;
2704                     if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
2705                     {
2706                         WINE_TRACE("removing menu related file %s\n", unix_file);
2707                         remove(unix_file);
2708                         RegDeleteValueW(hkey, value);
2709                     }
2710                     else
2711                         i++;
2712                 }
2713                 else
2714                 {
2715                     WINE_ERR("out of memory enumerating menus\n");
2716                     lret = ERROR_OUTOFMEMORY;
2717                 }
2718                 HeapFree(GetProcessHeap(), 0, unix_file);
2719                 HeapFree(GetProcessHeap(), 0, windows_file);
2720             }
2721             else if (lret != ERROR_NO_MORE_ITEMS)
2722                 WINE_ERR("error %d reading registry\n", lret);
2723             HeapFree(GetProcessHeap(), 0, value);
2724             HeapFree(GetProcessHeap(), 0, data);
2725         }
2726         RegCloseKey(hkey);
2727     }
2728     else
2729         WINE_ERR("error opening registry key, menu cleanup failed\n");
2730 }
2731
2732 static WCHAR *next_token( LPWSTR *p )
2733 {
2734     LPWSTR token = NULL, t = *p;
2735
2736     if( !t )
2737         return NULL;
2738
2739     while( t && !token )
2740     {
2741         switch( *t )
2742         {
2743         case ' ':
2744             t++;
2745             continue;
2746         case '"':
2747             /* unquote the token */
2748             token = ++t;
2749             t = strchrW( token, '"' );
2750             if( t )
2751                  *t++ = 0;
2752             break;
2753         case 0:
2754             t = NULL;
2755             break;
2756         default:
2757             token = t;
2758             t = strchrW( token, ' ' );
2759             if( t )
2760                  *t++ = 0;
2761             break;
2762         }
2763     }
2764     *p = t;
2765     return token;
2766 }
2767
2768 static BOOL init_xdg(void)
2769 {
2770     WCHAR shellDesktopPath[MAX_PATH];
2771     HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2772     if (SUCCEEDED(hr))
2773         xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2774     if (xdg_desktop_dir == NULL)
2775     {
2776         WINE_ERR("error looking up the desktop directory\n");
2777         return FALSE;
2778     }
2779
2780     if (getenv("XDG_CONFIG_HOME"))
2781         xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2782     else
2783         xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2784     if (xdg_config_dir)
2785     {
2786         create_directories(xdg_config_dir);
2787         if (getenv("XDG_DATA_HOME"))
2788             xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
2789         else
2790             xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2791         if (xdg_data_dir)
2792         {
2793             char *buffer;
2794             create_directories(xdg_data_dir);
2795             buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2796             if (buffer)
2797             {
2798                 mkdir(buffer, 0777);
2799                 HeapFree(GetProcessHeap(), 0, buffer);
2800             }
2801             return TRUE;
2802         }
2803         HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2804     }
2805     WINE_ERR("out of memory\n");
2806     return FALSE;
2807 }
2808
2809 /***********************************************************************
2810  *
2811  *           wWinMain
2812  */
2813 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
2814 {
2815     static const WCHAR dash_aW[] = {'-','a',0};
2816     static const WCHAR dash_rW[] = {'-','r',0};
2817     static const WCHAR dash_uW[] = {'-','u',0};
2818     static const WCHAR dash_wW[] = {'-','w',0};
2819
2820     LPWSTR token = NULL, p;
2821     BOOL bWait = FALSE;
2822     BOOL bURL = FALSE;
2823     int ret = 0;
2824
2825     if (!init_xdg())
2826         return 1;
2827
2828     for( p = cmdline; p && *p; )
2829     {
2830         token = next_token( &p );
2831         if( !token )
2832             break;
2833         if( !strcmpW( token, dash_aW ) )
2834         {
2835             RefreshFileTypeAssociations();
2836             continue;
2837         }
2838         if( !strcmpW( token, dash_rW ) )
2839         {
2840             cleanup_menus();
2841             continue;
2842         }
2843         if( !strcmpW( token, dash_wW ) )
2844             bWait = TRUE;
2845         else if ( !strcmpW( token, dash_uW ) )
2846             bURL = TRUE;
2847         else if( token[0] == '-' )
2848         {
2849             WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
2850         }
2851         else
2852         {
2853             BOOL bRet;
2854
2855             if (bURL)
2856                 bRet = Process_URL( token, bWait );
2857             else
2858                 bRet = Process_Link( token, bWait );
2859             if (!bRet)
2860             {
2861                 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
2862                 ret = 1;
2863             }
2864         }
2865     }
2866
2867     return ret;
2868 }