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