winemenubuilder: Track, update and clean up file open associations.
[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     }
1529     return NULL;
1530 }
1531
1532 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1533 {
1534     DWORD size;
1535     if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1536     {
1537         WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1538         if (ret)
1539         {
1540             if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1541                 return ret;
1542         }
1543     }
1544     return NULL;
1545 }
1546
1547 static HKEY open_associations_reg_key(void)
1548 {
1549     static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1550         '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};
1551     HKEY assocKey;
1552     if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1553         return assocKey;
1554     return NULL;
1555 }
1556
1557 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1558 {
1559     static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1560     static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1561     HKEY assocKey;
1562     BOOL ret;
1563
1564     if ((assocKey = open_associations_reg_key()))
1565     {
1566         CHAR *valueA;
1567         WCHAR *value;
1568
1569         ret = FALSE;
1570
1571         valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1572         if (!valueA || lstrcmpA(valueA, mimeType))
1573             ret = TRUE;
1574         HeapFree(GetProcessHeap(), 0, valueA);
1575
1576         value = reg_get_valW(assocKey, extensionW, ProgIDW);
1577         if (!value || strcmpW(value, progId))
1578             ret = TRUE;
1579         HeapFree(GetProcessHeap(), 0, value);
1580
1581         valueA = reg_get_valA(assocKey, extensionA, "AppName");
1582         if (!valueA || lstrcmpA(valueA, appName))
1583             ret = TRUE;
1584         HeapFree(GetProcessHeap(), 0, valueA);
1585
1586         value = reg_get_valW(assocKey, extensionW, DocNameW);
1587         if (docName && (!value || strcmpW(value, docName)))
1588             ret = TRUE;
1589         HeapFree(GetProcessHeap(), 0, value);
1590
1591         RegCloseKey(assocKey);
1592     }
1593     else
1594     {
1595         WINE_ERR("error opening associations registry key\n");
1596         ret = FALSE;
1597     }
1598     return ret;
1599 }
1600
1601 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1602 {
1603     static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1604     static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1605     HKEY assocKey;
1606
1607     if ((assocKey = open_associations_reg_key()))
1608     {
1609         HKEY subkey;
1610         if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1611         {
1612             RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (BYTE*) mimeType, lstrlenA(mimeType) + 1);
1613             RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1614             RegSetValueExA(subkey, "AppName", 0, REG_SZ, (BYTE*) appName, lstrlenA(appName) + 1);
1615             if (docName)
1616                 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1617             RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1618             RegCloseKey(subkey);
1619         }
1620         else
1621             WINE_ERR("could not create extension subkey\n");
1622         RegCloseKey(assocKey);
1623     }
1624     else
1625         WINE_ERR("could not open file associations key\n");
1626 }
1627
1628 static BOOL cleanup_associations(void)
1629 {
1630     HKEY assocKey;
1631     BOOL hasChanged = FALSE;
1632     if ((assocKey = open_associations_reg_key()))
1633     {
1634         int i;
1635         BOOL done = FALSE;
1636         for (i = 0; !done; i++)
1637         {
1638             WCHAR *extensionW = NULL;
1639             char *extensionA = NULL;
1640             DWORD size = 1024;
1641             LSTATUS ret;
1642
1643             do
1644             {
1645                 HeapFree(GetProcessHeap(), 0, extensionW);
1646                 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1647                 if (extensionW == NULL)
1648                 {
1649                     WINE_ERR("out of memory\n");
1650                     ret = ERROR_OUTOFMEMORY;
1651                     break;
1652                 }
1653                 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1654                 size *= 2;
1655             } while (ret == ERROR_MORE_DATA);
1656
1657             if (ret == ERROR_SUCCESS)
1658             {
1659                 WCHAR *command;
1660                 extensionA = wchars_to_utf8_chars(extensionW);
1661                 if (extensionA == NULL)
1662                 {
1663                     WINE_ERR("out of memory\n");
1664                     done = TRUE;
1665                     goto end;
1666                 }
1667                 command = assoc_query(ASSOCSTR_COMMAND, extensionW, NULL);
1668                 if (command == NULL)
1669                 {
1670                     char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1671                     if (desktopFile)
1672                     {
1673                         WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1674                         remove(desktopFile);
1675                     }
1676                     RegDeleteKeyW(assocKey, extensionW);
1677                     hasChanged = TRUE;
1678                     HeapFree(GetProcessHeap(), 0, desktopFile);
1679                 }
1680                 HeapFree(GetProcessHeap(), 0, command);
1681             }
1682             else
1683             {
1684                 if (ret != ERROR_NO_MORE_ITEMS)
1685                     WINE_ERR("error %d while reading registry\n", ret);
1686                 done = TRUE;
1687             }
1688         end:
1689             HeapFree(GetProcessHeap(), 0, extensionA);
1690             HeapFree(GetProcessHeap(), 0, extensionW);
1691         }
1692         RegCloseKey(assocKey);
1693     }
1694     else
1695         WINE_ERR("could not open file associations key\n");
1696     return hasChanged;
1697 }
1698
1699 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1700                                               const char *mime_type, const char *comment)
1701 {
1702     BOOL ret = FALSE;
1703     char *filename;
1704
1705     WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1706                wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1707
1708     filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1709     if (filename)
1710     {
1711         FILE *packageFile = fopen(filename, "w");
1712         if (packageFile)
1713         {
1714             fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1715             fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1716             fprintf(packageFile, "  <mime-type type=\"%s\">\n", mime_type);
1717             fprintf(packageFile, "    <glob pattern=\"*%s\"/>\n", dot_extension);
1718             if (comment)
1719                 fprintf(packageFile, "    <comment>%s</comment>\n", comment);
1720             fprintf(packageFile, "  </mime-type>\n");
1721             fprintf(packageFile, "</mime-info>\n");
1722             ret = TRUE;
1723             fclose(packageFile);
1724         }
1725         else
1726             WINE_ERR("error writing file %s\n", filename);
1727         HeapFree(GetProcessHeap(), 0, filename);
1728     }
1729     else
1730         WINE_ERR("out of memory\n");
1731     return ret;
1732 }
1733
1734 static BOOL is_extension_blacklisted(LPCWSTR extension)
1735 {
1736     /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1737     static const WCHAR comW[] = {'.','c','o','m',0};
1738     static const WCHAR exeW[] = {'.','e','x','e',0};
1739     static const WCHAR msiW[] = {'.','m','s','i',0};
1740
1741     if (!strcmpiW(extension, comW) ||
1742         !strcmpiW(extension, exeW) ||
1743         !strcmpiW(extension, msiW))
1744         return TRUE;
1745     return FALSE;
1746 }
1747
1748 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1749                                                 const char *friendlyAppName, const char *mimeType,
1750                                                 const char *progId)
1751 {
1752     BOOL ret = FALSE;
1753     FILE *desktop;
1754
1755     WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1756                wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1757                wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1758
1759     desktop = fopen(desktopPath, "w");
1760     if (desktop)
1761     {
1762         fprintf(desktop, "[Desktop Entry]\n");
1763         fprintf(desktop, "Type=Application\n");
1764         fprintf(desktop, "Name=%s\n", friendlyAppName);
1765         fprintf(desktop, "MimeType=%s\n", mimeType);
1766         fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1767         fprintf(desktop, "NoDisplay=true\n");
1768         fprintf(desktop, "StartupNotify=true\n");
1769         ret = TRUE;
1770         fclose(desktop);
1771     }
1772     else
1773         WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1774     return ret;
1775 }
1776
1777 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1778 {
1779     struct list *nativeMimeTypes = NULL;
1780     LSTATUS ret = 0;
1781     int i;
1782     BOOL hasChanged = FALSE;
1783
1784     if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1785     {
1786         WINE_ERR("could not build native MIME types\n");
1787         return FALSE;
1788     }
1789
1790     for (i = 0; ; i++)
1791     {
1792         WCHAR *extensionW = NULL;
1793         DWORD size = 1024;
1794
1795         do
1796         {
1797             HeapFree(GetProcessHeap(), 0, extensionW);
1798             extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1799             if (extensionW == NULL)
1800             {
1801                 WINE_ERR("out of memory\n");
1802                 ret = ERROR_OUTOFMEMORY;
1803                 break;
1804             }
1805             ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1806             size *= 2;
1807         } while (ret == ERROR_MORE_DATA);
1808
1809         if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1810         {
1811             char *extensionA = NULL;
1812             WCHAR *commandW = NULL;
1813             WCHAR *friendlyDocNameW = NULL;
1814             char *friendlyDocNameA = NULL;
1815             WCHAR *contentTypeW = NULL;
1816             char *mimeTypeA = NULL;
1817             WCHAR *friendlyAppNameW = NULL;
1818             char *friendlyAppNameA = NULL;
1819             WCHAR *progIdW = NULL;
1820             char *progIdA = NULL;
1821
1822             extensionA = wchars_to_utf8_chars(extensionW);
1823             if (extensionA == NULL)
1824             {
1825                 WINE_ERR("out of memory\n");
1826                 goto end;
1827             }
1828
1829             friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
1830             if (friendlyDocNameW)
1831             {
1832                 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
1833                 if (friendlyDocNameA == NULL)
1834                 {
1835                     WINE_ERR("out of memory\n");
1836                     goto end;
1837                 }
1838             }
1839
1840             contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
1841
1842             if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
1843                 goto end;
1844
1845             if (mimeTypeA == NULL)
1846             {
1847                 if (contentTypeW != NULL)
1848                     mimeTypeA = wchars_to_utf8_chars(contentTypeW);
1849                 else
1850                     mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
1851
1852                 if (mimeTypeA != NULL)
1853                 {
1854                     write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
1855                     hasChanged = TRUE;
1856                 }
1857                 else
1858                 {
1859                     WINE_FIXME("out of memory\n");
1860                     goto end;
1861                 }
1862             }
1863
1864             commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, NULL);
1865             if (commandW == NULL)
1866                 /* no command => no application is associated */
1867                 goto end;
1868
1869             friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
1870             if (friendlyAppNameW)
1871             {
1872                 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
1873                 if (friendlyAppNameA == NULL)
1874                 {
1875                     WINE_ERR("out of memory\n");
1876                     goto end;
1877                 }
1878             }
1879             else
1880             {
1881                 friendlyAppNameA = heap_printf("A Wine application");
1882                 if (friendlyAppNameA == NULL)
1883                 {
1884                     WINE_ERR("out of memory\n");
1885                     goto end;
1886                 }
1887             }
1888
1889             progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
1890             if (progIdW)
1891             {
1892                 progIdA = wchars_to_utf8_chars(progIdW);
1893                 if (progIdA == NULL)
1894                 {
1895                     WINE_ERR("out of memory\n");
1896                     goto end;
1897                 }
1898             }
1899             else
1900                 goto end; /* no progID => not a file type association */
1901
1902             if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
1903             {
1904                 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
1905                 if (desktopPath)
1906                 {
1907                     if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
1908                     {
1909                         hasChanged = TRUE;
1910                         update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
1911                     }
1912                     HeapFree(GetProcessHeap(), 0, desktopPath);
1913                 }
1914             }
1915
1916         end:
1917             HeapFree(GetProcessHeap(), 0, extensionA);
1918             HeapFree(GetProcessHeap(), 0, commandW);
1919             HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
1920             HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
1921             HeapFree(GetProcessHeap(), 0, contentTypeW);
1922             HeapFree(GetProcessHeap(), 0, mimeTypeA);
1923             HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
1924             HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
1925             HeapFree(GetProcessHeap(), 0, progIdW);
1926             HeapFree(GetProcessHeap(), 0, progIdA);
1927         }
1928         HeapFree(GetProcessHeap(), 0, extensionW);
1929         if (ret != ERROR_SUCCESS)
1930             break;
1931     }
1932
1933     free_native_mime_types(nativeMimeTypes);
1934     return hasChanged;
1935 }
1936
1937 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1938 {
1939     static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1940                                    '\\','s','t','a','r','t','.','e','x','e',0};
1941     char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1942     char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1943     WCHAR szTmp[INFOTIPSIZE];
1944     WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1945     WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1946     int iIconId = 0, r = -1;
1947     DWORD csidl = -1;
1948     HANDLE hsem = NULL;
1949
1950     if ( !link )
1951     {
1952         WINE_ERR("Link name is null\n");
1953         return FALSE;
1954     }
1955
1956     if( !GetLinkLocation( link, &csidl, &link_name ) )
1957     {
1958         WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1959         return TRUE;
1960     }
1961     if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1962     {
1963         WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1964         return TRUE;
1965     }
1966     WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));
1967
1968     szTmp[0] = 0;
1969     IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1970     ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1971     WINE_TRACE("workdir    : %s\n", wine_dbgstr_w(szWorkDir));
1972
1973     szTmp[0] = 0;
1974     IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1975     ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1976     WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1977
1978     get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1979     WINE_TRACE("path       : %s\n", wine_dbgstr_w(szPath));
1980     WINE_TRACE("args       : %s\n", wine_dbgstr_w(szArgs));
1981
1982     szTmp[0] = 0;
1983     IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1984     ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1985     WINE_TRACE("icon file  : %s\n", wine_dbgstr_w(szIconPath) );
1986
1987     if( !szPath[0] )
1988     {
1989         LPITEMIDLIST pidl = NULL;
1990         IShellLinkW_GetIDList( sl, &pidl );
1991         if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1992             WINE_TRACE("pidl path  : %s\n", wine_dbgstr_w(szPath));
1993     }
1994
1995     /* extract the icon */
1996     if( szIconPath[0] )
1997         icon_name = extract_icon( szIconPath , iIconId, bWait );
1998     else
1999         icon_name = extract_icon( szPath, iIconId, bWait );
2000
2001     /* fail - try once again after parent process exit */
2002     if( !icon_name )
2003     {
2004         if (bWait)
2005         {
2006             WINE_WARN("Unable to extract icon, deferring.\n");
2007             goto cleanup;
2008         }
2009         WINE_ERR("failed to extract icon from %s\n",
2010                  wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2011     }
2012
2013     /* check the path */
2014     if( szPath[0] )
2015     {
2016         static const WCHAR exeW[] = {'.','e','x','e',0};
2017         WCHAR *p;
2018
2019         /* check for .exe extension */
2020         if (!(p = strrchrW( szPath, '.' )) ||
2021             strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2022             lstrcmpiW( p, exeW ))
2023         {
2024             /* Not .exe - use 'start.exe' to launch this file */
2025             p = szArgs + lstrlenW(szPath) + 2;
2026             if (szArgs[0])
2027             {
2028                 p[0] = ' ';
2029                 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2030                                            sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2031             }
2032             else
2033                 p[0] = 0;
2034
2035             szArgs[0] = '"';
2036             lstrcpyW(szArgs + 1, szPath);
2037             p[-1] = '"';
2038
2039             GetWindowsDirectoryW(szPath, MAX_PATH);
2040             lstrcatW(szPath, startW);
2041         }
2042
2043         /* convert app working dir */
2044         if (szWorkDir[0])
2045             work_dir = wine_get_unix_file_name( szWorkDir );
2046     }
2047     else
2048     {
2049         /* if there's no path... try run the link itself */
2050         lstrcpynW(szArgs, link, MAX_PATH);
2051         GetWindowsDirectoryW(szPath, MAX_PATH);
2052         lstrcatW(szPath, startW);
2053     }
2054
2055     /* escape the path and parameters */
2056     escaped_path = escape(szPath);
2057     escaped_args = escape(szArgs);
2058     escaped_description = escape(szDescription);
2059
2060     /* building multiple menus concurrently has race conditions */
2061     hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2062     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2063     {
2064         WINE_ERR("failed wait for semaphore\n");
2065         goto cleanup;
2066     }
2067
2068     if (in_desktop_dir(csidl))
2069     {
2070         char *location;
2071         const char *lastEntry;
2072         lastEntry = strrchr(link_name, '/');
2073         if (lastEntry == NULL)
2074             lastEntry = link_name;
2075         else
2076             ++lastEntry;
2077         location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2078         if (location)
2079         {
2080             r = !write_desktop_entry(location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2081             HeapFree(GetProcessHeap(), 0, location);
2082         }
2083     }
2084     else
2085         r = !write_menu_entry(link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2086
2087     ReleaseSemaphore( hsem, 1, NULL );
2088
2089 cleanup:
2090     if (hsem) CloseHandle( hsem );
2091     HeapFree( GetProcessHeap(), 0, icon_name );
2092     HeapFree( GetProcessHeap(), 0, work_dir );
2093     HeapFree( GetProcessHeap(), 0, link_name );
2094     HeapFree( GetProcessHeap(), 0, escaped_args );
2095     HeapFree( GetProcessHeap(), 0, escaped_path );
2096     HeapFree( GetProcessHeap(), 0, escaped_description );
2097
2098     if (r && !bWait)
2099         WINE_ERR("failed to build the menu\n" );
2100
2101     return ( r == 0 );
2102 }
2103
2104 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2105 {
2106     char *link_name = NULL;
2107     DWORD csidl = -1;
2108     LPWSTR urlPath;
2109     char *escaped_urlPath = NULL;
2110     HRESULT hr;
2111     HANDLE hSem = NULL;
2112     BOOL ret = TRUE;
2113     int r = -1;
2114
2115     if ( !link )
2116     {
2117         WINE_ERR("Link name is null\n");
2118         return TRUE;
2119     }
2120
2121     if( !GetLinkLocation( link, &csidl, &link_name ) )
2122     {
2123         WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2124         return TRUE;
2125     }
2126     if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2127     {
2128         WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2129         ret = TRUE;
2130         goto cleanup;
2131     }
2132     WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));
2133
2134     hr = url->lpVtbl->GetURL(url, &urlPath);
2135     if (FAILED(hr))
2136     {
2137         ret = TRUE;
2138         goto cleanup;
2139     }
2140     WINE_TRACE("path       : %s\n", wine_dbgstr_w(urlPath));
2141
2142     escaped_urlPath = escape(urlPath);
2143
2144     hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2145     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2146     {
2147         WINE_ERR("failed wait for semaphore\n");
2148         goto cleanup;
2149     }
2150     if (in_desktop_dir(csidl))
2151     {
2152         char *location;
2153         const char *lastEntry;
2154         lastEntry = strrchr(link_name, '/');
2155         if (lastEntry == NULL)
2156             lastEntry = link_name;
2157         else
2158             ++lastEntry;
2159         location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2160         if (location)
2161         {
2162             r = !write_desktop_entry(location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2163             HeapFree(GetProcessHeap(), 0, location);
2164         }
2165     }
2166     else
2167         r = !write_menu_entry(link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2168     ret = (r != 0);
2169     ReleaseSemaphore(hSem, 1, NULL);
2170
2171 cleanup:
2172     if (hSem)
2173         CloseHandle(hSem);
2174     HeapFree(GetProcessHeap(), 0, link_name);
2175     CoTaskMemFree( urlPath );
2176     HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2177     return ret;
2178 }
2179
2180 static BOOL WaitForParentProcess( void )
2181 {
2182     PROCESSENTRY32 procentry;
2183     HANDLE hsnapshot = NULL, hprocess = NULL;
2184     DWORD ourpid = GetCurrentProcessId();
2185     BOOL ret = FALSE, rc;
2186
2187     WINE_TRACE("Waiting for parent process\n");
2188     if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2189         INVALID_HANDLE_VALUE)
2190     {
2191         WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2192         goto done;
2193     }
2194
2195     procentry.dwSize = sizeof(PROCESSENTRY32);
2196     rc = Process32First( hsnapshot, &procentry );
2197     while (rc)
2198     {
2199         if (procentry.th32ProcessID == ourpid) break;
2200         rc = Process32Next( hsnapshot, &procentry );
2201     }
2202     if (!rc)
2203     {
2204         WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2205         goto done;
2206     }
2207
2208     if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2209         NULL)
2210     {
2211         WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2212                  GetLastError());
2213         goto done;
2214     }
2215
2216     if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2217         ret = TRUE;
2218     else
2219         WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2220
2221 done:
2222     if (hprocess) CloseHandle( hprocess );
2223     if (hsnapshot) CloseHandle( hsnapshot );
2224     return ret;
2225 }
2226
2227 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2228 {
2229     IShellLinkW *sl;
2230     IPersistFile *pf;
2231     HRESULT r;
2232     WCHAR fullname[MAX_PATH];
2233     DWORD len;
2234
2235     WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2236
2237     if( !linkname[0] )
2238     {
2239         WINE_ERR("link name missing\n");
2240         return 1;
2241     }
2242
2243     len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2244     if (len==0 || len>MAX_PATH)
2245     {
2246         WINE_ERR("couldn't get full path of link file\n");
2247         return 1;
2248     }
2249
2250     r = CoInitialize( NULL );
2251     if( FAILED( r ) )
2252     {
2253         WINE_ERR("CoInitialize failed\n");
2254         return 1;
2255     }
2256
2257     r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2258                           &IID_IShellLinkW, (LPVOID *) &sl );
2259     if( FAILED( r ) )
2260     {
2261         WINE_ERR("No IID_IShellLink\n");
2262         return 1;
2263     }
2264
2265     r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2266     if( FAILED( r ) )
2267     {
2268         WINE_ERR("No IID_IPersistFile\n");
2269         return 1;
2270     }
2271
2272     r = IPersistFile_Load( pf, fullname, STGM_READ );
2273     if( SUCCEEDED( r ) )
2274     {
2275         /* If something fails (eg. Couldn't extract icon)
2276          * wait for parent process and try again
2277          */
2278         if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2279         {
2280             WaitForParentProcess();
2281             InvokeShellLinker( sl, fullname, FALSE );
2282         }
2283     }
2284     else
2285     {
2286         WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2287     }
2288
2289     IPersistFile_Release( pf );
2290     IShellLinkW_Release( sl );
2291
2292     CoUninitialize();
2293
2294     return !r;
2295 }
2296
2297 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2298 {
2299     IUniformResourceLocatorW *url;
2300     IPersistFile *pf;
2301     HRESULT r;
2302     WCHAR fullname[MAX_PATH];
2303     DWORD len;
2304
2305     WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2306
2307     if( !urlname[0] )
2308     {
2309         WINE_ERR("URL name missing\n");
2310         return 1;
2311     }
2312
2313     len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2314     if (len==0 || len>MAX_PATH)
2315     {
2316         WINE_ERR("couldn't get full path of URL file\n");
2317         return 1;
2318     }
2319
2320     r = CoInitialize( NULL );
2321     if( FAILED( r ) )
2322     {
2323         WINE_ERR("CoInitialize failed\n");
2324         return 1;
2325     }
2326
2327     r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2328                           &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2329     if( FAILED( r ) )
2330     {
2331         WINE_ERR("No IID_IUniformResourceLocatorW\n");
2332         return 1;
2333     }
2334
2335     r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2336     if( FAILED( r ) )
2337     {
2338         WINE_ERR("No IID_IPersistFile\n");
2339         return 1;
2340     }
2341     r = IPersistFile_Load( pf, fullname, STGM_READ );
2342     if( SUCCEEDED( r ) )
2343     {
2344         /* If something fails (eg. Couldn't extract icon)
2345          * wait for parent process and try again
2346          */
2347         if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2348         {
2349             WaitForParentProcess();
2350             InvokeShellLinkerForURL( url, fullname, FALSE );
2351         }
2352     }
2353
2354     IPersistFile_Release( pf );
2355     url->lpVtbl->Release( url );
2356
2357     CoUninitialize();
2358
2359     return !r;
2360 }
2361
2362 static void RefreshFileTypeAssociations(void)
2363 {
2364     HANDLE hSem = NULL;
2365     char *mime_dir = NULL;
2366     char *packages_dir = NULL;
2367     char *applications_dir = NULL;
2368     BOOL hasChanged;
2369
2370     hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2371     if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2372     {
2373         WINE_ERR("failed wait for semaphore\n");
2374         CloseHandle(hSem);
2375         hSem = NULL;
2376         goto end;
2377     }
2378
2379     mime_dir = heap_printf("%s/mime", xdg_data_dir);
2380     if (mime_dir == NULL)
2381     {
2382         WINE_ERR("out of memory\n");
2383         goto end;
2384     }
2385     create_directories(mime_dir);
2386
2387     packages_dir = heap_printf("%s/packages", mime_dir);
2388     if (packages_dir == NULL)
2389     {
2390         WINE_ERR("out of memory\n");
2391         goto end;
2392     }
2393     create_directories(packages_dir);
2394
2395     applications_dir = heap_printf("%s/applications", xdg_data_dir);
2396     if (applications_dir == NULL)
2397     {
2398         WINE_ERR("out of memory\n");
2399         goto end;
2400     }
2401     create_directories(applications_dir);
2402
2403     hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2404     hasChanged |= cleanup_associations();
2405     if (hasChanged)
2406     {
2407         char *command = heap_printf("update-mime-database %s", mime_dir);
2408         if (command)
2409         {
2410             system(command);
2411             HeapFree(GetProcessHeap(), 0, command);
2412         }
2413         else
2414         {
2415             WINE_ERR("out of memory\n");
2416             goto end;
2417         }
2418
2419         command = heap_printf("update-desktop-database %s/applications", xdg_data_dir);
2420         if (command)
2421         {
2422             system(command);
2423             HeapFree(GetProcessHeap(), 0, command);
2424         }
2425         else
2426         {
2427             WINE_ERR("out of memory\n");
2428             goto end;
2429         }
2430     }
2431
2432 end:
2433     if (hSem)
2434     {
2435         ReleaseSemaphore(hSem, 1, NULL);
2436         CloseHandle(hSem);
2437     }
2438     HeapFree(GetProcessHeap(), 0, mime_dir);
2439     HeapFree(GetProcessHeap(), 0, packages_dir);
2440     HeapFree(GetProcessHeap(), 0, applications_dir);
2441 }
2442
2443 static CHAR *next_token( LPSTR *p )
2444 {
2445     LPSTR token = NULL, t = *p;
2446
2447     if( !t )
2448         return NULL;
2449
2450     while( t && !token )
2451     {
2452         switch( *t )
2453         {
2454         case ' ':
2455             t++;
2456             continue;
2457         case '"':
2458             /* unquote the token */
2459             token = ++t;
2460             t = strchr( token, '"' );
2461             if( t )
2462                  *t++ = 0;
2463             break;
2464         case 0:
2465             t = NULL;
2466             break;
2467         default:
2468             token = t;
2469             t = strchr( token, ' ' );
2470             if( t )
2471                  *t++ = 0;
2472             break;
2473         }
2474     }
2475     *p = t;
2476     return token;
2477 }
2478
2479 static BOOL init_xdg(void)
2480 {
2481     WCHAR shellDesktopPath[MAX_PATH];
2482     HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2483     if (SUCCEEDED(hr))
2484         xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2485     if (xdg_desktop_dir == NULL)
2486     {
2487         WINE_ERR("error looking up the desktop directory\n");
2488         return FALSE;
2489     }
2490
2491     if (getenv("XDG_CONFIG_HOME"))
2492         xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2493     else
2494         xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2495     if (xdg_config_dir)
2496     {
2497         create_directories(xdg_config_dir);
2498         if (getenv("XDG_DATA_HOME"))
2499             xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
2500         else
2501             xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2502         if (xdg_data_dir)
2503         {
2504             char *buffer;
2505             create_directories(xdg_data_dir);
2506             buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2507             if (buffer)
2508             {
2509                 mkdir(buffer, 0777);
2510                 HeapFree(GetProcessHeap(), 0, buffer);
2511             }
2512             return TRUE;
2513         }
2514         HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2515     }
2516     WINE_ERR("out of memory\n");
2517     return FALSE;
2518 }
2519
2520 /***********************************************************************
2521  *
2522  *           WinMain
2523  */
2524 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
2525 {
2526     LPSTR token = NULL, p;
2527     BOOL bWait = FALSE;
2528     BOOL bURL = FALSE;
2529     int ret = 0;
2530
2531     if (!init_xdg())
2532         return 1;
2533
2534     for( p = cmdline; p && *p; )
2535     {
2536         token = next_token( &p );
2537         if( !token )
2538             break;
2539         if( !lstrcmpA( token, "-a" ) )
2540         {
2541             RefreshFileTypeAssociations();
2542             break;
2543         }
2544         if( !lstrcmpA( token, "-w" ) )
2545             bWait = TRUE;
2546         else if ( !lstrcmpA( token, "-u" ) )
2547             bURL = TRUE;
2548         else if( token[0] == '-' )
2549         {
2550             WINE_ERR( "unknown option %s\n",token);
2551         }
2552         else
2553         {
2554             WCHAR link[MAX_PATH];
2555             BOOL bRet;
2556
2557             MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2558             if (bURL)
2559                 bRet = Process_URL( link, bWait );
2560             else
2561                 bRet = Process_Link( link, bWait );
2562             if (!bRet)
2563             {
2564                 WINE_ERR( "failed to build menu item for %s\n",token);
2565                 ret = 1;
2566             }
2567         }
2568     }
2569
2570     return ret;
2571 }