winemenubuilder: Fix resource leak (Valgrind).
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blobb617510da06622f6b21c54d5d544b05250f1e16a
1 /*
2 * Helper program to build unix menu entries
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
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.
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.
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
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.
33 * This program will read a Windows shortcut file using the IShellLink
34 * interface, then create a KDE/GNOME menu entry for the shortcut.
36 * winemenubuilder [ -w ] <shortcut.lnk>
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.
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).
65 #include "config.h"
66 #include "wine/port.h"
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
80 #define COBJMACROS
81 #define NONAMELESSUNION
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>
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"
100 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
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)
107 /* link file formats */
109 #include "pshpack1.h"
111 typedef struct
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;
123 typedef struct
125 WORD idReserved;
126 WORD idType;
127 WORD idCount;
128 GRPICONDIRENTRY idEntries[1];
129 } GRPICONDIR;
131 typedef struct
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;
143 typedef struct
145 WORD idReserved;
146 WORD idType;
147 WORD idCount;
148 } ICONDIR;
150 typedef struct
152 WORD offset;
153 WORD length;
154 WORD flags;
155 WORD id;
156 WORD handle;
157 WORD usage;
158 } NE_NAMEINFO;
160 typedef struct
162 WORD type_id;
163 WORD count;
164 DWORD resloader;
165 } NE_TYPEINFO;
167 #define NE_RSCTYPE_ICON 0x8003
168 #define NE_RSCTYPE_GROUP_ICON 0x800e
170 #include "poppack.h"
172 typedef struct
174 HRSRC *pResInfo;
175 int nIndex;
176 } ENUMRESSTRUCT;
178 struct xdg_mime_type
180 char *mimeType;
181 char *glob;
182 char *lower_glob;
183 struct list entry;
186 struct rb_string_entry
188 char *string;
189 struct wine_rb_entry entry;
192 DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
194 static char *xdg_config_dir;
195 static char *xdg_data_dir;
196 static char *xdg_desktop_dir;
198 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra);
199 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream);
201 /* Utility routines */
202 static unsigned short crc16(const char* string)
204 unsigned short crc = 0;
205 int i, j, xor_poly;
207 for (i = 0; string[i] != 0; i++)
209 char c = string[i];
210 for (j = 0; j < 8; c >>= 1, j++)
212 xor_poly = (c ^ crc) & 1;
213 crc >>= 1;
214 if (xor_poly)
215 crc ^= 0xa001;
218 return crc;
221 static char *strdupA( const char *str )
223 char *ret;
225 if (!str) return NULL;
226 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
227 return ret;
230 static char* heap_printf(const char *format, ...)
232 va_list args;
233 int size = 4096;
234 char *buffer, *ret;
235 int n;
237 while (1)
239 buffer = HeapAlloc(GetProcessHeap(), 0, size);
240 if (buffer == NULL)
241 break;
242 va_start(args, format);
243 n = vsnprintf(buffer, size, format, args);
244 va_end(args);
245 if (n == -1)
246 size *= 2;
247 else if (n >= size)
248 size = n + 1;
249 else
250 break;
251 HeapFree(GetProcessHeap(), 0, buffer);
254 if (!buffer) return NULL;
255 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
256 if (!ret) ret = buffer;
257 return ret;
260 static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
262 const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);
264 return strcmp((char*)key, t->string);
267 static void *winemenubuilder_rb_alloc(size_t size)
269 return HeapAlloc(GetProcessHeap(), 0, size);
272 static void *winemenubuilder_rb_realloc(void *ptr, size_t size)
274 return HeapReAlloc(GetProcessHeap(), 0, ptr, size);
277 static void winemenubuilder_rb_free(void *ptr)
279 HeapFree(GetProcessHeap(), 0, ptr);
282 static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
284 struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
285 HeapFree(GetProcessHeap(), 0, t->string);
286 HeapFree(GetProcessHeap(), 0, t);
289 static const struct wine_rb_functions winemenubuilder_rb_functions =
291 winemenubuilder_rb_alloc,
292 winemenubuilder_rb_realloc,
293 winemenubuilder_rb_free,
294 winemenubuilder_rb_string_compare,
297 static void write_xml_text(FILE *file, const char *text)
299 int i;
300 for (i = 0; text[i]; i++)
302 if (text[i] == '&')
303 fputs("&amp;", file);
304 else if (text[i] == '<')
305 fputs("&lt;", file);
306 else if (text[i] == '>')
307 fputs("&gt;", file);
308 else if (text[i] == '\'')
309 fputs("&apos;", file);
310 else if (text[i] == '"')
311 fputs("&quot;", file);
312 else
313 fputc(text[i], file);
317 static BOOL create_directories(char *directory)
319 BOOL ret = TRUE;
320 int i;
322 for (i = 0; directory[i]; i++)
324 if (i > 0 && directory[i] == '/')
326 directory[i] = 0;
327 mkdir(directory, 0777);
328 directory[i] = '/';
331 if (mkdir(directory, 0777) && errno != EEXIST)
332 ret = FALSE;
334 return ret;
337 static char* wchars_to_utf8_chars(LPCWSTR string)
339 char *ret;
340 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
341 ret = HeapAlloc(GetProcessHeap(), 0, size);
342 if (ret)
343 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
344 return ret;
347 static char* wchars_to_unix_chars(LPCWSTR string)
349 char *ret;
350 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
351 ret = HeapAlloc(GetProcessHeap(), 0, size);
352 if (ret)
353 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
354 return ret;
357 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
359 WCHAR *ret;
360 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
361 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
362 if (ret)
363 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
364 return ret;
367 /* Icon extraction routines
369 * FIXME: should use PrivateExtractIcons and friends
370 * FIXME: should not use stdio
373 static HRESULT convert_to_native_icon(IStream *icoFile, int *indices, int numIndices,
374 const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
376 WCHAR *dosOutputFileName = NULL;
377 IWICImagingFactory *factory = NULL;
378 IWICBitmapDecoder *decoder = NULL;
379 IWICBitmapEncoder *encoder = NULL;
380 IWICBitmapScaler *scaler = NULL;
381 IStream *outputFile = NULL;
382 int i;
383 HRESULT hr = E_FAIL;
385 dosOutputFileName = wine_get_dos_file_name(outputFileName);
386 if (dosOutputFileName == NULL)
388 WINE_ERR("error converting %s to DOS file name\n", outputFileName);
389 goto end;
391 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
392 &IID_IWICImagingFactory, (void**)&factory);
393 if (FAILED(hr))
395 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
396 goto end;
398 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
399 WICDecodeMetadataCacheOnDemand, &decoder);
400 if (FAILED(hr))
402 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
403 goto end;
405 if (IsEqualCLSID(outputFormat,&CLSID_WICIcnsEncoder))
407 hr = IWICImagingFactory_CreateBitmapScaler(factory, &scaler);
408 if (FAILED(hr))
410 WINE_WARN("error 0x%08X creating IWICBitmapScaler\n", hr);
413 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
414 &IID_IWICBitmapEncoder, (void**)&encoder);
415 if (FAILED(hr))
417 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
418 goto end;
420 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
421 if (FAILED(hr))
423 WINE_ERR("error 0x%08X creating output file %s\n", hr, wine_dbgstr_w(dosOutputFileName));
424 goto end;
426 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, GENERIC_WRITE);
427 if (FAILED(hr))
429 WINE_ERR("error 0x%08X initializing encoder\n", hr);
430 goto end;
433 for (i = 0; i < numIndices; i++)
435 IWICBitmapFrameDecode *sourceFrame = NULL;
436 IWICBitmapSource *sourceBitmap = NULL;
437 IWICBitmapFrameEncode *dstFrame = NULL;
438 IPropertyBag2 *options = NULL;
439 UINT width, height;
441 hr = IWICBitmapDecoder_GetFrame(decoder, indices[i], &sourceFrame);
442 if (FAILED(hr))
444 WINE_ERR("error 0x%08X getting frame %d\n", hr, indices[i]);
445 goto endloop;
447 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
448 if (FAILED(hr))
450 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
451 goto endloop;
453 if ( scaler)
455 IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
456 if (width == 64) /* Classic Mode */
458 hr = IWICBitmapScaler_Initialize( scaler, sourceBitmap, 128, 128,
459 WICBitmapInterpolationModeNearestNeighbor);
460 if (FAILED(hr))
461 WINE_ERR("error 0x%08X scaling bitmap\n", hr);
462 else
464 IWICBitmapSource_Release(sourceBitmap);
465 IWICBitmapScaler_QueryInterface(scaler, &IID_IWICBitmapSource, (LPVOID)&sourceBitmap);
469 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
470 if (FAILED(hr))
472 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
473 goto endloop;
475 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
476 if (FAILED(hr))
478 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
479 goto endloop;
481 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
482 if (FAILED(hr))
484 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
485 goto endloop;
487 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
488 if (FAILED(hr))
490 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
491 goto endloop;
493 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
494 if (FAILED(hr))
496 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
497 goto endloop;
499 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
500 if (FAILED(hr))
502 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
503 goto endloop;
505 hr = IWICBitmapFrameEncode_Commit(dstFrame);
506 if (FAILED(hr))
508 WINE_ERR("error 0x%08X committing frame\n", hr);
509 goto endloop;
511 endloop:
512 if (sourceFrame)
513 IWICBitmapFrameDecode_Release(sourceFrame);
514 if (sourceBitmap)
515 IWICBitmapSource_Release(sourceBitmap);
516 if (dstFrame)
517 IWICBitmapFrameEncode_Release(dstFrame);
518 if (options)
519 IPropertyBag2_Release(options);
522 hr = IWICBitmapEncoder_Commit(encoder);
523 if (FAILED(hr))
525 WINE_ERR("error 0x%08X committing encoder\n", hr);
526 goto end;
529 end:
530 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
531 if (factory)
532 IWICImagingFactory_Release(factory);
533 if (decoder)
534 IWICBitmapDecoder_Release(decoder);
535 if (scaler)
536 IWICBitmapScaler_Release(scaler);
537 if (encoder)
538 IWICBitmapEncoder_Release(encoder);
539 if (outputFile)
540 IStream_Release(outputFile);
541 return hr;
544 struct IconData16 {
545 BYTE *fileBytes;
546 DWORD fileSize;
547 NE_TYPEINFO *iconResources;
548 WORD alignmentShiftCount;
551 static int populate_module16_icons(struct IconData16 *iconData16, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
553 int i, j;
554 int validEntries = 0;
556 for (i = 0; i < grpIconDir->idCount; i++)
558 BYTE *iconPtr = (BYTE*)iconData16->iconResources;
559 NE_NAMEINFO *matchingIcon = NULL;
560 iconPtr += sizeof(NE_TYPEINFO);
561 for (j = 0; j < iconData16->iconResources->count; j++)
563 NE_NAMEINFO *iconInfo = (NE_NAMEINFO*)iconPtr;
564 if ((((BYTE*)iconPtr) + sizeof(NE_NAMEINFO)) > (iconData16->fileBytes + iconData16->fileSize))
566 WINE_WARN("file too small for icon NE_NAMEINFO\n");
567 break;
569 if (iconInfo->id == (0x8000 | grpIconDir->idEntries[i].nID))
571 matchingIcon = iconInfo;
572 break;
574 iconPtr += sizeof(NE_NAMEINFO);
577 if (matchingIcon == NULL)
578 continue;
579 if (((matchingIcon->offset << iconData16->alignmentShiftCount) + grpIconDir->idEntries[i].dwBytesInRes) > iconData16->fileSize)
581 WINE_WARN("file too small for icon contents\n");
582 break;
585 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
586 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
587 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
588 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
589 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
590 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
591 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
592 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
593 validEntries++;
594 memcpy(&icons[*iconOffset], &iconData16->fileBytes[matchingIcon->offset << iconData16->alignmentShiftCount], grpIconDir->idEntries[i].dwBytesInRes);
595 *iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
597 return validEntries;
600 static int populate_module_icons(HMODULE hModule, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
602 int i;
603 int validEntries = 0;
605 for (i = 0; i < grpIconDir->idCount; i++)
607 HRSRC hResInfo;
608 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
609 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
611 HGLOBAL hResData;
612 if ((hResData = LoadResource(hModule, hResInfo)))
614 BITMAPINFO *pIcon;
615 if ((pIcon = LockResource(hResData)))
617 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
618 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
619 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
620 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
621 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
622 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
623 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
624 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
625 validEntries++;
626 memcpy(&icons[*iconOffset], pIcon, grpIconDir->idEntries[i].dwBytesInRes);
627 *iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
629 FreeResource(hResData);
633 return validEntries;
636 static IStream *add_module_icons_to_stream(struct IconData16 *iconData16, HMODULE hModule, GRPICONDIR *grpIconDir)
638 int i;
639 SIZE_T iconsSize = 0;
640 BYTE *icons = NULL;
641 ICONDIRENTRY *iconDirEntries = NULL;
642 IStream *stream = NULL;
643 HRESULT hr = E_FAIL;
644 ULONG bytesWritten;
645 ICONDIR iconDir;
646 SIZE_T iconOffset;
647 int validEntries = 0;
648 LARGE_INTEGER zero;
650 for (i = 0; i < grpIconDir->idCount; i++)
651 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
652 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
653 if (icons == NULL)
655 WINE_ERR("out of memory allocating icon\n");
656 goto end;
659 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
660 if (iconDirEntries == NULL)
662 WINE_ERR("out of memory allocating icon dir entries\n");
663 goto end;
666 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
667 if (FAILED(hr))
669 WINE_ERR("error creating icon stream\n");
670 goto end;
673 iconOffset = 0;
674 if (iconData16)
675 validEntries = populate_module16_icons(iconData16, grpIconDir, iconDirEntries, icons, &iconOffset);
676 else if (hModule)
677 validEntries = populate_module_icons(hModule, grpIconDir, iconDirEntries, icons, &iconOffset);
679 if (validEntries == 0)
681 WINE_ERR("no valid icon entries\n");
682 goto end;
685 iconDir.idReserved = 0;
686 iconDir.idType = 1;
687 iconDir.idCount = validEntries;
688 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
689 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
691 WINE_ERR("error 0x%08X writing icon stream\n", hr);
692 goto end;
694 for (i = 0; i < validEntries; i++)
695 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
696 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
697 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
699 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
700 goto end;
702 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
703 if (FAILED(hr) || bytesWritten != iconOffset)
705 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
706 goto end;
708 zero.QuadPart = 0;
709 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
711 end:
712 HeapFree(GetProcessHeap(), 0, icons);
713 HeapFree(GetProcessHeap(), 0, iconDirEntries);
714 if (FAILED(hr) && stream != NULL)
716 IStream_Release(stream);
717 stream = NULL;
719 return stream;
722 static HRESULT open_module16_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
724 HANDLE hFile = INVALID_HANDLE_VALUE;
725 HANDLE hFileMapping = NULL;
726 DWORD fileSize;
727 BYTE *fileBytes = NULL;
728 IMAGE_DOS_HEADER *dosHeader;
729 IMAGE_OS2_HEADER *neHeader;
730 BYTE *rsrcTab;
731 NE_TYPEINFO *iconGroupResources;
732 NE_TYPEINFO *iconResources;
733 NE_NAMEINFO *iconDirPtr;
734 GRPICONDIR *iconDir;
735 WORD alignmentShiftCount;
736 struct IconData16 iconData16;
737 HRESULT hr = E_FAIL;
739 hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
740 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
741 if (hFile == INVALID_HANDLE_VALUE)
743 WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName), GetLastError());
744 goto end;
747 hFileMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
748 if (hFileMapping == NULL)
750 WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
751 goto end;
754 fileSize = GetFileSize(hFile, NULL);
756 fileBytes = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
757 if (fileBytes == NULL)
759 WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
760 goto end;
763 dosHeader = (IMAGE_DOS_HEADER*)fileBytes;
764 if (sizeof(IMAGE_DOS_HEADER) >= fileSize || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
766 WINE_WARN("file too small for MZ header\n");
767 goto end;
770 neHeader = (IMAGE_OS2_HEADER*)(fileBytes + dosHeader->e_lfanew);
771 if ((((BYTE*)neHeader) + sizeof(IMAGE_OS2_HEADER)) > (fileBytes + fileSize) ||
772 neHeader->ne_magic != IMAGE_OS2_SIGNATURE)
774 WINE_WARN("file too small for NE header\n");
775 goto end;
778 rsrcTab = ((BYTE*)neHeader) + neHeader->ne_rsrctab;
779 if ((rsrcTab + 2) > (fileBytes + fileSize))
781 WINE_WARN("file too small for resource table\n");
782 goto end;
785 alignmentShiftCount = *(WORD*)rsrcTab;
786 rsrcTab += 2;
787 iconGroupResources = NULL;
788 iconResources = NULL;
789 for (;;)
791 NE_TYPEINFO *neTypeInfo = (NE_TYPEINFO*)rsrcTab;
792 if ((rsrcTab + sizeof(NE_TYPEINFO)) > (fileBytes + fileSize))
794 WINE_WARN("file too small for resource table\n");
795 goto end;
797 if (neTypeInfo->type_id == 0)
798 break;
799 else if (neTypeInfo->type_id == NE_RSCTYPE_GROUP_ICON)
800 iconGroupResources = neTypeInfo;
801 else if (neTypeInfo->type_id == NE_RSCTYPE_ICON)
802 iconResources = neTypeInfo;
803 rsrcTab += sizeof(NE_TYPEINFO) + neTypeInfo->count*sizeof(NE_NAMEINFO);
805 if (iconGroupResources == NULL)
807 WINE_WARN("no group icon resource type found\n");
808 goto end;
810 if (iconResources == NULL)
812 WINE_WARN("no icon resource type found\n");
813 goto end;
816 if (nIndex >= iconGroupResources->count)
818 WINE_WARN("icon index out of range\n");
819 goto end;
822 iconDirPtr = (NE_NAMEINFO*)(((BYTE*)iconGroupResources) + sizeof(NE_TYPEINFO) + nIndex*sizeof(NE_NAMEINFO));
823 if ((((BYTE*)iconDirPtr) + sizeof(NE_NAMEINFO)) > (fileBytes + fileSize))
825 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
826 goto end;
828 iconDir = (GRPICONDIR*)(fileBytes + (iconDirPtr->offset << alignmentShiftCount));
829 if ((((BYTE*)iconDir) + sizeof(GRPICONDIR) + iconDir->idCount*sizeof(GRPICONDIRENTRY)) > (fileBytes + fileSize))
831 WINE_WARN("file too small for GRPICONDIR\n");
832 goto end;
835 iconData16.fileBytes = fileBytes;
836 iconData16.fileSize = fileSize;
837 iconData16.iconResources = iconResources;
838 iconData16.alignmentShiftCount = alignmentShiftCount;
839 *ppStream = add_module_icons_to_stream(&iconData16, NULL, iconDir);
840 if (*ppStream)
841 hr = S_OK;
843 end:
844 if (hFile != INVALID_HANDLE_VALUE)
845 CloseHandle(hFile);
846 if (hFileMapping != NULL)
847 CloseHandle(hFileMapping);
848 if (fileBytes != NULL)
849 UnmapViewOfFile(fileBytes);
850 return hr;
853 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
855 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
857 if (!sEnumRes->nIndex--)
859 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
860 return FALSE;
862 else
863 return TRUE;
866 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
868 HMODULE hModule;
869 HRSRC hResInfo;
870 HGLOBAL hResData;
871 GRPICONDIR *pIconDir;
872 ENUMRESSTRUCT sEnumRes;
873 HRESULT hr = E_FAIL;
875 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
876 if (!hModule)
878 if (GetLastError() == ERROR_BAD_EXE_FORMAT)
879 return open_module16_icon(szFileName, nIndex, ppStream);
880 else
882 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
883 wine_dbgstr_w(szFileName), GetLastError());
884 return HRESULT_FROM_WIN32(GetLastError());
888 if (nIndex < 0)
890 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
891 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
892 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
894 else
896 hResInfo=NULL;
897 sEnumRes.pResInfo = &hResInfo;
898 sEnumRes.nIndex = nIndex;
899 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
900 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
901 sEnumRes.nIndex != -1)
903 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
907 if (hResInfo)
909 if ((hResData = LoadResource(hModule, hResInfo)))
911 if ((pIconDir = LockResource(hResData)))
913 *ppStream = add_module_icons_to_stream(0, hModule, pIconDir);
914 if (*ppStream)
915 hr = S_OK;
918 FreeResource(hResData);
921 else
923 WINE_WARN("found no icon\n");
924 FreeLibrary(hModule);
925 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
928 FreeLibrary(hModule);
929 return hr;
932 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
934 ICONDIR iconDir;
935 ULONG bytesRead;
936 HRESULT hr;
938 *ppIconDirEntries = NULL;
940 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
941 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
942 (iconDir.idReserved != 0) || (iconDir.idType != 1))
944 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
945 hr = E_FAIL;
946 goto end;
948 *numEntries = iconDir.idCount;
950 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
952 hr = E_OUTOFMEMORY;
953 goto end;
955 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
956 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
958 if (SUCCEEDED(hr)) hr = E_FAIL;
959 goto end;
962 end:
963 if (FAILED(hr))
964 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
965 return hr;
968 static HRESULT write_native_icon(IStream *iconStream, const char *icon_name, LPCWSTR szFileName)
970 ICONDIRENTRY *pIconDirEntry = NULL;
971 int numEntries;
972 int nMax = 0, nMaxBits = 0;
973 int nIndex = 0;
974 int i;
975 LARGE_INTEGER position;
976 HRESULT hr;
978 hr = read_ico_direntries(iconStream, &pIconDirEntry, &numEntries);
979 if (FAILED(hr))
980 goto end;
982 for (i = 0; i < numEntries; i++)
984 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
985 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
986 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
988 nIndex = i;
989 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
990 nMaxBits = pIconDirEntry[i].wBitCount;
993 WINE_TRACE("Selected: %d\n", nIndex);
995 position.QuadPart = 0;
996 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
997 if (FAILED(hr))
998 goto end;
999 hr = convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
1001 end:
1002 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
1003 return hr;
1006 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
1008 static const WCHAR openW[] = {'o','p','e','n',0};
1009 WCHAR *extension;
1010 WCHAR *icon = NULL;
1011 WCHAR *comma;
1012 WCHAR *executable = NULL;
1013 int index = 0;
1014 char *output_path = NULL;
1015 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
1017 extension = strrchrW(szFileName, '.');
1018 if (extension == NULL)
1019 goto end;
1021 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
1022 if (icon)
1024 comma = strrchrW(icon, ',');
1025 if (comma)
1027 *comma = 0;
1028 index = atoiW(comma + 1);
1030 hr = open_icon(icon, index, FALSE, ppStream);
1032 else
1034 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, openW);
1035 if (executable)
1036 hr = open_icon(executable, 0, FALSE, ppStream);
1039 end:
1040 HeapFree(GetProcessHeap(), 0, icon);
1041 HeapFree(GetProcessHeap(), 0, executable);
1042 HeapFree(GetProcessHeap(), 0, output_path);
1043 return hr;
1046 static HRESULT open_default_icon(IStream **ppStream)
1048 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
1050 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
1053 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream)
1055 HRESULT hr;
1057 hr = open_module_icon(filename, index, ppStream);
1058 if (FAILED(hr))
1060 if(bWait && hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
1062 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1063 wine_dbgstr_w(filename));
1064 return hr;
1066 else
1068 static const WCHAR dot_icoW[] = {'.','i','c','o',0};
1069 int len = strlenW(filename);
1070 if (len >= 4 && strcmpiW(&filename[len - 4], dot_icoW) == 0)
1071 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
1074 if (FAILED(hr))
1075 hr = open_file_type_icon(filename, ppStream);
1076 if (FAILED(hr) && !bWait)
1077 hr = open_default_icon(ppStream);
1078 return hr;
1081 static char* compute_native_identifier(int exeIndex, LPCWSTR icoPathW)
1083 char* nativeIdentifier;
1084 char *icoPathA;
1085 unsigned short crc;
1086 char *basename, *ext;
1088 icoPathA = wchars_to_utf8_chars(icoPathW);
1089 if (icoPathA == NULL)
1090 return NULL;
1092 crc = crc16(icoPathA);
1093 basename = strrchr(icoPathA, '\\');
1094 if (basename == NULL)
1095 basename = icoPathA;
1096 else
1098 *basename = 0;
1099 basename++;
1101 ext = strrchr(basename, '.');
1102 if (ext)
1103 *ext = 0;
1105 nativeIdentifier = heap_printf("%04X_%s.%d", crc, basename, exeIndex);
1106 HeapFree(GetProcessHeap(), 0, icoPathA);
1107 return nativeIdentifier;
1110 #ifdef __APPLE__
1111 #define ICNS_SLOTS 6
1113 static inline int size_to_slot(int size)
1115 switch (size)
1117 case 16: return 0;
1118 case 32: return 1;
1119 case 48: return 2;
1120 case 64: return -2; /* Classic Mode */
1121 case 128: return 3;
1122 case 256: return 4;
1123 case 512: return 5;
1126 return -1;
1129 #define CLASSIC_SLOT 3
1131 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex, LPCWSTR icoPathW,
1132 const char *destFilename, char **nativeIdentifier)
1134 ICONDIRENTRY *iconDirEntries = NULL;
1135 int numEntries;
1136 struct {
1137 int index;
1138 int maxBits;
1139 BOOL scaled;
1140 } best[ICNS_SLOTS];
1141 int indexes[ICNS_SLOTS];
1142 int i;
1143 char *icnsPath = NULL;
1144 LARGE_INTEGER zero;
1145 HRESULT hr;
1147 hr = read_ico_direntries(icoStream, &iconDirEntries, &numEntries);
1148 if (FAILED(hr))
1149 goto end;
1150 for (i = 0; i < ICNS_SLOTS; i++)
1152 best[i].index = -1;
1153 best[i].maxBits = 0;
1155 for (i = 0; i < numEntries; i++)
1157 int slot;
1158 int width = iconDirEntries[i].bWidth ? iconDirEntries[i].bWidth : 256;
1159 int height = iconDirEntries[i].bHeight ? iconDirEntries[i].bHeight : 256;
1160 BOOL scaled = FALSE;
1162 WINE_TRACE("[%d]: %d x %d @ %d\n", i, width, height, iconDirEntries[i].wBitCount);
1163 if (height != width)
1164 continue;
1165 slot = size_to_slot(width);
1166 if (slot == -2)
1168 scaled = TRUE;
1169 slot = CLASSIC_SLOT;
1171 else if (slot < 0)
1172 continue;
1173 if (scaled && best[slot].maxBits && !best[slot].scaled)
1174 continue; /* don't replace unscaled with scaled */
1175 if (iconDirEntries[i].wBitCount >= best[slot].maxBits || (!scaled && best[slot].scaled))
1177 best[slot].index = i;
1178 best[slot].maxBits = iconDirEntries[i].wBitCount;
1179 best[slot].scaled = scaled;
1182 /* remove the scaled icon if a larger unscaled icon exists */
1183 if (best[CLASSIC_SLOT].scaled)
1185 for (i = CLASSIC_SLOT+1; i < ICNS_SLOTS; i++)
1186 if (best[i].index >= 0 && !best[i].scaled)
1188 best[CLASSIC_SLOT].index = -1;
1189 break;
1193 numEntries = 0;
1194 for (i = 0; i < ICNS_SLOTS; i++)
1196 if (best[i].index >= 0)
1198 indexes[numEntries] = best[i].index;
1199 numEntries++;
1203 if (destFilename)
1204 *nativeIdentifier = heap_printf("%s", destFilename);
1205 else
1206 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1207 if (*nativeIdentifier == NULL)
1209 hr = E_OUTOFMEMORY;
1210 goto end;
1212 icnsPath = heap_printf("/tmp/%s.icns", *nativeIdentifier);
1213 if (icnsPath == NULL)
1215 hr = E_OUTOFMEMORY;
1216 WINE_WARN("out of memory creating ICNS path\n");
1217 goto end;
1219 zero.QuadPart = 0;
1220 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1221 if (FAILED(hr))
1223 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
1224 goto end;
1226 hr = convert_to_native_icon(icoStream, indexes, numEntries, &CLSID_WICIcnsEncoder,
1227 icnsPath, icoPathW);
1228 if (FAILED(hr))
1230 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
1231 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
1232 goto end;
1235 end:
1236 HeapFree(GetProcessHeap(), 0, iconDirEntries);
1237 HeapFree(GetProcessHeap(), 0, icnsPath);
1238 return hr;
1240 #else
1241 static void refresh_icon_cache(const char *iconsDir)
1243 /* The icon theme spec only requires the mtime on the "toplevel"
1244 * directory (whatever that is) to be changed for a refresh,
1245 * but on GNOME you have to create a file in that directory
1246 * instead. Creating a file also works on KDE, Xfce and LXDE.
1248 char *filename = heap_printf("%s/.wine-refresh-XXXXXX", iconsDir);
1249 if (filename != NULL)
1251 int fd = mkstemps(filename, 0);
1252 if (fd >= 0)
1254 close(fd);
1255 unlink(filename);
1257 HeapFree(GetProcessHeap(), 0, filename);
1261 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex, LPCWSTR icoPathW,
1262 const char *destFilename, char **nativeIdentifier)
1264 ICONDIRENTRY *iconDirEntries = NULL;
1265 int numEntries;
1266 int i;
1267 char *iconsDir = NULL;
1268 HRESULT hr = S_OK;
1269 LARGE_INTEGER zero;
1271 hr = read_ico_direntries(icoStream, &iconDirEntries, &numEntries);
1272 if (FAILED(hr))
1273 goto end;
1275 if (destFilename)
1276 *nativeIdentifier = heap_printf("%s", destFilename);
1277 else
1278 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1279 if (*nativeIdentifier == NULL)
1281 hr = E_OUTOFMEMORY;
1282 goto end;
1284 iconsDir = heap_printf("%s/icons/hicolor", xdg_data_dir);
1285 if (iconsDir == NULL)
1287 hr = E_OUTOFMEMORY;
1288 goto end;
1291 for (i = 0; i < numEntries; i++)
1293 int bestIndex = i;
1294 int j;
1295 BOOLEAN duplicate = FALSE;
1296 int w, h;
1297 char *iconDir = NULL;
1298 char *pngPath = NULL;
1300 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
1301 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
1303 for (j = 0; j < i; j++)
1305 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1306 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
1308 duplicate = TRUE;
1309 break;
1312 if (duplicate)
1313 continue;
1314 for (j = i + 1; j < numEntries; j++)
1316 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1317 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1318 iconDirEntries[j].wBitCount >= iconDirEntries[bestIndex].wBitCount)
1320 bestIndex = j;
1323 WINE_TRACE("Selected: %d\n", bestIndex);
1325 w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
1326 h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
1327 iconDir = heap_printf("%s/%dx%d/apps", iconsDir, w, h);
1328 if (iconDir == NULL)
1330 hr = E_OUTOFMEMORY;
1331 goto endloop;
1333 create_directories(iconDir);
1334 pngPath = heap_printf("%s/%s.png", iconDir, *nativeIdentifier);
1335 if (pngPath == NULL)
1337 hr = E_OUTOFMEMORY;
1338 goto endloop;
1340 zero.QuadPart = 0;
1341 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1342 if (FAILED(hr))
1343 goto endloop;
1344 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
1345 pngPath, icoPathW);
1347 endloop:
1348 HeapFree(GetProcessHeap(), 0, iconDir);
1349 HeapFree(GetProcessHeap(), 0, pngPath);
1351 refresh_icon_cache(iconsDir);
1353 end:
1354 HeapFree(GetProcessHeap(), 0, iconDirEntries);
1355 HeapFree(GetProcessHeap(), 0, iconsDir);
1356 return hr;
1358 #endif /* defined(__APPLE__) */
1360 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1361 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
1363 IStream *stream = NULL;
1364 HRESULT hr;
1365 char *nativeIdentifier = NULL;
1367 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
1369 hr = open_icon(icoPathW, index, bWait, &stream);
1370 if (FAILED(hr))
1372 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
1373 goto end;
1375 hr = platform_write_icon(stream, index, icoPathW, destFilename, &nativeIdentifier);
1376 if (FAILED(hr))
1377 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
1379 end:
1380 if (stream)
1381 IStream_Release(stream);
1382 if (FAILED(hr))
1384 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
1385 nativeIdentifier = NULL;
1387 return nativeIdentifier;
1390 static HKEY open_menus_reg_key(void)
1392 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1393 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1394 HKEY assocKey;
1395 DWORD ret;
1396 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1397 if (ret == ERROR_SUCCESS)
1398 return assocKey;
1399 SetLastError(ret);
1400 return NULL;
1403 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1405 WCHAR *unix_fileW;
1406 WCHAR *windows_fileW;
1407 INT size;
1408 DWORD ret;
1410 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1411 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1412 if (unix_fileW)
1414 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1415 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1416 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1417 if (windows_fileW)
1419 HKEY hkey;
1420 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1421 hkey = open_menus_reg_key();
1422 if (hkey)
1424 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1425 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1426 RegCloseKey(hkey);
1428 else
1429 ret = GetLastError();
1430 HeapFree(GetProcessHeap(), 0, windows_fileW);
1432 else
1433 ret = ERROR_NOT_ENOUGH_MEMORY;
1434 HeapFree(GetProcessHeap(), 0, unix_fileW);
1436 else
1437 ret = ERROR_NOT_ENOUGH_MEMORY;
1438 return ret;
1441 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1442 const char *path, const char *args, const char *descr,
1443 const char *workdir, const char *icon)
1445 FILE *file;
1447 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1448 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1449 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1451 file = fopen(location, "w");
1452 if (file == NULL)
1453 return FALSE;
1455 fprintf(file, "[Desktop Entry]\n");
1456 fprintf(file, "Name=%s\n", linkname);
1457 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1458 wine_get_config_dir(), path, args);
1459 fprintf(file, "Type=Application\n");
1460 fprintf(file, "StartupNotify=true\n");
1461 if (descr && lstrlenA(descr))
1462 fprintf(file, "Comment=%s\n", descr);
1463 if (workdir && lstrlenA(workdir))
1464 fprintf(file, "Path=%s\n", workdir);
1465 if (icon && lstrlenA(icon))
1466 fprintf(file, "Icon=%s\n", icon);
1468 fclose(file);
1470 if (unix_link)
1472 DWORD ret = register_menus_entry(location, unix_link);
1473 if (ret != ERROR_SUCCESS)
1474 return FALSE;
1477 return TRUE;
1480 static BOOL write_directory_entry(const char *directory, const char *location)
1482 FILE *file;
1484 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1486 file = fopen(location, "w");
1487 if (file == NULL)
1488 return FALSE;
1490 fprintf(file, "[Desktop Entry]\n");
1491 fprintf(file, "Type=Directory\n");
1492 if (strcmp(directory, "wine") == 0)
1494 fprintf(file, "Name=Wine\n");
1495 fprintf(file, "Icon=wine\n");
1497 else
1499 fprintf(file, "Name=%s\n", directory);
1500 fprintf(file, "Icon=folder\n");
1503 fclose(file);
1504 return TRUE;
1507 static BOOL write_menu_file(const char *unix_link, const char *filename)
1509 char *tempfilename;
1510 FILE *tempfile = NULL;
1511 char *lastEntry;
1512 char *name = NULL;
1513 char *menuPath = NULL;
1514 int i;
1515 int count = 0;
1516 BOOL ret = FALSE;
1518 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1520 while (1)
1522 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1523 if (tempfilename)
1525 int tempfd = mkstemps(tempfilename, 0);
1526 if (tempfd >= 0)
1528 tempfile = fdopen(tempfd, "w");
1529 if (tempfile)
1530 break;
1531 close(tempfd);
1532 goto end;
1534 else if (errno == EEXIST)
1536 HeapFree(GetProcessHeap(), 0, tempfilename);
1537 continue;
1539 HeapFree(GetProcessHeap(), 0, tempfilename);
1541 return FALSE;
1544 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1545 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1546 fprintf(tempfile, "<Menu>\n");
1547 fprintf(tempfile, " <Name>Applications</Name>\n");
1549 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1550 if (name == NULL) goto end;
1551 lastEntry = name;
1552 for (i = 0; filename[i]; i++)
1554 name[i] = filename[i];
1555 if (filename[i] == '/')
1557 char *dir_file_name;
1558 struct stat st;
1559 name[i] = 0;
1560 fprintf(tempfile, " <Menu>\n");
1561 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1562 write_xml_text(tempfile, name);
1563 fprintf(tempfile, "</Name>\n");
1564 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1565 write_xml_text(tempfile, name);
1566 fprintf(tempfile, ".directory</Directory>\n");
1567 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1568 xdg_data_dir, count ? "" : "wine-", name);
1569 if (dir_file_name)
1571 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1572 write_directory_entry(lastEntry, dir_file_name);
1573 HeapFree(GetProcessHeap(), 0, dir_file_name);
1575 name[i] = '-';
1576 lastEntry = &name[i+1];
1577 ++count;
1580 name[i] = 0;
1582 fprintf(tempfile, " <Include>\n");
1583 fprintf(tempfile, " <Filename>");
1584 write_xml_text(tempfile, name);
1585 fprintf(tempfile, "</Filename>\n");
1586 fprintf(tempfile, " </Include>\n");
1587 for (i = 0; i < count; i++)
1588 fprintf(tempfile, " </Menu>\n");
1589 fprintf(tempfile, "</Menu>\n");
1591 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1592 if (menuPath == NULL) goto end;
1593 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1594 ret = TRUE;
1596 end:
1597 if (tempfile)
1598 fclose(tempfile);
1599 if (ret)
1600 ret = (rename(tempfilename, menuPath) == 0);
1601 if (!ret && tempfilename)
1602 remove(tempfilename);
1603 HeapFree(GetProcessHeap(), 0, tempfilename);
1604 if (ret)
1605 register_menus_entry(menuPath, unix_link);
1606 HeapFree(GetProcessHeap(), 0, name);
1607 HeapFree(GetProcessHeap(), 0, menuPath);
1608 return ret;
1611 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1612 const char *descr, const char *workdir, const char *icon)
1614 const char *linkname;
1615 char *desktopPath = NULL;
1616 char *desktopDir;
1617 char *filename = NULL;
1618 BOOL ret = TRUE;
1620 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1621 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1622 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1624 linkname = strrchr(link, '/');
1625 if (linkname == NULL)
1626 linkname = link;
1627 else
1628 ++linkname;
1630 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1631 if (!desktopPath)
1633 WINE_WARN("out of memory creating menu entry\n");
1634 ret = FALSE;
1635 goto end;
1637 desktopDir = strrchr(desktopPath, '/');
1638 *desktopDir = 0;
1639 if (!create_directories(desktopPath))
1641 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1642 ret = FALSE;
1643 goto end;
1645 *desktopDir = '/';
1646 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1648 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1649 ret = FALSE;
1650 goto end;
1653 filename = heap_printf("wine/%s.desktop", link);
1654 if (!filename || !write_menu_file(unix_link, filename))
1656 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1657 ret = FALSE;
1660 end:
1661 HeapFree(GetProcessHeap(), 0, desktopPath);
1662 HeapFree(GetProcessHeap(), 0, filename);
1663 return ret;
1666 /* This escapes reserved characters in .desktop files' Exec keys. */
1667 static LPSTR escape(LPCWSTR arg)
1669 int i, j;
1670 WCHAR *escaped_string;
1671 char *utf8_string;
1673 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1674 if (escaped_string == NULL) return NULL;
1675 for (i = j = 0; arg[i]; i++)
1677 switch (arg[i])
1679 case '\\':
1680 escaped_string[j++] = '\\';
1681 escaped_string[j++] = '\\';
1682 escaped_string[j++] = '\\';
1683 escaped_string[j++] = '\\';
1684 break;
1685 case ' ':
1686 case '\t':
1687 case '\n':
1688 case '"':
1689 case '\'':
1690 case '>':
1691 case '<':
1692 case '~':
1693 case '|':
1694 case '&':
1695 case ';':
1696 case '$':
1697 case '*':
1698 case '?':
1699 case '#':
1700 case '(':
1701 case ')':
1702 case '`':
1703 escaped_string[j++] = '\\';
1704 escaped_string[j++] = '\\';
1705 /* fall through */
1706 default:
1707 escaped_string[j++] = arg[i];
1708 break;
1711 escaped_string[j] = 0;
1713 utf8_string = wchars_to_utf8_chars(escaped_string);
1714 if (utf8_string == NULL)
1716 WINE_ERR("out of memory\n");
1717 goto end;
1720 end:
1721 HeapFree(GetProcessHeap(), 0, escaped_string);
1722 return utf8_string;
1725 /* Return a heap-allocated copy of the unix format difference between the two
1726 * Windows-format paths.
1727 * locn is the owning location
1728 * link is within locn
1730 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1732 char *unix_locn, *unix_link;
1733 char *relative = NULL;
1735 unix_locn = wine_get_unix_file_name(locn);
1736 unix_link = wine_get_unix_file_name(link);
1737 if (unix_locn && unix_link)
1739 size_t len_unix_locn, len_unix_link;
1740 len_unix_locn = strlen (unix_locn);
1741 len_unix_link = strlen (unix_link);
1742 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1744 size_t len_rel;
1745 char *p = strrchr (unix_link + len_unix_locn, '/');
1746 p = strrchr (p, '.');
1747 if (p)
1749 *p = '\0';
1750 len_unix_link = p - unix_link;
1752 len_rel = len_unix_link - len_unix_locn;
1753 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1754 if (relative)
1756 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1760 if (!relative)
1761 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1762 HeapFree(GetProcessHeap(), 0, unix_locn);
1763 HeapFree(GetProcessHeap(), 0, unix_link);
1764 return relative;
1767 /***********************************************************************
1769 * GetLinkLocation
1771 * returns TRUE if successful
1772 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1773 * *relative will contain the address of a heap-allocated copy of the portion
1774 * of the filename that is within the specified location, in unix form
1776 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1778 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1779 DWORD len, i, r, filelen;
1780 const DWORD locations[] = {
1781 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1782 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1783 CSIDL_COMMON_STARTMENU };
1785 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1786 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1787 if (filelen==0 || filelen>MAX_PATH)
1788 return FALSE;
1790 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1792 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1793 * expand or our hardcoded list won't match.
1795 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1796 if (filelen==0 || filelen>MAX_PATH)
1797 return FALSE;
1799 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1801 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1803 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1804 continue;
1806 len = lstrlenW(buffer);
1807 if (len >= MAX_PATH)
1808 continue; /* We've just trashed memory! Hopefully we are OK */
1810 if (len > filelen || filename[len]!='\\')
1811 continue;
1812 /* do a lstrcmpinW */
1813 filename[len] = 0;
1814 r = lstrcmpiW( filename, buffer );
1815 filename[len] = '\\';
1816 if ( r )
1817 continue;
1819 /* return the remainder of the string and link type */
1820 *loc = locations[i];
1821 *relative = relative_path (filename, buffer);
1822 return (*relative != NULL);
1825 return FALSE;
1828 /* gets the target path directly or through MSI */
1829 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1830 LPWSTR szArgs, DWORD argsSize)
1832 IShellLinkDataList *dl = NULL;
1833 EXP_DARWIN_LINK *dar = NULL;
1834 HRESULT hr;
1836 szPath[0] = 0;
1837 szArgs[0] = 0;
1839 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1840 if (hr == S_OK && szPath[0])
1842 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1843 return hr;
1846 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1847 if (FAILED(hr))
1848 return hr;
1850 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1851 if (SUCCEEDED(hr))
1853 WCHAR* szCmdline;
1854 DWORD cmdSize;
1856 cmdSize=0;
1857 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1858 if (hr == ERROR_SUCCESS)
1860 cmdSize++;
1861 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1862 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1863 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1864 if (hr == ERROR_SUCCESS)
1866 WCHAR *s, *d;
1867 int bcount = 0;
1868 BOOL in_quotes = FALSE;
1870 /* Extract the application path */
1871 s=szCmdline;
1872 d=szPath;
1873 while (*s)
1875 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1877 /* skip the remaining spaces */
1878 do {
1879 s++;
1880 } while (*s==0x0009 || *s==0x0020);
1881 break;
1883 else if (*s==0x005c)
1885 /* '\\' */
1886 *d++=*s++;
1887 bcount++;
1889 else if (*s==0x0022)
1891 /* '"' */
1892 if ((bcount & 1)==0)
1894 /* Preceded by an even number of '\', this is
1895 * half that number of '\', plus a quote which
1896 * we erase.
1898 d-=bcount/2;
1899 in_quotes=!in_quotes;
1900 s++;
1902 else
1904 /* Preceded by an odd number of '\', this is
1905 * half that number of '\' followed by a '"'
1907 d=d-bcount/2-1;
1908 *d++='"';
1909 s++;
1911 bcount=0;
1913 else
1915 /* a regular character */
1916 *d++=*s++;
1917 bcount=0;
1919 if ((d-szPath) == pathSize)
1921 /* Keep processing the path till we get to the
1922 * arguments, but 'stand still'
1924 d--;
1927 /* Close the application path */
1928 *d=0;
1930 lstrcpynW(szArgs, s, argsSize);
1932 HeapFree( GetProcessHeap(), 0, szCmdline );
1934 LocalFree( dar );
1937 IShellLinkDataList_Release( dl );
1938 return hr;
1941 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1943 HRESULT hr;
1944 WCHAR *value = NULL;
1945 DWORD size = 0;
1946 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1947 if (SUCCEEDED(hr))
1949 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1950 if (value)
1952 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1953 if (FAILED(hr))
1955 HeapFree(GetProcessHeap(), 0, value);
1956 value = NULL;
1960 return value;
1963 static char *slashes_to_minuses(const char *string)
1965 int i;
1966 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1967 if (ret)
1969 for (i = 0; string[i]; i++)
1971 if (string[i] == '/')
1972 ret[i] = '-';
1973 else
1974 ret[i] = string[i];
1976 ret[i] = 0;
1977 return ret;
1979 return NULL;
1982 static BOOL next_line(FILE *file, char **line, int *size)
1984 int pos = 0;
1985 char *cr;
1986 if (*line == NULL)
1988 *size = 4096;
1989 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1991 while (*line != NULL)
1993 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1995 HeapFree(GetProcessHeap(), 0, *line);
1996 *line = NULL;
1997 if (feof(file))
1998 return TRUE;
1999 return FALSE;
2001 pos = strlen(*line);
2002 cr = strchr(*line, '\n');
2003 if (cr == NULL)
2005 char *line2;
2006 (*size) *= 2;
2007 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
2008 if (line2)
2009 *line = line2;
2010 else
2012 HeapFree(GetProcessHeap(), 0, *line);
2013 *line = NULL;
2016 else
2018 *cr = 0;
2019 return TRUE;
2022 return FALSE;
2025 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
2027 char *globs_filename = NULL;
2028 BOOL ret = TRUE;
2029 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
2030 if (globs_filename)
2032 FILE *globs_file = fopen(globs_filename, "r");
2033 if (globs_file) /* doesn't have to exist */
2035 char *line = NULL;
2036 int size = 0;
2037 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
2039 char *pos;
2040 struct xdg_mime_type *mime_type_entry = NULL;
2041 if (line[0] != '#' && (pos = strchr(line, ':')))
2043 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
2044 if (mime_type_entry)
2046 *pos = 0;
2047 mime_type_entry->mimeType = strdupA(line);
2048 mime_type_entry->glob = strdupA(pos + 1);
2049 mime_type_entry->lower_glob = strdupA(pos + 1);
2050 if (mime_type_entry->lower_glob)
2052 char *l;
2053 for (l = mime_type_entry->lower_glob; *l; l++)
2054 *l = tolower(*l);
2056 if (mime_type_entry->mimeType && mime_type_entry->glob && mime_type_entry->lower_glob)
2057 list_add_tail(mime_types, &mime_type_entry->entry);
2058 else
2060 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2061 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2062 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2063 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2064 ret = FALSE;
2067 else
2068 ret = FALSE;
2071 HeapFree(GetProcessHeap(), 0, line);
2072 fclose(globs_file);
2074 HeapFree(GetProcessHeap(), 0, globs_filename);
2076 else
2077 ret = FALSE;
2078 return ret;
2081 static void free_native_mime_types(struct list *native_mime_types)
2083 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
2085 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
2087 list_remove(&mime_type_entry->entry);
2088 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2089 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2090 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2091 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2093 HeapFree(GetProcessHeap(), 0, native_mime_types);
2096 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
2098 char *xdg_data_dirs;
2099 BOOL ret;
2101 *mime_types = NULL;
2103 xdg_data_dirs = getenv("XDG_DATA_DIRS");
2104 if (xdg_data_dirs == NULL)
2105 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
2106 else
2107 xdg_data_dirs = strdupA(xdg_data_dirs);
2109 if (xdg_data_dirs)
2111 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
2112 if (*mime_types)
2114 const char *begin;
2115 char *end;
2117 list_init(*mime_types);
2118 ret = add_mimes(xdg_data_home, *mime_types);
2119 if (ret)
2121 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
2123 *end = '\0';
2124 ret = add_mimes(begin, *mime_types);
2125 *end = ':';
2126 if (!ret)
2127 break;
2129 if (ret)
2130 ret = add_mimes(begin, *mime_types);
2133 else
2134 ret = FALSE;
2135 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
2137 else
2138 ret = FALSE;
2139 if (!ret && *mime_types)
2141 free_native_mime_types(*mime_types);
2142 *mime_types = NULL;
2144 return ret;
2147 static BOOL match_glob(struct list *native_mime_types, const char *extension,
2148 int ignoreGlobCase, char **match)
2150 #ifdef HAVE_FNMATCH
2151 struct xdg_mime_type *mime_type_entry;
2152 int matchLength = 0;
2154 *match = NULL;
2156 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
2158 const char *glob = ignoreGlobCase ? mime_type_entry->lower_glob : mime_type_entry->glob;
2159 if (fnmatch(glob, extension, 0) == 0)
2161 if (*match == NULL || matchLength < strlen(glob))
2163 *match = mime_type_entry->mimeType;
2164 matchLength = strlen(glob);
2169 if (*match != NULL)
2171 *match = strdupA(*match);
2172 if (*match == NULL)
2173 return FALSE;
2175 #else
2176 *match = NULL;
2177 #endif
2178 return TRUE;
2181 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
2182 const char *extensionA,
2183 LPCWSTR extensionW,
2184 char **mime_type)
2186 WCHAR *lower_extensionW;
2187 INT len;
2188 BOOL ret = match_glob(native_mime_types, extensionA, 0, mime_type);
2189 if (ret == FALSE || *mime_type != NULL)
2190 return ret;
2191 len = strlenW(extensionW);
2192 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
2193 if (lower_extensionW)
2195 char *lower_extensionA;
2196 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
2197 strlwrW(lower_extensionW);
2198 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
2199 if (lower_extensionA)
2201 ret = match_glob(native_mime_types, lower_extensionA, 1, mime_type);
2202 HeapFree(GetProcessHeap(), 0, lower_extensionA);
2204 else
2206 ret = FALSE;
2207 WINE_FIXME("out of memory\n");
2209 HeapFree(GetProcessHeap(), 0, lower_extensionW);
2211 else
2213 ret = FALSE;
2214 WINE_FIXME("out of memory\n");
2216 return ret;
2219 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
2221 DWORD size;
2222 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
2224 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
2225 if (ret)
2227 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
2228 return ret;
2230 HeapFree(GetProcessHeap(), 0, ret);
2232 return NULL;
2235 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
2237 WCHAR *valW = reg_get_valW(key, subkey, name);
2238 if (valW)
2240 char *val = wchars_to_utf8_chars(valW);
2241 HeapFree(GetProcessHeap(), 0, valW);
2242 return val;
2244 return NULL;
2247 static HKEY open_associations_reg_key(void)
2249 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
2250 '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};
2251 HKEY assocKey;
2252 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
2253 return assocKey;
2254 return NULL;
2257 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
2258 LPCSTR appName, LPCSTR openWithIcon)
2260 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2261 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2262 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2263 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2264 HKEY assocKey;
2265 BOOL ret;
2267 if ((assocKey = open_associations_reg_key()))
2269 CHAR *valueA;
2270 WCHAR *value;
2272 ret = FALSE;
2274 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
2275 if (!valueA || lstrcmpA(valueA, mimeType))
2276 ret = TRUE;
2277 HeapFree(GetProcessHeap(), 0, valueA);
2279 value = reg_get_valW(assocKey, extensionW, ProgIDW);
2280 if (!value || strcmpW(value, progId))
2281 ret = TRUE;
2282 HeapFree(GetProcessHeap(), 0, value);
2284 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2285 if (!valueA || lstrcmpA(valueA, appName))
2286 ret = TRUE;
2287 HeapFree(GetProcessHeap(), 0, valueA);
2289 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
2290 if ((openWithIcon && !valueA) ||
2291 (!openWithIcon && valueA) ||
2292 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
2293 ret = TRUE;
2294 HeapFree(GetProcessHeap(), 0, valueA);
2296 RegCloseKey(assocKey);
2298 else
2300 WINE_ERR("error opening associations registry key\n");
2301 ret = FALSE;
2303 return ret;
2306 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2307 LPCSTR appName, LPCSTR desktopFile, LPCSTR openWithIcon)
2309 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2310 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2311 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2312 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2313 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2314 HKEY assocKey = NULL;
2315 HKEY subkey = NULL;
2316 WCHAR *mimeTypeW = NULL;
2317 WCHAR *appNameW = NULL;
2318 WCHAR *desktopFileW = NULL;
2319 WCHAR *openWithIconW = NULL;
2321 assocKey = open_associations_reg_key();
2322 if (assocKey == NULL)
2324 WINE_ERR("could not open file associations key\n");
2325 goto done;
2328 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2330 WINE_ERR("could not create extension subkey\n");
2331 goto done;
2334 mimeTypeW = utf8_chars_to_wchars(mimeType);
2335 if (mimeTypeW == NULL)
2337 WINE_ERR("out of memory\n");
2338 goto done;
2341 appNameW = utf8_chars_to_wchars(appName);
2342 if (appNameW == NULL)
2344 WINE_ERR("out of memory\n");
2345 goto done;
2348 desktopFileW = utf8_chars_to_wchars(desktopFile);
2349 if (desktopFileW == NULL)
2351 WINE_ERR("out of memory\n");
2352 goto done;
2355 if (openWithIcon)
2357 openWithIconW = utf8_chars_to_wchars(openWithIcon);
2358 if (openWithIconW == NULL)
2360 WINE_ERR("out of memory\n");
2361 goto done;
2365 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2366 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2367 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2368 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2369 if (openWithIcon)
2370 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
2371 else
2372 RegDeleteValueW(subkey, OpenWithIconW);
2374 done:
2375 RegCloseKey(assocKey);
2376 RegCloseKey(subkey);
2377 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2378 HeapFree(GetProcessHeap(), 0, appNameW);
2379 HeapFree(GetProcessHeap(), 0, desktopFileW);
2380 HeapFree(GetProcessHeap(), 0, openWithIconW);
2383 static BOOL cleanup_associations(void)
2385 static const WCHAR openW[] = {'o','p','e','n',0};
2386 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2387 HKEY assocKey;
2388 BOOL hasChanged = FALSE;
2389 if ((assocKey = open_associations_reg_key()))
2391 int i;
2392 BOOL done = FALSE;
2393 for (i = 0; !done;)
2395 WCHAR *extensionW = NULL;
2396 DWORD size = 1024;
2397 LSTATUS ret;
2401 HeapFree(GetProcessHeap(), 0, extensionW);
2402 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2403 if (extensionW == NULL)
2405 WINE_ERR("out of memory\n");
2406 ret = ERROR_OUTOFMEMORY;
2407 break;
2409 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2410 size *= 2;
2411 } while (ret == ERROR_MORE_DATA);
2413 if (ret == ERROR_SUCCESS)
2415 WCHAR *command;
2416 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2417 if (command == NULL)
2419 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2420 if (desktopFile)
2422 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2423 remove(desktopFile);
2425 RegDeleteKeyW(assocKey, extensionW);
2426 hasChanged = TRUE;
2427 HeapFree(GetProcessHeap(), 0, desktopFile);
2429 else
2430 i++;
2431 HeapFree(GetProcessHeap(), 0, command);
2433 else
2435 if (ret != ERROR_NO_MORE_ITEMS)
2436 WINE_ERR("error %d while reading registry\n", ret);
2437 done = TRUE;
2439 HeapFree(GetProcessHeap(), 0, extensionW);
2441 RegCloseKey(assocKey);
2443 else
2444 WINE_ERR("could not open file associations key\n");
2445 return hasChanged;
2448 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2449 const char *mime_type, const char *comment)
2451 BOOL ret = FALSE;
2452 char *filename;
2454 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2455 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2457 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2458 if (filename)
2460 FILE *packageFile = fopen(filename, "w");
2461 if (packageFile)
2463 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2464 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2465 fprintf(packageFile, " <mime-type type=\"");
2466 write_xml_text(packageFile, mime_type);
2467 fprintf(packageFile, "\">\n");
2468 fprintf(packageFile, " <glob pattern=\"*");
2469 write_xml_text(packageFile, dot_extension);
2470 fprintf(packageFile, "\"/>\n");
2471 if (comment)
2473 fprintf(packageFile, " <comment>");
2474 write_xml_text(packageFile, comment);
2475 fprintf(packageFile, "</comment>\n");
2477 fprintf(packageFile, " </mime-type>\n");
2478 fprintf(packageFile, "</mime-info>\n");
2479 ret = TRUE;
2480 fclose(packageFile);
2482 else
2483 WINE_ERR("error writing file %s\n", filename);
2484 HeapFree(GetProcessHeap(), 0, filename);
2486 else
2487 WINE_ERR("out of memory\n");
2488 return ret;
2491 static BOOL is_extension_blacklisted(LPCWSTR extension)
2493 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2494 static const WCHAR comW[] = {'.','c','o','m',0};
2495 static const WCHAR exeW[] = {'.','e','x','e',0};
2496 static const WCHAR msiW[] = {'.','m','s','i',0};
2498 if (!strcmpiW(extension, comW) ||
2499 !strcmpiW(extension, exeW) ||
2500 !strcmpiW(extension, msiW))
2501 return TRUE;
2502 return FALSE;
2505 static const char* get_special_mime_type(LPCWSTR extension)
2507 static const WCHAR lnkW[] = {'.','l','n','k',0};
2508 if (!strcmpiW(extension, lnkW))
2509 return "application/x-ms-shortcut";
2510 return NULL;
2513 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2514 const char *friendlyAppName, const char *mimeType,
2515 const char *progId, const char *openWithIcon)
2517 BOOL ret = FALSE;
2518 FILE *desktop;
2520 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2521 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2522 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2524 desktop = fopen(desktopPath, "w");
2525 if (desktop)
2527 fprintf(desktop, "[Desktop Entry]\n");
2528 fprintf(desktop, "Type=Application\n");
2529 fprintf(desktop, "Name=%s\n", friendlyAppName);
2530 fprintf(desktop, "MimeType=%s;\n", mimeType);
2531 fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId);
2532 fprintf(desktop, "NoDisplay=true\n");
2533 fprintf(desktop, "StartupNotify=true\n");
2534 if (openWithIcon)
2535 fprintf(desktop, "Icon=%s\n", openWithIcon);
2536 ret = TRUE;
2537 fclose(desktop);
2539 else
2540 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2541 return ret;
2544 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2546 static const WCHAR openW[] = {'o','p','e','n',0};
2547 struct wine_rb_tree mimeProgidTree;
2548 struct list *nativeMimeTypes = NULL;
2549 LSTATUS ret = 0;
2550 int i;
2551 BOOL hasChanged = FALSE;
2553 if (wine_rb_init(&mimeProgidTree, &winemenubuilder_rb_functions))
2555 WINE_ERR("wine_rb_init failed\n");
2556 return FALSE;
2558 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2560 WINE_ERR("could not build native MIME types\n");
2561 return FALSE;
2564 for (i = 0; ; i++)
2566 WCHAR *extensionW = NULL;
2567 DWORD size = 1024;
2571 HeapFree(GetProcessHeap(), 0, extensionW);
2572 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2573 if (extensionW == NULL)
2575 WINE_ERR("out of memory\n");
2576 ret = ERROR_OUTOFMEMORY;
2577 break;
2579 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2580 size *= 2;
2581 } while (ret == ERROR_MORE_DATA);
2583 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2585 char *extensionA = NULL;
2586 WCHAR *commandW = NULL;
2587 WCHAR *executableW = NULL;
2588 char *openWithIconA = NULL;
2589 WCHAR *friendlyDocNameW = NULL;
2590 char *friendlyDocNameA = NULL;
2591 WCHAR *iconW = NULL;
2592 char *iconA = NULL;
2593 WCHAR *contentTypeW = NULL;
2594 char *mimeTypeA = NULL;
2595 WCHAR *friendlyAppNameW = NULL;
2596 char *friendlyAppNameA = NULL;
2597 WCHAR *progIdW = NULL;
2598 char *progIdA = NULL;
2599 char *mimeProgId = NULL;
2601 extensionA = wchars_to_utf8_chars(strlwrW(extensionW));
2602 if (extensionA == NULL)
2604 WINE_ERR("out of memory\n");
2605 goto end;
2608 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2609 if (friendlyDocNameW)
2611 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2612 if (friendlyDocNameA == NULL)
2614 WINE_ERR("out of memory\n");
2615 goto end;
2619 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2621 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2622 if (contentTypeW)
2623 strlwrW(contentTypeW);
2625 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2626 goto end;
2628 if (mimeTypeA == NULL)
2630 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2631 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2632 else if ((get_special_mime_type(extensionW)))
2633 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2634 else
2635 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2637 if (mimeTypeA != NULL)
2639 /* GNOME seems to ignore the <icon> tag in MIME packages,
2640 * and the default name is more intuitive anyway.
2642 if (iconW)
2644 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2645 if (flattened_mime)
2647 int index = 0;
2648 WCHAR *comma = strrchrW(iconW, ',');
2649 if (comma)
2651 *comma = 0;
2652 index = atoiW(comma + 1);
2654 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2655 HeapFree(GetProcessHeap(), 0, flattened_mime);
2659 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2660 hasChanged = TRUE;
2662 else
2664 WINE_FIXME("out of memory\n");
2665 goto end;
2669 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2670 if (commandW == NULL)
2671 /* no command => no application is associated */
2672 goto end;
2674 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2675 if (executableW)
2676 openWithIconA = extract_icon(executableW, 0, NULL, FALSE);
2678 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, openW);
2679 if (friendlyAppNameW)
2681 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2682 if (friendlyAppNameA == NULL)
2684 WINE_ERR("out of memory\n");
2685 goto end;
2688 else
2690 friendlyAppNameA = heap_printf("A Wine application");
2691 if (friendlyAppNameA == NULL)
2693 WINE_ERR("out of memory\n");
2694 goto end;
2698 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2699 if (progIdW)
2701 progIdA = escape(progIdW);
2702 if (progIdA == NULL)
2704 WINE_ERR("out of memory\n");
2705 goto end;
2708 else
2709 goto end; /* no progID => not a file type association */
2711 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2712 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2713 if (mimeProgId)
2715 struct rb_string_entry *entry;
2716 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2718 HeapFree(GetProcessHeap(), 0, mimeProgId);
2719 goto end;
2721 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2722 if (!entry)
2724 WINE_ERR("out of memory allocating rb_string_entry\n");
2725 goto end;
2727 entry->string = mimeProgId;
2728 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2730 WINE_ERR("error updating rb tree\n");
2731 goto end;
2735 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, openWithIconA))
2737 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2738 if (desktopPath)
2740 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2742 hasChanged = TRUE;
2743 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, desktopPath, openWithIconA);
2745 HeapFree(GetProcessHeap(), 0, desktopPath);
2749 end:
2750 HeapFree(GetProcessHeap(), 0, extensionA);
2751 HeapFree(GetProcessHeap(), 0, commandW);
2752 HeapFree(GetProcessHeap(), 0, executableW);
2753 HeapFree(GetProcessHeap(), 0, openWithIconA);
2754 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2755 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2756 HeapFree(GetProcessHeap(), 0, iconW);
2757 HeapFree(GetProcessHeap(), 0, iconA);
2758 HeapFree(GetProcessHeap(), 0, contentTypeW);
2759 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2760 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2761 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2762 HeapFree(GetProcessHeap(), 0, progIdW);
2763 HeapFree(GetProcessHeap(), 0, progIdA);
2765 HeapFree(GetProcessHeap(), 0, extensionW);
2766 if (ret != ERROR_SUCCESS)
2767 break;
2770 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2771 free_native_mime_types(nativeMimeTypes);
2772 return hasChanged;
2775 static char *get_start_exe_path(void)
2777 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2778 '\\','s','t','a','r','t','.','e','x','e',0};
2779 WCHAR start_path[MAX_PATH];
2780 GetWindowsDirectoryW(start_path, MAX_PATH);
2781 lstrcatW(start_path, startW);
2782 return escape(start_path);
2785 static char* escape_unix_link_arg(LPCSTR unix_link)
2787 char *ret = NULL;
2788 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2789 if (unix_linkW)
2791 char *escaped_lnk = escape(unix_linkW);
2792 if (escaped_lnk)
2794 ret = heap_printf("/Unix %s", escaped_lnk);
2795 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2797 HeapFree(GetProcessHeap(), 0, unix_linkW);
2799 return ret;
2802 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2804 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2805 '\\','s','t','a','r','t','.','e','x','e',0};
2806 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2807 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2808 WCHAR szTmp[INFOTIPSIZE];
2809 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2810 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2811 int iIconId = 0, r = -1;
2812 DWORD csidl = -1;
2813 HANDLE hsem = NULL;
2814 char *unix_link = NULL;
2815 char *start_path = NULL;
2817 if ( !link )
2819 WINE_ERR("Link name is null\n");
2820 return FALSE;
2823 if( !GetLinkLocation( link, &csidl, &link_name ) )
2825 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2826 return TRUE;
2828 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2830 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2831 return TRUE;
2833 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2835 szTmp[0] = 0;
2836 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2837 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2838 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2840 szTmp[0] = 0;
2841 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2842 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2843 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2845 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2846 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2847 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2848 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2850 szTmp[0] = 0;
2851 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2852 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2853 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2855 if( !szPath[0] )
2857 LPITEMIDLIST pidl = NULL;
2858 IShellLinkW_GetIDList( sl, &pidl );
2859 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2860 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2863 /* extract the icon */
2864 if( szIconPath[0] )
2865 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2866 else
2867 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2869 /* fail - try once again after parent process exit */
2870 if( !icon_name )
2872 if (bWait)
2874 WINE_WARN("Unable to extract icon, deferring.\n");
2875 goto cleanup;
2877 WINE_ERR("failed to extract icon from %s\n",
2878 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2881 unix_link = wine_get_unix_file_name(link);
2882 if (unix_link == NULL)
2884 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2885 goto cleanup;
2888 /* check the path */
2889 if( szPath[0] )
2891 static const WCHAR exeW[] = {'.','e','x','e',0};
2892 WCHAR *p;
2894 /* check for .exe extension */
2895 if (!(p = strrchrW( szPath, '.' )) ||
2896 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2897 lstrcmpiW( p, exeW ))
2899 /* Not .exe - use 'start.exe' to launch this file */
2900 p = szArgs + lstrlenW(szPath) + 2;
2901 if (szArgs[0])
2903 p[0] = ' ';
2904 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2905 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2907 else
2908 p[0] = 0;
2910 szArgs[0] = '"';
2911 lstrcpyW(szArgs + 1, szPath);
2912 p[-1] = '"';
2914 GetWindowsDirectoryW(szPath, MAX_PATH);
2915 lstrcatW(szPath, startW);
2918 /* convert app working dir */
2919 if (szWorkDir[0])
2920 work_dir = wine_get_unix_file_name( szWorkDir );
2922 else
2924 /* if there's no path... try run the link itself */
2925 lstrcpynW(szArgs, link, MAX_PATH);
2926 GetWindowsDirectoryW(szPath, MAX_PATH);
2927 lstrcatW(szPath, startW);
2930 /* escape the path and parameters */
2931 escaped_path = escape(szPath);
2932 escaped_args = escape(szArgs);
2933 description = wchars_to_utf8_chars(szDescription);
2934 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2936 WINE_ERR("out of memory allocating/escaping parameters\n");
2937 goto cleanup;
2940 start_path = get_start_exe_path();
2941 if (start_path == NULL)
2943 WINE_ERR("out of memory\n");
2944 goto cleanup;
2947 /* building multiple menus concurrently has race conditions */
2948 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2949 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2951 WINE_ERR("failed wait for semaphore\n");
2952 goto cleanup;
2955 if (in_desktop_dir(csidl))
2957 char *location;
2958 const char *lastEntry;
2959 lastEntry = strrchr(link_name, '/');
2960 if (lastEntry == NULL)
2961 lastEntry = link_name;
2962 else
2963 ++lastEntry;
2964 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2965 if (location)
2967 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2969 char *link_arg = escape_unix_link_arg(unix_link);
2970 if (link_arg)
2972 r = !write_desktop_entry(unix_link, location, lastEntry,
2973 start_path, link_arg, description, work_dir, icon_name);
2974 HeapFree(GetProcessHeap(), 0, link_arg);
2977 else
2978 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2979 if (r == 0)
2980 chmod(location, 0755);
2981 HeapFree(GetProcessHeap(), 0, location);
2984 else
2986 char *link_arg = escape_unix_link_arg(unix_link);
2987 if (link_arg)
2989 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name);
2990 HeapFree(GetProcessHeap(), 0, link_arg);
2994 ReleaseSemaphore( hsem, 1, NULL );
2996 cleanup:
2997 if (hsem) CloseHandle( hsem );
2998 HeapFree( GetProcessHeap(), 0, icon_name );
2999 HeapFree( GetProcessHeap(), 0, work_dir );
3000 HeapFree( GetProcessHeap(), 0, link_name );
3001 HeapFree( GetProcessHeap(), 0, escaped_args );
3002 HeapFree( GetProcessHeap(), 0, escaped_path );
3003 HeapFree( GetProcessHeap(), 0, description );
3004 HeapFree( GetProcessHeap(), 0, unix_link );
3005 HeapFree( GetProcessHeap(), 0, start_path );
3007 if (r && !bWait)
3008 WINE_ERR("failed to build the menu\n" );
3010 return ( r == 0 );
3013 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
3015 char *link_name = NULL, *icon_name = NULL;
3016 DWORD csidl = -1;
3017 LPWSTR urlPath = NULL;
3018 char *escaped_urlPath = NULL;
3019 HRESULT hr;
3020 HANDLE hSem = NULL;
3021 BOOL ret = TRUE;
3022 int r = -1;
3023 char *unix_link = NULL;
3024 IPropertySetStorage *pPropSetStg;
3025 IPropertyStorage *pPropStg;
3026 PROPSPEC ps[2];
3027 PROPVARIANT pv[2];
3028 char *start_path = NULL;
3029 BOOL has_icon = FALSE;
3031 if ( !link )
3033 WINE_ERR("Link name is null\n");
3034 return TRUE;
3037 if( !GetLinkLocation( link, &csidl, &link_name ) )
3039 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
3040 return TRUE;
3042 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
3044 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3045 ret = TRUE;
3046 goto cleanup;
3048 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
3050 hr = url->lpVtbl->GetURL(url, &urlPath);
3051 if (FAILED(hr))
3053 ret = TRUE;
3054 goto cleanup;
3056 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
3058 unix_link = wine_get_unix_file_name(link);
3059 if (unix_link == NULL)
3061 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
3062 goto cleanup;
3065 escaped_urlPath = escape(urlPath);
3066 if (escaped_urlPath == NULL)
3068 WINE_ERR("couldn't escape url, out of memory\n");
3069 goto cleanup;
3072 start_path = get_start_exe_path();
3073 if (start_path == NULL)
3075 WINE_ERR("out of memory\n");
3076 goto cleanup;
3079 ps[0].ulKind = PRSPEC_PROPID;
3080 ps[0].u.propid = PID_IS_ICONFILE;
3081 ps[1].ulKind = PRSPEC_PROPID;
3082 ps[1].u.propid = PID_IS_ICONINDEX;
3084 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
3085 if (SUCCEEDED(hr))
3087 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
3088 if (SUCCEEDED(hr))
3090 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
3091 if (SUCCEEDED(hr))
3093 if (pv[0].vt == VT_LPWSTR && pv[0].u.pwszVal && pv[0].u.pwszVal[0])
3095 has_icon = TRUE;
3096 icon_name = extract_icon( pv[0].u.pwszVal, pv[1].u.iVal, NULL, bWait );
3098 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);
3100 PropVariantClear(&pv[0]);
3101 PropVariantClear(&pv[1]);
3103 IPropertyStorage_Release(pPropStg);
3105 IPropertySetStorage_Release(pPropSetStg);
3108 /* fail - try once again after parent process exit */
3109 if( has_icon && !icon_name )
3111 if (bWait)
3113 WINE_WARN("Unable to extract icon, deferring.\n");
3114 ret = FALSE;
3115 goto cleanup;
3117 WINE_ERR("failed to extract icon from %s\n",
3118 wine_dbgstr_w( pv[0].u.pwszVal ));
3121 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3122 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3124 WINE_ERR("failed wait for semaphore\n");
3125 goto cleanup;
3127 if (in_desktop_dir(csidl))
3129 char *location;
3130 const char *lastEntry;
3131 lastEntry = strrchr(link_name, '/');
3132 if (lastEntry == NULL)
3133 lastEntry = link_name;
3134 else
3135 ++lastEntry;
3136 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
3137 if (location)
3139 r = !write_desktop_entry(NULL, location, lastEntry, start_path, escaped_urlPath, NULL, NULL, icon_name);
3140 if (r == 0)
3141 chmod(location, 0755);
3142 HeapFree(GetProcessHeap(), 0, location);
3145 else
3146 r = !write_menu_entry(unix_link, link_name, start_path, escaped_urlPath, NULL, NULL, icon_name);
3147 ret = (r == 0);
3148 ReleaseSemaphore(hSem, 1, NULL);
3150 cleanup:
3151 if (hSem)
3152 CloseHandle(hSem);
3153 HeapFree( GetProcessHeap(), 0, icon_name );
3154 HeapFree(GetProcessHeap(), 0, link_name);
3155 CoTaskMemFree( urlPath );
3156 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
3157 HeapFree(GetProcessHeap(), 0, unix_link);
3158 return ret;
3161 static BOOL WaitForParentProcess( void )
3163 PROCESSENTRY32 procentry;
3164 HANDLE hsnapshot = NULL, hprocess = NULL;
3165 DWORD ourpid = GetCurrentProcessId();
3166 BOOL ret = FALSE, rc;
3168 WINE_TRACE("Waiting for parent process\n");
3169 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
3170 INVALID_HANDLE_VALUE)
3172 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3173 goto done;
3176 procentry.dwSize = sizeof(PROCESSENTRY32);
3177 rc = Process32First( hsnapshot, &procentry );
3178 while (rc)
3180 if (procentry.th32ProcessID == ourpid) break;
3181 rc = Process32Next( hsnapshot, &procentry );
3183 if (!rc)
3185 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
3186 goto done;
3189 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
3190 NULL)
3192 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
3193 GetLastError());
3194 goto done;
3197 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
3198 ret = TRUE;
3199 else
3200 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3202 done:
3203 if (hprocess) CloseHandle( hprocess );
3204 if (hsnapshot) CloseHandle( hsnapshot );
3205 return ret;
3208 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
3210 IShellLinkW *sl;
3211 IPersistFile *pf;
3212 HRESULT r;
3213 WCHAR fullname[MAX_PATH];
3214 DWORD len;
3216 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
3218 if( !linkname[0] )
3220 WINE_ERR("link name missing\n");
3221 return FALSE;
3224 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
3225 if (len==0 || len>MAX_PATH)
3227 WINE_ERR("couldn't get full path of link file\n");
3228 return FALSE;
3231 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3232 &IID_IShellLinkW, (LPVOID *) &sl );
3233 if( FAILED( r ) )
3235 WINE_ERR("No IID_IShellLink\n");
3236 return FALSE;
3239 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
3240 if( FAILED( r ) )
3242 WINE_ERR("No IID_IPersistFile\n");
3243 return FALSE;
3246 r = IPersistFile_Load( pf, fullname, STGM_READ );
3247 if( SUCCEEDED( r ) )
3249 /* If something fails (eg. Couldn't extract icon)
3250 * wait for parent process and try again
3252 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
3254 WaitForParentProcess();
3255 InvokeShellLinker( sl, fullname, FALSE );
3258 else
3260 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
3263 IPersistFile_Release( pf );
3264 IShellLinkW_Release( sl );
3266 return !r;
3269 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
3271 IUniformResourceLocatorW *url;
3272 IPersistFile *pf;
3273 HRESULT r;
3274 WCHAR fullname[MAX_PATH];
3275 DWORD len;
3277 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
3279 if( !urlname[0] )
3281 WINE_ERR("URL name missing\n");
3282 return FALSE;
3285 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
3286 if (len==0 || len>MAX_PATH)
3288 WINE_ERR("couldn't get full path of URL file\n");
3289 return FALSE;
3292 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
3293 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
3294 if( FAILED( r ) )
3296 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3297 return FALSE;
3300 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
3301 if( FAILED( r ) )
3303 WINE_ERR("No IID_IPersistFile\n");
3304 return FALSE;
3306 r = IPersistFile_Load( pf, fullname, STGM_READ );
3307 if( SUCCEEDED( r ) )
3309 /* If something fails (eg. Couldn't extract icon)
3310 * wait for parent process and try again
3312 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
3314 WaitForParentProcess();
3315 InvokeShellLinkerForURL( url, fullname, FALSE );
3319 IPersistFile_Release( pf );
3320 url->lpVtbl->Release( url );
3322 return !r;
3325 static void RefreshFileTypeAssociations(void)
3327 HANDLE hSem = NULL;
3328 char *mime_dir = NULL;
3329 char *packages_dir = NULL;
3330 char *applications_dir = NULL;
3331 BOOL hasChanged;
3333 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3334 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3336 WINE_ERR("failed wait for semaphore\n");
3337 CloseHandle(hSem);
3338 hSem = NULL;
3339 goto end;
3342 mime_dir = heap_printf("%s/mime", xdg_data_dir);
3343 if (mime_dir == NULL)
3345 WINE_ERR("out of memory\n");
3346 goto end;
3348 create_directories(mime_dir);
3350 packages_dir = heap_printf("%s/packages", mime_dir);
3351 if (packages_dir == NULL)
3353 WINE_ERR("out of memory\n");
3354 goto end;
3356 create_directories(packages_dir);
3358 applications_dir = heap_printf("%s/applications", xdg_data_dir);
3359 if (applications_dir == NULL)
3361 WINE_ERR("out of memory\n");
3362 goto end;
3364 create_directories(applications_dir);
3366 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3367 hasChanged |= cleanup_associations();
3368 if (hasChanged)
3370 const char *argv[3];
3372 argv[0] = "update-mime-database";
3373 argv[1] = mime_dir;
3374 argv[2] = NULL;
3375 _spawnvp( _P_DETACH, argv[0], argv );
3377 argv[0] = "update-desktop-database";
3378 argv[1] = applications_dir;
3379 _spawnvp( _P_DETACH, argv[0], argv );
3382 end:
3383 if (hSem)
3385 ReleaseSemaphore(hSem, 1, NULL);
3386 CloseHandle(hSem);
3388 HeapFree(GetProcessHeap(), 0, mime_dir);
3389 HeapFree(GetProcessHeap(), 0, packages_dir);
3390 HeapFree(GetProcessHeap(), 0, applications_dir);
3393 static void cleanup_menus(void)
3395 HKEY hkey;
3397 hkey = open_menus_reg_key();
3398 if (hkey)
3400 int i;
3401 LSTATUS lret = ERROR_SUCCESS;
3402 for (i = 0; lret == ERROR_SUCCESS; )
3404 WCHAR *value = NULL;
3405 WCHAR *data = NULL;
3406 DWORD valueSize = 4096;
3407 DWORD dataSize = 4096;
3408 while (1)
3410 lret = ERROR_OUTOFMEMORY;
3411 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3412 if (value == NULL)
3413 break;
3414 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3415 if (data == NULL)
3416 break;
3417 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3418 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
3419 break;
3420 valueSize *= 2;
3421 dataSize *= 2;
3422 HeapFree(GetProcessHeap(), 0, value);
3423 HeapFree(GetProcessHeap(), 0, data);
3424 value = data = NULL;
3426 if (lret == ERROR_SUCCESS)
3428 char *unix_file;
3429 char *windows_file;
3430 unix_file = wchars_to_unix_chars(value);
3431 windows_file = wchars_to_unix_chars(data);
3432 if (unix_file != NULL && windows_file != NULL)
3434 struct stat filestats;
3435 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3437 WINE_TRACE("removing menu related file %s\n", unix_file);
3438 remove(unix_file);
3439 RegDeleteValueW(hkey, value);
3441 else
3442 i++;
3444 else
3446 WINE_ERR("out of memory enumerating menus\n");
3447 lret = ERROR_OUTOFMEMORY;
3449 HeapFree(GetProcessHeap(), 0, unix_file);
3450 HeapFree(GetProcessHeap(), 0, windows_file);
3452 else if (lret != ERROR_NO_MORE_ITEMS)
3453 WINE_ERR("error %d reading registry\n", lret);
3454 HeapFree(GetProcessHeap(), 0, value);
3455 HeapFree(GetProcessHeap(), 0, data);
3457 RegCloseKey(hkey);
3459 else
3460 WINE_ERR("error opening registry key, menu cleanup failed\n");
3463 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3465 char *utf8lnkPath = NULL;
3466 char *utf8OutputPath = NULL;
3467 WCHAR *winLnkPath = NULL;
3468 IShellLinkW *shellLink = NULL;
3469 IPersistFile *persistFile = NULL;
3470 WCHAR szTmp[MAX_PATH];
3471 WCHAR szPath[MAX_PATH];
3472 WCHAR szArgs[INFOTIPSIZE];
3473 WCHAR szIconPath[MAX_PATH];
3474 int iconId;
3475 IStream *stream = NULL;
3476 HRESULT hr;
3478 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3479 if (utf8lnkPath == NULL)
3481 WINE_ERR("out of memory converting paths\n");
3482 goto end;
3485 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3486 if (utf8OutputPath == NULL)
3488 WINE_ERR("out of memory converting paths\n");
3489 goto end;
3492 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3493 if (winLnkPath == NULL)
3495 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3496 goto end;
3499 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3500 &IID_IShellLinkW, (LPVOID*)&shellLink);
3501 if (FAILED(hr))
3503 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3504 goto end;
3507 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3508 if (FAILED(hr))
3510 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3511 goto end;
3514 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3515 if (FAILED(hr))
3517 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3518 goto end;
3521 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3522 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3523 szTmp[0] = 0;
3524 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3525 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3527 if(!szPath[0])
3529 LPITEMIDLIST pidl = NULL;
3530 IShellLinkW_GetIDList(shellLink, &pidl);
3531 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3532 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3535 if (szIconPath[0])
3537 hr = open_icon(szIconPath, iconId, FALSE, &stream);
3538 if (SUCCEEDED(hr))
3539 hr = write_native_icon(stream, utf8OutputPath, NULL);
3541 else
3543 hr = open_icon(szPath, iconId, FALSE, &stream);
3544 if (SUCCEEDED(hr))
3545 hr = write_native_icon(stream, utf8OutputPath, NULL);
3548 end:
3549 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3550 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3551 HeapFree(GetProcessHeap(), 0, winLnkPath);
3552 if (shellLink != NULL)
3553 IShellLinkW_Release(shellLink);
3554 if (persistFile != NULL)
3555 IPersistFile_Release(persistFile);
3556 if (stream != NULL)
3557 IStream_Release(stream);
3560 static WCHAR *next_token( LPWSTR *p )
3562 LPWSTR token = NULL, t = *p;
3564 if( !t )
3565 return NULL;
3567 while( t && !token )
3569 switch( *t )
3571 case ' ':
3572 t++;
3573 continue;
3574 case '"':
3575 /* unquote the token */
3576 token = ++t;
3577 t = strchrW( token, '"' );
3578 if( t )
3579 *t++ = 0;
3580 break;
3581 case 0:
3582 t = NULL;
3583 break;
3584 default:
3585 token = t;
3586 t = strchrW( token, ' ' );
3587 if( t )
3588 *t++ = 0;
3589 break;
3592 *p = t;
3593 return token;
3596 static BOOL init_xdg(void)
3598 WCHAR shellDesktopPath[MAX_PATH];
3599 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3600 if (SUCCEEDED(hr))
3601 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3602 if (xdg_desktop_dir == NULL)
3604 WINE_ERR("error looking up the desktop directory\n");
3605 return FALSE;
3608 if (getenv("XDG_CONFIG_HOME"))
3609 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3610 else
3611 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3612 if (xdg_config_dir)
3614 create_directories(xdg_config_dir);
3615 if (getenv("XDG_DATA_HOME"))
3616 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3617 else
3618 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3619 if (xdg_data_dir)
3621 char *buffer;
3622 create_directories(xdg_data_dir);
3623 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3624 if (buffer)
3626 mkdir(buffer, 0777);
3627 HeapFree(GetProcessHeap(), 0, buffer);
3629 return TRUE;
3631 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3633 WINE_ERR("out of memory\n");
3634 return FALSE;
3637 /***********************************************************************
3639 * wWinMain
3641 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3643 static const WCHAR dash_aW[] = {'-','a',0};
3644 static const WCHAR dash_rW[] = {'-','r',0};
3645 static const WCHAR dash_tW[] = {'-','t',0};
3646 static const WCHAR dash_uW[] = {'-','u',0};
3647 static const WCHAR dash_wW[] = {'-','w',0};
3649 LPWSTR token = NULL, p;
3650 BOOL bWait = FALSE;
3651 BOOL bURL = FALSE;
3652 HRESULT hr;
3653 int ret = 0;
3655 if (!init_xdg())
3656 return 1;
3658 hr = CoInitialize(NULL);
3659 if (FAILED(hr))
3661 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3662 return 1;
3665 for( p = cmdline; p && *p; )
3667 token = next_token( &p );
3668 if( !token )
3669 break;
3670 if( !strcmpW( token, dash_aW ) )
3672 RefreshFileTypeAssociations();
3673 continue;
3675 if( !strcmpW( token, dash_rW ) )
3677 cleanup_menus();
3678 continue;
3680 if( !strcmpW( token, dash_wW ) )
3681 bWait = TRUE;
3682 else if ( !strcmpW( token, dash_uW ) )
3683 bURL = TRUE;
3684 else if ( !strcmpW( token, dash_tW ) )
3686 WCHAR *lnkFile = next_token( &p );
3687 if (lnkFile)
3689 WCHAR *outputFile = next_token( &p );
3690 if (outputFile)
3691 thumbnail_lnk(lnkFile, outputFile);
3694 else if( token[0] == '-' )
3696 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3698 else
3700 BOOL bRet;
3702 if (bURL)
3703 bRet = Process_URL( token, bWait );
3704 else
3705 bRet = Process_Link( token, bWait );
3706 if (!bRet)
3708 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3709 ret = 1;
3714 CoUninitialize();
3715 return ret;