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