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