winemenubuilder: Prevent recursion by calling open_module_icon() instead of open_icon()
[wine.git] / programs / winemenubuilder / winemenubuilder.c
blobfae89f97c576a58a7e84a1946eb59e2b7f4e9bc0
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 DWORD size = min( grpIconDir->idEntries[i].dwBytesInRes, ((IMAGE_RESOURCE_DATA_ENTRY *)hResInfo)->Size );
616 if ((pIcon = LockResource(hResData)))
618 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
619 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
620 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
621 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
622 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
623 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
624 iconDirEntries[validEntries].dwBytesInRes = size;
625 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
626 validEntries++;
627 memcpy(&icons[*iconOffset], pIcon, size);
628 *iconOffset += size;
630 FreeResource(hResData);
634 return validEntries;
637 static IStream *add_module_icons_to_stream(struct IconData16 *iconData16, HMODULE hModule, GRPICONDIR *grpIconDir)
639 int i;
640 SIZE_T iconsSize = 0;
641 BYTE *icons = NULL;
642 ICONDIRENTRY *iconDirEntries = NULL;
643 IStream *stream = NULL;
644 HRESULT hr = E_FAIL;
645 ULONG bytesWritten;
646 ICONDIR iconDir;
647 SIZE_T iconOffset;
648 int validEntries = 0;
649 LARGE_INTEGER zero;
651 for (i = 0; i < grpIconDir->idCount; i++)
652 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
653 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
654 if (icons == NULL)
656 WINE_ERR("out of memory allocating icon\n");
657 goto end;
660 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
661 if (iconDirEntries == NULL)
663 WINE_ERR("out of memory allocating icon dir entries\n");
664 goto end;
667 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
668 if (FAILED(hr))
670 WINE_ERR("error creating icon stream\n");
671 goto end;
674 iconOffset = 0;
675 if (iconData16)
676 validEntries = populate_module16_icons(iconData16, grpIconDir, iconDirEntries, icons, &iconOffset);
677 else if (hModule)
678 validEntries = populate_module_icons(hModule, grpIconDir, iconDirEntries, icons, &iconOffset);
680 if (validEntries == 0)
682 WINE_ERR("no valid icon entries\n");
683 goto end;
686 iconDir.idReserved = 0;
687 iconDir.idType = 1;
688 iconDir.idCount = validEntries;
689 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
690 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
692 WINE_ERR("error 0x%08X writing icon stream\n", hr);
693 goto end;
695 for (i = 0; i < validEntries; i++)
696 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
697 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
698 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
700 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
701 goto end;
703 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
704 if (FAILED(hr) || bytesWritten != iconOffset)
706 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
707 goto end;
709 zero.QuadPart = 0;
710 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
712 end:
713 HeapFree(GetProcessHeap(), 0, icons);
714 HeapFree(GetProcessHeap(), 0, iconDirEntries);
715 if (FAILED(hr) && stream != NULL)
717 IStream_Release(stream);
718 stream = NULL;
720 return stream;
723 static HRESULT open_module16_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
725 HANDLE hFile = INVALID_HANDLE_VALUE;
726 HANDLE hFileMapping = NULL;
727 DWORD fileSize;
728 BYTE *fileBytes = NULL;
729 IMAGE_DOS_HEADER *dosHeader;
730 IMAGE_OS2_HEADER *neHeader;
731 BYTE *rsrcTab;
732 NE_TYPEINFO *iconGroupResources;
733 NE_TYPEINFO *iconResources;
734 NE_NAMEINFO *iconDirPtr;
735 GRPICONDIR *iconDir;
736 WORD alignmentShiftCount;
737 struct IconData16 iconData16;
738 HRESULT hr = E_FAIL;
740 hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
741 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
742 if (hFile == INVALID_HANDLE_VALUE)
744 WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName), GetLastError());
745 goto end;
748 hFileMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
749 if (hFileMapping == NULL)
751 WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
752 goto end;
755 fileSize = GetFileSize(hFile, NULL);
757 fileBytes = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
758 if (fileBytes == NULL)
760 WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
761 goto end;
764 dosHeader = (IMAGE_DOS_HEADER*)fileBytes;
765 if (sizeof(IMAGE_DOS_HEADER) >= fileSize || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
767 WINE_WARN("file too small for MZ header\n");
768 goto end;
771 neHeader = (IMAGE_OS2_HEADER*)(fileBytes + dosHeader->e_lfanew);
772 if ((((BYTE*)neHeader) + sizeof(IMAGE_OS2_HEADER)) > (fileBytes + fileSize) ||
773 neHeader->ne_magic != IMAGE_OS2_SIGNATURE)
775 WINE_WARN("file too small for NE header\n");
776 goto end;
779 rsrcTab = ((BYTE*)neHeader) + neHeader->ne_rsrctab;
780 if ((rsrcTab + 2) > (fileBytes + fileSize))
782 WINE_WARN("file too small for resource table\n");
783 goto end;
786 alignmentShiftCount = *(WORD*)rsrcTab;
787 rsrcTab += 2;
788 iconGroupResources = NULL;
789 iconResources = NULL;
790 for (;;)
792 NE_TYPEINFO *neTypeInfo = (NE_TYPEINFO*)rsrcTab;
793 if ((rsrcTab + sizeof(NE_TYPEINFO)) > (fileBytes + fileSize))
795 WINE_WARN("file too small for resource table\n");
796 goto end;
798 if (neTypeInfo->type_id == 0)
799 break;
800 else if (neTypeInfo->type_id == NE_RSCTYPE_GROUP_ICON)
801 iconGroupResources = neTypeInfo;
802 else if (neTypeInfo->type_id == NE_RSCTYPE_ICON)
803 iconResources = neTypeInfo;
804 rsrcTab += sizeof(NE_TYPEINFO) + neTypeInfo->count*sizeof(NE_NAMEINFO);
806 if (iconGroupResources == NULL)
808 WINE_WARN("no group icon resource type found\n");
809 goto end;
811 if (iconResources == NULL)
813 WINE_WARN("no icon resource type found\n");
814 goto end;
817 if (nIndex >= iconGroupResources->count)
819 WINE_WARN("icon index out of range\n");
820 goto end;
823 iconDirPtr = (NE_NAMEINFO*)(((BYTE*)iconGroupResources) + sizeof(NE_TYPEINFO) + nIndex*sizeof(NE_NAMEINFO));
824 if ((((BYTE*)iconDirPtr) + sizeof(NE_NAMEINFO)) > (fileBytes + fileSize))
826 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
827 goto end;
829 iconDir = (GRPICONDIR*)(fileBytes + (iconDirPtr->offset << alignmentShiftCount));
830 if ((((BYTE*)iconDir) + sizeof(GRPICONDIR) + iconDir->idCount*sizeof(GRPICONDIRENTRY)) > (fileBytes + fileSize))
832 WINE_WARN("file too small for GRPICONDIR\n");
833 goto end;
836 iconData16.fileBytes = fileBytes;
837 iconData16.fileSize = fileSize;
838 iconData16.iconResources = iconResources;
839 iconData16.alignmentShiftCount = alignmentShiftCount;
840 *ppStream = add_module_icons_to_stream(&iconData16, NULL, iconDir);
841 if (*ppStream)
842 hr = S_OK;
844 end:
845 if (hFile != INVALID_HANDLE_VALUE)
846 CloseHandle(hFile);
847 if (hFileMapping != NULL)
848 CloseHandle(hFileMapping);
849 if (fileBytes != NULL)
850 UnmapViewOfFile(fileBytes);
851 return hr;
854 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
856 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
858 if (!sEnumRes->nIndex--)
860 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
861 return FALSE;
863 else
864 return TRUE;
867 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
869 HMODULE hModule;
870 HRSRC hResInfo;
871 HGLOBAL hResData;
872 GRPICONDIR *pIconDir;
873 ENUMRESSTRUCT sEnumRes;
874 HRESULT hr = E_FAIL;
876 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
877 if (!hModule)
879 if (GetLastError() == ERROR_BAD_EXE_FORMAT)
880 return open_module16_icon(szFileName, nIndex, ppStream);
881 else
883 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
884 wine_dbgstr_w(szFileName), GetLastError());
885 return HRESULT_FROM_WIN32(GetLastError());
889 if (nIndex < 0)
891 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
892 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
893 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
895 else
897 hResInfo=NULL;
898 sEnumRes.pResInfo = &hResInfo;
899 sEnumRes.nIndex = nIndex;
900 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
901 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
902 sEnumRes.nIndex != -1)
904 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
908 if (hResInfo)
910 if ((hResData = LoadResource(hModule, hResInfo)))
912 if ((pIconDir = LockResource(hResData)))
914 *ppStream = add_module_icons_to_stream(0, hModule, pIconDir);
915 if (*ppStream)
916 hr = S_OK;
919 FreeResource(hResData);
922 else
924 WINE_WARN("found no icon\n");
925 FreeLibrary(hModule);
926 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
929 FreeLibrary(hModule);
930 return hr;
933 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
935 ICONDIR iconDir;
936 ULONG bytesRead;
937 HRESULT hr;
939 *ppIconDirEntries = NULL;
941 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
942 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
943 (iconDir.idReserved != 0) || (iconDir.idType != 1))
945 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
946 hr = E_FAIL;
947 goto end;
949 *numEntries = iconDir.idCount;
951 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
953 hr = E_OUTOFMEMORY;
954 goto end;
956 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
957 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
959 if (SUCCEEDED(hr)) hr = E_FAIL;
960 goto end;
963 end:
964 if (FAILED(hr))
965 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
966 return hr;
969 static HRESULT write_native_icon(IStream *iconStream, const char *icon_name, LPCWSTR szFileName)
971 ICONDIRENTRY *pIconDirEntry = NULL;
972 int numEntries;
973 int nMax = 0, nMaxBits = 0;
974 int nIndex = 0;
975 int i;
976 LARGE_INTEGER position;
977 HRESULT hr;
979 hr = read_ico_direntries(iconStream, &pIconDirEntry, &numEntries);
980 if (FAILED(hr))
981 goto end;
983 for (i = 0; i < numEntries; i++)
985 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
986 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
987 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
989 nIndex = i;
990 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
991 nMaxBits = pIconDirEntry[i].wBitCount;
994 WINE_TRACE("Selected: %d\n", nIndex);
996 position.QuadPart = 0;
997 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
998 if (FAILED(hr))
999 goto end;
1000 hr = convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
1002 end:
1003 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
1004 return hr;
1007 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
1009 static const WCHAR openW[] = {'o','p','e','n',0};
1010 WCHAR *extension;
1011 WCHAR *icon = NULL;
1012 WCHAR *comma;
1013 WCHAR *executable = NULL;
1014 int index = 0;
1015 char *output_path = NULL;
1016 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
1018 extension = strrchrW(szFileName, '.');
1019 if (extension == NULL)
1020 goto end;
1022 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
1023 if (icon)
1025 comma = strrchrW(icon, ',');
1026 if (comma)
1028 *comma = 0;
1029 index = atoiW(comma + 1);
1031 hr = open_module_icon(icon, index, ppStream);
1033 else
1035 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, openW);
1036 if (executable)
1037 hr = open_module_icon(executable, 0, ppStream);
1040 end:
1041 HeapFree(GetProcessHeap(), 0, icon);
1042 HeapFree(GetProcessHeap(), 0, executable);
1043 HeapFree(GetProcessHeap(), 0, output_path);
1044 return hr;
1047 static HRESULT open_default_icon(IStream **ppStream)
1049 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
1051 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
1054 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream)
1056 HRESULT hr;
1058 hr = open_module_icon(filename, index, ppStream);
1059 if (FAILED(hr))
1061 if(bWait && hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
1063 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1064 wine_dbgstr_w(filename));
1065 return hr;
1067 else
1069 static const WCHAR dot_icoW[] = {'.','i','c','o',0};
1070 int len = strlenW(filename);
1071 if (len >= 4 && strcmpiW(&filename[len - 4], dot_icoW) == 0)
1072 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
1075 if (FAILED(hr))
1076 hr = open_file_type_icon(filename, ppStream);
1077 if (FAILED(hr) && !bWait)
1078 hr = open_default_icon(ppStream);
1079 return hr;
1082 static char* compute_native_identifier(int exeIndex, LPCWSTR icoPathW)
1084 char* nativeIdentifier;
1085 char *icoPathA;
1086 unsigned short crc;
1087 char *basename, *ext;
1089 icoPathA = wchars_to_utf8_chars(icoPathW);
1090 if (icoPathA == NULL)
1091 return NULL;
1093 crc = crc16(icoPathA);
1094 basename = strrchr(icoPathA, '\\');
1095 if (basename == NULL)
1096 basename = icoPathA;
1097 else
1099 *basename = 0;
1100 basename++;
1102 ext = strrchr(basename, '.');
1103 if (ext)
1104 *ext = 0;
1106 nativeIdentifier = heap_printf("%04X_%s.%d", crc, basename, exeIndex);
1107 HeapFree(GetProcessHeap(), 0, icoPathA);
1108 return nativeIdentifier;
1111 #ifdef __APPLE__
1112 #define ICNS_SLOTS 6
1114 static inline int size_to_slot(int size)
1116 switch (size)
1118 case 16: return 0;
1119 case 32: return 1;
1120 case 48: return 2;
1121 case 64: return -2; /* Classic Mode */
1122 case 128: return 3;
1123 case 256: return 4;
1124 case 512: return 5;
1127 return -1;
1130 #define CLASSIC_SLOT 3
1132 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex, LPCWSTR icoPathW,
1133 const char *destFilename, char **nativeIdentifier)
1135 ICONDIRENTRY *iconDirEntries = NULL;
1136 int numEntries;
1137 struct {
1138 int index;
1139 int maxBits;
1140 BOOL scaled;
1141 } best[ICNS_SLOTS];
1142 int indexes[ICNS_SLOTS];
1143 int i;
1144 const char* tmpdir;
1145 char *icnsPath = NULL;
1146 LARGE_INTEGER zero;
1147 HRESULT hr;
1149 hr = read_ico_direntries(icoStream, &iconDirEntries, &numEntries);
1150 if (FAILED(hr))
1151 goto end;
1152 for (i = 0; i < ICNS_SLOTS; i++)
1154 best[i].index = -1;
1155 best[i].maxBits = 0;
1157 for (i = 0; i < numEntries; i++)
1159 int slot;
1160 int width = iconDirEntries[i].bWidth ? iconDirEntries[i].bWidth : 256;
1161 int height = iconDirEntries[i].bHeight ? iconDirEntries[i].bHeight : 256;
1162 BOOL scaled = FALSE;
1164 WINE_TRACE("[%d]: %d x %d @ %d\n", i, width, height, iconDirEntries[i].wBitCount);
1165 if (height != width)
1166 continue;
1167 slot = size_to_slot(width);
1168 if (slot == -2)
1170 scaled = TRUE;
1171 slot = CLASSIC_SLOT;
1173 else if (slot < 0)
1174 continue;
1175 if (scaled && best[slot].maxBits && !best[slot].scaled)
1176 continue; /* don't replace unscaled with scaled */
1177 if (iconDirEntries[i].wBitCount >= best[slot].maxBits || (!scaled && best[slot].scaled))
1179 best[slot].index = i;
1180 best[slot].maxBits = iconDirEntries[i].wBitCount;
1181 best[slot].scaled = scaled;
1184 /* remove the scaled icon if a larger unscaled icon exists */
1185 if (best[CLASSIC_SLOT].scaled)
1187 for (i = CLASSIC_SLOT+1; i < ICNS_SLOTS; i++)
1188 if (best[i].index >= 0 && !best[i].scaled)
1190 best[CLASSIC_SLOT].index = -1;
1191 break;
1195 numEntries = 0;
1196 for (i = 0; i < ICNS_SLOTS; i++)
1198 if (best[i].index >= 0)
1200 indexes[numEntries] = best[i].index;
1201 numEntries++;
1205 if (destFilename)
1206 *nativeIdentifier = heap_printf("%s", destFilename);
1207 else
1208 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1209 if (*nativeIdentifier == NULL)
1211 hr = E_OUTOFMEMORY;
1212 goto end;
1214 if (!(tmpdir = getenv("TMPDIR"))) tmpdir = "/tmp";
1215 icnsPath = heap_printf("%s/%s.icns", tmpdir, *nativeIdentifier);
1216 if (icnsPath == NULL)
1218 hr = E_OUTOFMEMORY;
1219 WINE_WARN("out of memory creating ICNS path\n");
1220 goto end;
1222 zero.QuadPart = 0;
1223 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1224 if (FAILED(hr))
1226 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
1227 goto end;
1229 hr = convert_to_native_icon(icoStream, indexes, numEntries, &CLSID_WICIcnsEncoder,
1230 icnsPath, icoPathW);
1231 if (FAILED(hr))
1233 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
1234 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
1235 goto end;
1238 end:
1239 HeapFree(GetProcessHeap(), 0, iconDirEntries);
1240 HeapFree(GetProcessHeap(), 0, icnsPath);
1241 return hr;
1243 #else
1244 static void refresh_icon_cache(const char *iconsDir)
1246 /* The icon theme spec only requires the mtime on the "toplevel"
1247 * directory (whatever that is) to be changed for a refresh,
1248 * but on GNOME you have to create a file in that directory
1249 * instead. Creating a file also works on KDE, Xfce and LXDE.
1251 char *filename = heap_printf("%s/.wine-refresh-XXXXXX", iconsDir);
1252 if (filename != NULL)
1254 int fd = mkstemps(filename, 0);
1255 if (fd >= 0)
1257 close(fd);
1258 unlink(filename);
1260 HeapFree(GetProcessHeap(), 0, filename);
1264 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex, LPCWSTR icoPathW,
1265 const char *destFilename, char **nativeIdentifier)
1267 ICONDIRENTRY *iconDirEntries = NULL;
1268 int numEntries;
1269 int i;
1270 char *iconsDir = NULL;
1271 HRESULT hr = S_OK;
1272 LARGE_INTEGER zero;
1274 hr = read_ico_direntries(icoStream, &iconDirEntries, &numEntries);
1275 if (FAILED(hr))
1276 goto end;
1278 if (destFilename)
1279 *nativeIdentifier = heap_printf("%s", destFilename);
1280 else
1281 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1282 if (*nativeIdentifier == NULL)
1284 hr = E_OUTOFMEMORY;
1285 goto end;
1287 iconsDir = heap_printf("%s/icons/hicolor", xdg_data_dir);
1288 if (iconsDir == NULL)
1290 hr = E_OUTOFMEMORY;
1291 goto end;
1294 for (i = 0; i < numEntries; i++)
1296 int bestIndex = i;
1297 int j;
1298 BOOLEAN duplicate = FALSE;
1299 int w, h;
1300 char *iconDir = NULL;
1301 char *pngPath = NULL;
1303 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
1304 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
1306 for (j = 0; j < i; j++)
1308 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1309 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
1311 duplicate = TRUE;
1312 break;
1315 if (duplicate)
1316 continue;
1317 for (j = i + 1; j < numEntries; j++)
1319 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1320 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1321 iconDirEntries[j].wBitCount >= iconDirEntries[bestIndex].wBitCount)
1323 bestIndex = j;
1326 WINE_TRACE("Selected: %d\n", bestIndex);
1328 w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
1329 h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
1330 iconDir = heap_printf("%s/%dx%d/apps", iconsDir, w, h);
1331 if (iconDir == NULL)
1333 hr = E_OUTOFMEMORY;
1334 goto endloop;
1336 create_directories(iconDir);
1337 pngPath = heap_printf("%s/%s.png", iconDir, *nativeIdentifier);
1338 if (pngPath == NULL)
1340 hr = E_OUTOFMEMORY;
1341 goto endloop;
1343 zero.QuadPart = 0;
1344 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1345 if (FAILED(hr))
1346 goto endloop;
1347 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
1348 pngPath, icoPathW);
1350 endloop:
1351 HeapFree(GetProcessHeap(), 0, iconDir);
1352 HeapFree(GetProcessHeap(), 0, pngPath);
1354 refresh_icon_cache(iconsDir);
1356 end:
1357 HeapFree(GetProcessHeap(), 0, iconDirEntries);
1358 HeapFree(GetProcessHeap(), 0, iconsDir);
1359 return hr;
1361 #endif /* defined(__APPLE__) */
1363 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1364 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
1366 IStream *stream = NULL;
1367 HRESULT hr;
1368 char *nativeIdentifier = NULL;
1370 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
1372 hr = open_icon(icoPathW, index, bWait, &stream);
1373 if (FAILED(hr))
1375 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
1376 goto end;
1378 hr = platform_write_icon(stream, index, icoPathW, destFilename, &nativeIdentifier);
1379 if (FAILED(hr))
1380 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
1382 end:
1383 if (stream)
1384 IStream_Release(stream);
1385 if (FAILED(hr))
1387 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
1388 nativeIdentifier = NULL;
1390 return nativeIdentifier;
1393 static HKEY open_menus_reg_key(void)
1395 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1396 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1397 HKEY assocKey;
1398 DWORD ret;
1399 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1400 if (ret == ERROR_SUCCESS)
1401 return assocKey;
1402 SetLastError(ret);
1403 return NULL;
1406 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1408 WCHAR *unix_fileW;
1409 WCHAR *windows_fileW;
1410 INT size;
1411 DWORD ret;
1413 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1414 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1415 if (unix_fileW)
1417 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1418 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1419 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1420 if (windows_fileW)
1422 HKEY hkey;
1423 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1424 hkey = open_menus_reg_key();
1425 if (hkey)
1427 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1428 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1429 RegCloseKey(hkey);
1431 else
1432 ret = GetLastError();
1433 HeapFree(GetProcessHeap(), 0, windows_fileW);
1435 else
1436 ret = ERROR_NOT_ENOUGH_MEMORY;
1437 HeapFree(GetProcessHeap(), 0, unix_fileW);
1439 else
1440 ret = ERROR_NOT_ENOUGH_MEMORY;
1441 return ret;
1444 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1445 const char *path, const char *args, const char *descr,
1446 const char *workdir, const char *icon)
1448 FILE *file;
1450 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1451 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1452 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1454 file = fopen(location, "w");
1455 if (file == NULL)
1456 return FALSE;
1458 fprintf(file, "[Desktop Entry]\n");
1459 fprintf(file, "Name=%s\n", linkname);
1460 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1461 wine_get_config_dir(), path, args);
1462 fprintf(file, "Type=Application\n");
1463 fprintf(file, "StartupNotify=true\n");
1464 if (descr && lstrlenA(descr))
1465 fprintf(file, "Comment=%s\n", descr);
1466 if (workdir && lstrlenA(workdir))
1467 fprintf(file, "Path=%s\n", workdir);
1468 if (icon && lstrlenA(icon))
1469 fprintf(file, "Icon=%s\n", icon);
1471 fclose(file);
1473 if (unix_link)
1475 DWORD ret = register_menus_entry(location, unix_link);
1476 if (ret != ERROR_SUCCESS)
1477 return FALSE;
1480 return TRUE;
1483 static BOOL write_directory_entry(const char *directory, const char *location)
1485 FILE *file;
1487 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1489 file = fopen(location, "w");
1490 if (file == NULL)
1491 return FALSE;
1493 fprintf(file, "[Desktop Entry]\n");
1494 fprintf(file, "Type=Directory\n");
1495 if (strcmp(directory, "wine") == 0)
1497 fprintf(file, "Name=Wine\n");
1498 fprintf(file, "Icon=wine\n");
1500 else
1502 fprintf(file, "Name=%s\n", directory);
1503 fprintf(file, "Icon=folder\n");
1506 fclose(file);
1507 return TRUE;
1510 static BOOL write_menu_file(const char *unix_link, const char *filename)
1512 char *tempfilename;
1513 FILE *tempfile = NULL;
1514 char *lastEntry;
1515 char *name = NULL;
1516 char *menuPath = NULL;
1517 int i;
1518 int count = 0;
1519 BOOL ret = FALSE;
1521 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1523 while (1)
1525 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1526 if (tempfilename)
1528 int tempfd = mkstemps(tempfilename, 0);
1529 if (tempfd >= 0)
1531 tempfile = fdopen(tempfd, "w");
1532 if (tempfile)
1533 break;
1534 close(tempfd);
1535 goto end;
1537 else if (errno == EEXIST)
1539 HeapFree(GetProcessHeap(), 0, tempfilename);
1540 continue;
1542 HeapFree(GetProcessHeap(), 0, tempfilename);
1544 return FALSE;
1547 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1548 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1549 fprintf(tempfile, "<Menu>\n");
1550 fprintf(tempfile, " <Name>Applications</Name>\n");
1552 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1553 if (name == NULL) goto end;
1554 lastEntry = name;
1555 for (i = 0; filename[i]; i++)
1557 name[i] = filename[i];
1558 if (filename[i] == '/')
1560 char *dir_file_name;
1561 struct stat st;
1562 name[i] = 0;
1563 fprintf(tempfile, " <Menu>\n");
1564 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1565 write_xml_text(tempfile, name);
1566 fprintf(tempfile, "</Name>\n");
1567 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1568 write_xml_text(tempfile, name);
1569 fprintf(tempfile, ".directory</Directory>\n");
1570 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1571 xdg_data_dir, count ? "" : "wine-", name);
1572 if (dir_file_name)
1574 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1575 write_directory_entry(lastEntry, dir_file_name);
1576 HeapFree(GetProcessHeap(), 0, dir_file_name);
1578 name[i] = '-';
1579 lastEntry = &name[i+1];
1580 ++count;
1583 name[i] = 0;
1585 fprintf(tempfile, " <Include>\n");
1586 fprintf(tempfile, " <Filename>");
1587 write_xml_text(tempfile, name);
1588 fprintf(tempfile, "</Filename>\n");
1589 fprintf(tempfile, " </Include>\n");
1590 for (i = 0; i < count; i++)
1591 fprintf(tempfile, " </Menu>\n");
1592 fprintf(tempfile, "</Menu>\n");
1594 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1595 if (menuPath == NULL) goto end;
1596 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1597 ret = TRUE;
1599 end:
1600 if (tempfile)
1601 fclose(tempfile);
1602 if (ret)
1603 ret = (rename(tempfilename, menuPath) == 0);
1604 if (!ret && tempfilename)
1605 remove(tempfilename);
1606 HeapFree(GetProcessHeap(), 0, tempfilename);
1607 if (ret)
1608 register_menus_entry(menuPath, unix_link);
1609 HeapFree(GetProcessHeap(), 0, name);
1610 HeapFree(GetProcessHeap(), 0, menuPath);
1611 return ret;
1614 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1615 const char *descr, const char *workdir, const char *icon)
1617 const char *linkname;
1618 char *desktopPath = NULL;
1619 char *desktopDir;
1620 char *filename = NULL;
1621 BOOL ret = TRUE;
1623 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1624 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1625 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1627 linkname = strrchr(link, '/');
1628 if (linkname == NULL)
1629 linkname = link;
1630 else
1631 ++linkname;
1633 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1634 if (!desktopPath)
1636 WINE_WARN("out of memory creating menu entry\n");
1637 ret = FALSE;
1638 goto end;
1640 desktopDir = strrchr(desktopPath, '/');
1641 *desktopDir = 0;
1642 if (!create_directories(desktopPath))
1644 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1645 ret = FALSE;
1646 goto end;
1648 *desktopDir = '/';
1649 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1651 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1652 ret = FALSE;
1653 goto end;
1656 filename = heap_printf("wine/%s.desktop", link);
1657 if (!filename || !write_menu_file(unix_link, filename))
1659 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1660 ret = FALSE;
1663 end:
1664 HeapFree(GetProcessHeap(), 0, desktopPath);
1665 HeapFree(GetProcessHeap(), 0, filename);
1666 return ret;
1669 /* This escapes reserved characters in .desktop files' Exec keys. */
1670 static LPSTR escape(LPCWSTR arg)
1672 int i, j;
1673 WCHAR *escaped_string;
1674 char *utf8_string;
1676 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1677 if (escaped_string == NULL) return NULL;
1678 for (i = j = 0; arg[i]; i++)
1680 switch (arg[i])
1682 case '\\':
1683 escaped_string[j++] = '\\';
1684 escaped_string[j++] = '\\';
1685 escaped_string[j++] = '\\';
1686 escaped_string[j++] = '\\';
1687 break;
1688 case ' ':
1689 case '\t':
1690 case '\n':
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 case '(':
1704 case ')':
1705 case '`':
1706 escaped_string[j++] = '\\';
1707 escaped_string[j++] = '\\';
1708 /* fall through */
1709 default:
1710 escaped_string[j++] = arg[i];
1711 break;
1714 escaped_string[j] = 0;
1716 utf8_string = wchars_to_utf8_chars(escaped_string);
1717 if (utf8_string == NULL)
1719 WINE_ERR("out of memory\n");
1720 goto end;
1723 end:
1724 HeapFree(GetProcessHeap(), 0, escaped_string);
1725 return utf8_string;
1728 /* Return a heap-allocated copy of the unix format difference between the two
1729 * Windows-format paths.
1730 * locn is the owning location
1731 * link is within locn
1733 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1735 char *unix_locn, *unix_link;
1736 char *relative = NULL;
1738 unix_locn = wine_get_unix_file_name(locn);
1739 unix_link = wine_get_unix_file_name(link);
1740 if (unix_locn && unix_link)
1742 size_t len_unix_locn, len_unix_link;
1743 len_unix_locn = strlen (unix_locn);
1744 len_unix_link = strlen (unix_link);
1745 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1747 size_t len_rel;
1748 char *p = strrchr (unix_link + len_unix_locn, '/');
1749 p = strrchr (p, '.');
1750 if (p)
1752 *p = '\0';
1753 len_unix_link = p - unix_link;
1755 len_rel = len_unix_link - len_unix_locn;
1756 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1757 if (relative)
1759 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1763 if (!relative)
1764 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1765 HeapFree(GetProcessHeap(), 0, unix_locn);
1766 HeapFree(GetProcessHeap(), 0, unix_link);
1767 return relative;
1770 /***********************************************************************
1772 * GetLinkLocation
1774 * returns TRUE if successful
1775 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1776 * *relative will contain the address of a heap-allocated copy of the portion
1777 * of the filename that is within the specified location, in unix form
1779 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1781 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1782 DWORD len, i, r, filelen;
1783 const DWORD locations[] = {
1784 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1785 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1786 CSIDL_COMMON_STARTMENU };
1788 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1789 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1790 if (filelen==0 || filelen>MAX_PATH)
1791 return FALSE;
1793 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1795 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1796 * expand or our hardcoded list won't match.
1798 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1799 if (filelen==0 || filelen>MAX_PATH)
1800 return FALSE;
1802 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1804 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1806 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1807 continue;
1809 len = lstrlenW(buffer);
1810 if (len >= MAX_PATH)
1811 continue; /* We've just trashed memory! Hopefully we are OK */
1813 if (len > filelen || filename[len]!='\\')
1814 continue;
1815 /* do a lstrcmpinW */
1816 filename[len] = 0;
1817 r = lstrcmpiW( filename, buffer );
1818 filename[len] = '\\';
1819 if ( r )
1820 continue;
1822 /* return the remainder of the string and link type */
1823 *loc = locations[i];
1824 *relative = relative_path (filename, buffer);
1825 return (*relative != NULL);
1828 return FALSE;
1831 /* gets the target path directly or through MSI */
1832 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1833 LPWSTR szArgs, DWORD argsSize)
1835 IShellLinkDataList *dl = NULL;
1836 EXP_DARWIN_LINK *dar = NULL;
1837 HRESULT hr;
1839 szPath[0] = 0;
1840 szArgs[0] = 0;
1842 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1843 if (hr == S_OK && szPath[0])
1845 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1846 return hr;
1849 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1850 if (FAILED(hr))
1851 return hr;
1853 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1854 if (SUCCEEDED(hr))
1856 WCHAR* szCmdline;
1857 DWORD cmdSize;
1859 cmdSize=0;
1860 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1861 if (hr == ERROR_SUCCESS)
1863 cmdSize++;
1864 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1865 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1866 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1867 if (hr == ERROR_SUCCESS)
1869 WCHAR *s, *d;
1870 int bcount = 0;
1871 BOOL in_quotes = FALSE;
1873 /* Extract the application path */
1874 s=szCmdline;
1875 d=szPath;
1876 while (*s)
1878 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1880 /* skip the remaining spaces */
1881 do {
1882 s++;
1883 } while (*s==0x0009 || *s==0x0020);
1884 break;
1886 else if (*s==0x005c)
1888 /* '\\' */
1889 *d++=*s++;
1890 bcount++;
1892 else if (*s==0x0022)
1894 /* '"' */
1895 if ((bcount & 1)==0)
1897 /* Preceded by an even number of '\', this is
1898 * half that number of '\', plus a quote which
1899 * we erase.
1901 d-=bcount/2;
1902 in_quotes=!in_quotes;
1903 s++;
1905 else
1907 /* Preceded by an odd number of '\', this is
1908 * half that number of '\' followed by a '"'
1910 d=d-bcount/2-1;
1911 *d++='"';
1912 s++;
1914 bcount=0;
1916 else
1918 /* a regular character */
1919 *d++=*s++;
1920 bcount=0;
1922 if ((d-szPath) == pathSize)
1924 /* Keep processing the path till we get to the
1925 * arguments, but 'stand still'
1927 d--;
1930 /* Close the application path */
1931 *d=0;
1933 lstrcpynW(szArgs, s, argsSize);
1935 HeapFree( GetProcessHeap(), 0, szCmdline );
1937 LocalFree( dar );
1940 IShellLinkDataList_Release( dl );
1941 return hr;
1944 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1946 HRESULT hr;
1947 WCHAR *value = NULL;
1948 DWORD size = 0;
1949 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1950 if (SUCCEEDED(hr))
1952 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1953 if (value)
1955 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1956 if (FAILED(hr))
1958 HeapFree(GetProcessHeap(), 0, value);
1959 value = NULL;
1963 return value;
1966 static char *slashes_to_minuses(const char *string)
1968 int i;
1969 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1970 if (ret)
1972 for (i = 0; string[i]; i++)
1974 if (string[i] == '/')
1975 ret[i] = '-';
1976 else
1977 ret[i] = string[i];
1979 ret[i] = 0;
1980 return ret;
1982 return NULL;
1985 static BOOL next_line(FILE *file, char **line, int *size)
1987 int pos = 0;
1988 char *cr;
1989 if (*line == NULL)
1991 *size = 4096;
1992 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1994 while (*line != NULL)
1996 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1998 HeapFree(GetProcessHeap(), 0, *line);
1999 *line = NULL;
2000 if (feof(file))
2001 return TRUE;
2002 return FALSE;
2004 pos = strlen(*line);
2005 cr = strchr(*line, '\n');
2006 if (cr == NULL)
2008 char *line2;
2009 (*size) *= 2;
2010 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
2011 if (line2)
2012 *line = line2;
2013 else
2015 HeapFree(GetProcessHeap(), 0, *line);
2016 *line = NULL;
2019 else
2021 *cr = 0;
2022 return TRUE;
2025 return FALSE;
2028 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
2030 char *globs_filename = NULL;
2031 BOOL ret = TRUE;
2032 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
2033 if (globs_filename)
2035 FILE *globs_file = fopen(globs_filename, "r");
2036 if (globs_file) /* doesn't have to exist */
2038 char *line = NULL;
2039 int size = 0;
2040 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
2042 char *pos;
2043 struct xdg_mime_type *mime_type_entry = NULL;
2044 if (line[0] != '#' && (pos = strchr(line, ':')))
2046 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
2047 if (mime_type_entry)
2049 *pos = 0;
2050 mime_type_entry->mimeType = strdupA(line);
2051 mime_type_entry->glob = strdupA(pos + 1);
2052 mime_type_entry->lower_glob = strdupA(pos + 1);
2053 if (mime_type_entry->lower_glob)
2055 char *l;
2056 for (l = mime_type_entry->lower_glob; *l; l++)
2057 *l = tolower(*l);
2059 if (mime_type_entry->mimeType && mime_type_entry->glob && mime_type_entry->lower_glob)
2060 list_add_tail(mime_types, &mime_type_entry->entry);
2061 else
2063 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2064 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2065 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2066 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2067 ret = FALSE;
2070 else
2071 ret = FALSE;
2074 HeapFree(GetProcessHeap(), 0, line);
2075 fclose(globs_file);
2077 HeapFree(GetProcessHeap(), 0, globs_filename);
2079 else
2080 ret = FALSE;
2081 return ret;
2084 static void free_native_mime_types(struct list *native_mime_types)
2086 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
2088 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
2090 list_remove(&mime_type_entry->entry);
2091 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2092 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2093 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2094 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2096 HeapFree(GetProcessHeap(), 0, native_mime_types);
2099 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
2101 char *xdg_data_dirs;
2102 BOOL ret;
2104 *mime_types = NULL;
2106 xdg_data_dirs = getenv("XDG_DATA_DIRS");
2107 if (xdg_data_dirs == NULL)
2108 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
2109 else
2110 xdg_data_dirs = strdupA(xdg_data_dirs);
2112 if (xdg_data_dirs)
2114 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
2115 if (*mime_types)
2117 const char *begin;
2118 char *end;
2120 list_init(*mime_types);
2121 ret = add_mimes(xdg_data_home, *mime_types);
2122 if (ret)
2124 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
2126 *end = '\0';
2127 ret = add_mimes(begin, *mime_types);
2128 *end = ':';
2129 if (!ret)
2130 break;
2132 if (ret)
2133 ret = add_mimes(begin, *mime_types);
2136 else
2137 ret = FALSE;
2138 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
2140 else
2141 ret = FALSE;
2142 if (!ret && *mime_types)
2144 free_native_mime_types(*mime_types);
2145 *mime_types = NULL;
2147 return ret;
2150 static BOOL match_glob(struct list *native_mime_types, const char *extension,
2151 int ignoreGlobCase, char **match)
2153 #ifdef HAVE_FNMATCH
2154 struct xdg_mime_type *mime_type_entry;
2155 int matchLength = 0;
2157 *match = NULL;
2159 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
2161 const char *glob = ignoreGlobCase ? mime_type_entry->lower_glob : mime_type_entry->glob;
2162 if (fnmatch(glob, extension, 0) == 0)
2164 if (*match == NULL || matchLength < strlen(glob))
2166 *match = mime_type_entry->mimeType;
2167 matchLength = strlen(glob);
2172 if (*match != NULL)
2174 *match = strdupA(*match);
2175 if (*match == NULL)
2176 return FALSE;
2178 #else
2179 *match = NULL;
2180 #endif
2181 return TRUE;
2184 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
2185 const char *extensionA,
2186 LPCWSTR extensionW,
2187 char **mime_type)
2189 WCHAR *lower_extensionW;
2190 INT len;
2191 BOOL ret = match_glob(native_mime_types, extensionA, 0, mime_type);
2192 if (ret == FALSE || *mime_type != NULL)
2193 return ret;
2194 len = strlenW(extensionW);
2195 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
2196 if (lower_extensionW)
2198 char *lower_extensionA;
2199 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
2200 strlwrW(lower_extensionW);
2201 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
2202 if (lower_extensionA)
2204 ret = match_glob(native_mime_types, lower_extensionA, 1, mime_type);
2205 HeapFree(GetProcessHeap(), 0, lower_extensionA);
2207 else
2209 ret = FALSE;
2210 WINE_FIXME("out of memory\n");
2212 HeapFree(GetProcessHeap(), 0, lower_extensionW);
2214 else
2216 ret = FALSE;
2217 WINE_FIXME("out of memory\n");
2219 return ret;
2222 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
2224 DWORD size;
2225 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
2227 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
2228 if (ret)
2230 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
2231 return ret;
2233 HeapFree(GetProcessHeap(), 0, ret);
2235 return NULL;
2238 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
2240 WCHAR *valW = reg_get_valW(key, subkey, name);
2241 if (valW)
2243 char *val = wchars_to_utf8_chars(valW);
2244 HeapFree(GetProcessHeap(), 0, valW);
2245 return val;
2247 return NULL;
2250 static HKEY open_associations_reg_key(void)
2252 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
2253 '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};
2254 HKEY assocKey;
2255 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
2256 return assocKey;
2257 return NULL;
2260 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
2261 LPCSTR appName, LPCSTR openWithIcon)
2263 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2264 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2265 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2266 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2267 HKEY assocKey;
2268 BOOL ret;
2270 if ((assocKey = open_associations_reg_key()))
2272 CHAR *valueA;
2273 WCHAR *value;
2275 ret = FALSE;
2277 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
2278 if (!valueA || lstrcmpA(valueA, mimeType))
2279 ret = TRUE;
2280 HeapFree(GetProcessHeap(), 0, valueA);
2282 value = reg_get_valW(assocKey, extensionW, ProgIDW);
2283 if (!value || strcmpW(value, progId))
2284 ret = TRUE;
2285 HeapFree(GetProcessHeap(), 0, value);
2287 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2288 if (!valueA || lstrcmpA(valueA, appName))
2289 ret = TRUE;
2290 HeapFree(GetProcessHeap(), 0, valueA);
2292 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
2293 if ((openWithIcon && !valueA) ||
2294 (!openWithIcon && valueA) ||
2295 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
2296 ret = TRUE;
2297 HeapFree(GetProcessHeap(), 0, valueA);
2299 RegCloseKey(assocKey);
2301 else
2303 WINE_ERR("error opening associations registry key\n");
2304 ret = FALSE;
2306 return ret;
2309 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2310 LPCSTR appName, LPCSTR desktopFile, LPCSTR openWithIcon)
2312 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2313 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2314 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2315 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2316 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2317 HKEY assocKey = NULL;
2318 HKEY subkey = NULL;
2319 WCHAR *mimeTypeW = NULL;
2320 WCHAR *appNameW = NULL;
2321 WCHAR *desktopFileW = NULL;
2322 WCHAR *openWithIconW = NULL;
2324 assocKey = open_associations_reg_key();
2325 if (assocKey == NULL)
2327 WINE_ERR("could not open file associations key\n");
2328 goto done;
2331 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2333 WINE_ERR("could not create extension subkey\n");
2334 goto done;
2337 mimeTypeW = utf8_chars_to_wchars(mimeType);
2338 if (mimeTypeW == NULL)
2340 WINE_ERR("out of memory\n");
2341 goto done;
2344 appNameW = utf8_chars_to_wchars(appName);
2345 if (appNameW == NULL)
2347 WINE_ERR("out of memory\n");
2348 goto done;
2351 desktopFileW = utf8_chars_to_wchars(desktopFile);
2352 if (desktopFileW == NULL)
2354 WINE_ERR("out of memory\n");
2355 goto done;
2358 if (openWithIcon)
2360 openWithIconW = utf8_chars_to_wchars(openWithIcon);
2361 if (openWithIconW == NULL)
2363 WINE_ERR("out of memory\n");
2364 goto done;
2368 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2369 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2370 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2371 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2372 if (openWithIcon)
2373 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
2374 else
2375 RegDeleteValueW(subkey, OpenWithIconW);
2377 done:
2378 RegCloseKey(assocKey);
2379 RegCloseKey(subkey);
2380 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2381 HeapFree(GetProcessHeap(), 0, appNameW);
2382 HeapFree(GetProcessHeap(), 0, desktopFileW);
2383 HeapFree(GetProcessHeap(), 0, openWithIconW);
2386 static BOOL cleanup_associations(void)
2388 static const WCHAR openW[] = {'o','p','e','n',0};
2389 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2390 HKEY assocKey;
2391 BOOL hasChanged = FALSE;
2392 if ((assocKey = open_associations_reg_key()))
2394 int i;
2395 BOOL done = FALSE;
2396 for (i = 0; !done;)
2398 WCHAR *extensionW = NULL;
2399 DWORD size = 1024;
2400 LSTATUS ret;
2404 HeapFree(GetProcessHeap(), 0, extensionW);
2405 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2406 if (extensionW == NULL)
2408 WINE_ERR("out of memory\n");
2409 ret = ERROR_OUTOFMEMORY;
2410 break;
2412 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2413 size *= 2;
2414 } while (ret == ERROR_MORE_DATA);
2416 if (ret == ERROR_SUCCESS)
2418 WCHAR *command;
2419 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2420 if (command == NULL)
2422 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2423 if (desktopFile)
2425 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2426 remove(desktopFile);
2428 RegDeleteKeyW(assocKey, extensionW);
2429 hasChanged = TRUE;
2430 HeapFree(GetProcessHeap(), 0, desktopFile);
2432 else
2433 i++;
2434 HeapFree(GetProcessHeap(), 0, command);
2436 else
2438 if (ret != ERROR_NO_MORE_ITEMS)
2439 WINE_ERR("error %d while reading registry\n", ret);
2440 done = TRUE;
2442 HeapFree(GetProcessHeap(), 0, extensionW);
2444 RegCloseKey(assocKey);
2446 else
2447 WINE_ERR("could not open file associations key\n");
2448 return hasChanged;
2451 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2452 const char *mime_type, const char *comment)
2454 BOOL ret = FALSE;
2455 char *filename;
2457 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2458 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2460 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2461 if (filename)
2463 FILE *packageFile = fopen(filename, "w");
2464 if (packageFile)
2466 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2467 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2468 fprintf(packageFile, " <mime-type type=\"");
2469 write_xml_text(packageFile, mime_type);
2470 fprintf(packageFile, "\">\n");
2471 fprintf(packageFile, " <glob pattern=\"*");
2472 write_xml_text(packageFile, dot_extension);
2473 fprintf(packageFile, "\"/>\n");
2474 if (comment)
2476 fprintf(packageFile, " <comment>");
2477 write_xml_text(packageFile, comment);
2478 fprintf(packageFile, "</comment>\n");
2480 fprintf(packageFile, " </mime-type>\n");
2481 fprintf(packageFile, "</mime-info>\n");
2482 ret = TRUE;
2483 fclose(packageFile);
2485 else
2486 WINE_ERR("error writing file %s\n", filename);
2487 HeapFree(GetProcessHeap(), 0, filename);
2489 else
2490 WINE_ERR("out of memory\n");
2491 return ret;
2494 static BOOL is_extension_blacklisted(LPCWSTR extension)
2496 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2497 static const WCHAR comW[] = {'.','c','o','m',0};
2498 static const WCHAR exeW[] = {'.','e','x','e',0};
2499 static const WCHAR msiW[] = {'.','m','s','i',0};
2501 if (!strcmpiW(extension, comW) ||
2502 !strcmpiW(extension, exeW) ||
2503 !strcmpiW(extension, msiW))
2504 return TRUE;
2505 return FALSE;
2508 static const char* get_special_mime_type(LPCWSTR extension)
2510 static const WCHAR lnkW[] = {'.','l','n','k',0};
2511 if (!strcmpiW(extension, lnkW))
2512 return "application/x-ms-shortcut";
2513 return NULL;
2516 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2517 const char *friendlyAppName, const char *mimeType,
2518 const char *progId, const char *openWithIcon)
2520 BOOL ret = FALSE;
2521 FILE *desktop;
2523 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2524 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2525 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2527 desktop = fopen(desktopPath, "w");
2528 if (desktop)
2530 fprintf(desktop, "[Desktop Entry]\n");
2531 fprintf(desktop, "Type=Application\n");
2532 fprintf(desktop, "Name=%s\n", friendlyAppName);
2533 fprintf(desktop, "MimeType=%s;\n", mimeType);
2534 fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId);
2535 fprintf(desktop, "NoDisplay=true\n");
2536 fprintf(desktop, "StartupNotify=true\n");
2537 if (openWithIcon)
2538 fprintf(desktop, "Icon=%s\n", openWithIcon);
2539 ret = TRUE;
2540 fclose(desktop);
2542 else
2543 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2544 return ret;
2547 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2549 static const WCHAR openW[] = {'o','p','e','n',0};
2550 struct wine_rb_tree mimeProgidTree;
2551 struct list *nativeMimeTypes = NULL;
2552 LSTATUS ret = 0;
2553 int i;
2554 BOOL hasChanged = FALSE;
2556 if (wine_rb_init(&mimeProgidTree, &winemenubuilder_rb_functions))
2558 WINE_ERR("wine_rb_init failed\n");
2559 return FALSE;
2561 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2563 WINE_ERR("could not build native MIME types\n");
2564 return FALSE;
2567 for (i = 0; ; i++)
2569 WCHAR *extensionW = NULL;
2570 DWORD size = 1024;
2574 HeapFree(GetProcessHeap(), 0, extensionW);
2575 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2576 if (extensionW == NULL)
2578 WINE_ERR("out of memory\n");
2579 ret = ERROR_OUTOFMEMORY;
2580 break;
2582 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2583 size *= 2;
2584 } while (ret == ERROR_MORE_DATA);
2586 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2588 char *extensionA = NULL;
2589 WCHAR *commandW = NULL;
2590 WCHAR *executableW = NULL;
2591 char *openWithIconA = NULL;
2592 WCHAR *friendlyDocNameW = NULL;
2593 char *friendlyDocNameA = NULL;
2594 WCHAR *iconW = NULL;
2595 char *iconA = NULL;
2596 WCHAR *contentTypeW = NULL;
2597 char *mimeTypeA = NULL;
2598 WCHAR *friendlyAppNameW = NULL;
2599 char *friendlyAppNameA = NULL;
2600 WCHAR *progIdW = NULL;
2601 char *progIdA = NULL;
2602 char *mimeProgId = NULL;
2604 extensionA = wchars_to_utf8_chars(strlwrW(extensionW));
2605 if (extensionA == NULL)
2607 WINE_ERR("out of memory\n");
2608 goto end;
2611 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2612 if (friendlyDocNameW)
2614 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2615 if (friendlyDocNameA == NULL)
2617 WINE_ERR("out of memory\n");
2618 goto end;
2622 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2624 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2625 if (contentTypeW)
2626 strlwrW(contentTypeW);
2628 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2629 goto end;
2631 if (mimeTypeA == NULL)
2633 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2634 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2635 else if ((get_special_mime_type(extensionW)))
2636 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2637 else
2638 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2640 if (mimeTypeA != NULL)
2642 /* GNOME seems to ignore the <icon> tag in MIME packages,
2643 * and the default name is more intuitive anyway.
2645 if (iconW)
2647 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2648 if (flattened_mime)
2650 int index = 0;
2651 WCHAR *comma = strrchrW(iconW, ',');
2652 if (comma)
2654 *comma = 0;
2655 index = atoiW(comma + 1);
2657 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2658 HeapFree(GetProcessHeap(), 0, flattened_mime);
2662 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2663 hasChanged = TRUE;
2665 else
2667 WINE_FIXME("out of memory\n");
2668 goto end;
2672 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2673 if (commandW == NULL)
2674 /* no command => no application is associated */
2675 goto end;
2677 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2678 if (executableW)
2679 openWithIconA = extract_icon(executableW, 0, NULL, FALSE);
2681 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, openW);
2682 if (friendlyAppNameW)
2684 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2685 if (friendlyAppNameA == NULL)
2687 WINE_ERR("out of memory\n");
2688 goto end;
2691 else
2693 friendlyAppNameA = heap_printf("A Wine application");
2694 if (friendlyAppNameA == NULL)
2696 WINE_ERR("out of memory\n");
2697 goto end;
2701 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2702 if (progIdW)
2704 progIdA = escape(progIdW);
2705 if (progIdA == NULL)
2707 WINE_ERR("out of memory\n");
2708 goto end;
2711 else
2712 goto end; /* no progID => not a file type association */
2714 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2715 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2716 if (mimeProgId)
2718 struct rb_string_entry *entry;
2719 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2721 HeapFree(GetProcessHeap(), 0, mimeProgId);
2722 goto end;
2724 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2725 if (!entry)
2727 WINE_ERR("out of memory allocating rb_string_entry\n");
2728 goto end;
2730 entry->string = mimeProgId;
2731 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2733 WINE_ERR("error updating rb tree\n");
2734 goto end;
2738 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, openWithIconA))
2740 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2741 if (desktopPath)
2743 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2745 hasChanged = TRUE;
2746 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, desktopPath, openWithIconA);
2748 HeapFree(GetProcessHeap(), 0, desktopPath);
2752 end:
2753 HeapFree(GetProcessHeap(), 0, extensionA);
2754 HeapFree(GetProcessHeap(), 0, commandW);
2755 HeapFree(GetProcessHeap(), 0, executableW);
2756 HeapFree(GetProcessHeap(), 0, openWithIconA);
2757 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2758 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2759 HeapFree(GetProcessHeap(), 0, iconW);
2760 HeapFree(GetProcessHeap(), 0, iconA);
2761 HeapFree(GetProcessHeap(), 0, contentTypeW);
2762 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2763 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2764 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2765 HeapFree(GetProcessHeap(), 0, progIdW);
2766 HeapFree(GetProcessHeap(), 0, progIdA);
2768 HeapFree(GetProcessHeap(), 0, extensionW);
2769 if (ret != ERROR_SUCCESS)
2770 break;
2773 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2774 free_native_mime_types(nativeMimeTypes);
2775 return hasChanged;
2778 static char *get_start_exe_path(void)
2780 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2781 '\\','s','t','a','r','t','.','e','x','e',0};
2782 WCHAR start_path[MAX_PATH];
2783 GetWindowsDirectoryW(start_path, MAX_PATH);
2784 lstrcatW(start_path, startW);
2785 return escape(start_path);
2788 static char* escape_unix_link_arg(LPCSTR unix_link)
2790 char *ret = NULL;
2791 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2792 if (unix_linkW)
2794 char *escaped_lnk = escape(unix_linkW);
2795 if (escaped_lnk)
2797 ret = heap_printf("/Unix %s", escaped_lnk);
2798 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2800 HeapFree(GetProcessHeap(), 0, unix_linkW);
2802 return ret;
2805 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2807 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2808 '\\','s','t','a','r','t','.','e','x','e',0};
2809 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2810 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2811 WCHAR szTmp[INFOTIPSIZE];
2812 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2813 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2814 int iIconId = 0, r = -1;
2815 DWORD csidl = -1;
2816 HANDLE hsem = NULL;
2817 char *unix_link = NULL;
2818 char *start_path = NULL;
2820 if ( !link )
2822 WINE_ERR("Link name is null\n");
2823 return FALSE;
2826 if( !GetLinkLocation( link, &csidl, &link_name ) )
2828 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2829 return TRUE;
2831 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2833 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2834 return TRUE;
2836 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2838 szTmp[0] = 0;
2839 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2840 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2841 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2843 szTmp[0] = 0;
2844 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2845 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2846 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2848 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2849 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2850 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2851 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2853 szTmp[0] = 0;
2854 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2855 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2856 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2858 if( !szPath[0] )
2860 LPITEMIDLIST pidl = NULL;
2861 IShellLinkW_GetIDList( sl, &pidl );
2862 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2863 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2866 /* extract the icon */
2867 if( szIconPath[0] )
2868 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2869 else
2870 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2872 /* fail - try once again after parent process exit */
2873 if( !icon_name )
2875 if (bWait)
2877 WINE_WARN("Unable to extract icon, deferring.\n");
2878 goto cleanup;
2880 WINE_ERR("failed to extract icon from %s\n",
2881 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2884 unix_link = wine_get_unix_file_name(link);
2885 if (unix_link == NULL)
2887 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2888 goto cleanup;
2891 /* check the path */
2892 if( szPath[0] )
2894 static const WCHAR exeW[] = {'.','e','x','e',0};
2895 WCHAR *p;
2897 /* check for .exe extension */
2898 if (!(p = strrchrW( szPath, '.' )) ||
2899 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2900 lstrcmpiW( p, exeW ))
2902 /* Not .exe - use 'start.exe' to launch this file */
2903 p = szArgs + lstrlenW(szPath) + 2;
2904 if (szArgs[0])
2906 p[0] = ' ';
2907 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2908 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2910 else
2911 p[0] = 0;
2913 szArgs[0] = '"';
2914 lstrcpyW(szArgs + 1, szPath);
2915 p[-1] = '"';
2917 GetWindowsDirectoryW(szPath, MAX_PATH);
2918 lstrcatW(szPath, startW);
2921 /* convert app working dir */
2922 if (szWorkDir[0])
2923 work_dir = wine_get_unix_file_name( szWorkDir );
2925 else
2927 /* if there's no path... try run the link itself */
2928 lstrcpynW(szArgs, link, MAX_PATH);
2929 GetWindowsDirectoryW(szPath, MAX_PATH);
2930 lstrcatW(szPath, startW);
2933 /* escape the path and parameters */
2934 escaped_path = escape(szPath);
2935 escaped_args = escape(szArgs);
2936 description = wchars_to_utf8_chars(szDescription);
2937 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2939 WINE_ERR("out of memory allocating/escaping parameters\n");
2940 goto cleanup;
2943 start_path = get_start_exe_path();
2944 if (start_path == NULL)
2946 WINE_ERR("out of memory\n");
2947 goto cleanup;
2950 /* building multiple menus concurrently has race conditions */
2951 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2952 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2954 WINE_ERR("failed wait for semaphore\n");
2955 goto cleanup;
2958 if (in_desktop_dir(csidl))
2960 char *location;
2961 const char *lastEntry;
2962 lastEntry = strrchr(link_name, '/');
2963 if (lastEntry == NULL)
2964 lastEntry = link_name;
2965 else
2966 ++lastEntry;
2967 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2968 if (location)
2970 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2972 char *link_arg = escape_unix_link_arg(unix_link);
2973 if (link_arg)
2975 r = !write_desktop_entry(unix_link, location, lastEntry,
2976 start_path, link_arg, description, work_dir, icon_name);
2977 HeapFree(GetProcessHeap(), 0, link_arg);
2980 else
2981 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2982 if (r == 0)
2983 chmod(location, 0755);
2984 HeapFree(GetProcessHeap(), 0, location);
2987 else
2989 char *link_arg = escape_unix_link_arg(unix_link);
2990 if (link_arg)
2992 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name);
2993 HeapFree(GetProcessHeap(), 0, link_arg);
2997 ReleaseSemaphore( hsem, 1, NULL );
2999 cleanup:
3000 if (hsem) CloseHandle( hsem );
3001 HeapFree( GetProcessHeap(), 0, icon_name );
3002 HeapFree( GetProcessHeap(), 0, work_dir );
3003 HeapFree( GetProcessHeap(), 0, link_name );
3004 HeapFree( GetProcessHeap(), 0, escaped_args );
3005 HeapFree( GetProcessHeap(), 0, escaped_path );
3006 HeapFree( GetProcessHeap(), 0, description );
3007 HeapFree( GetProcessHeap(), 0, unix_link );
3008 HeapFree( GetProcessHeap(), 0, start_path );
3010 if (r && !bWait)
3011 WINE_ERR("failed to build the menu\n" );
3013 return ( r == 0 );
3016 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
3018 char *link_name = NULL, *icon_name = NULL;
3019 DWORD csidl = -1;
3020 LPWSTR urlPath = NULL;
3021 char *escaped_urlPath = NULL;
3022 HRESULT hr;
3023 HANDLE hSem = NULL;
3024 BOOL ret = TRUE;
3025 int r = -1;
3026 char *unix_link = NULL;
3027 IPropertySetStorage *pPropSetStg;
3028 IPropertyStorage *pPropStg;
3029 PROPSPEC ps[2];
3030 PROPVARIANT pv[2];
3031 char *start_path = NULL;
3032 BOOL has_icon = FALSE;
3034 if ( !link )
3036 WINE_ERR("Link name is null\n");
3037 return TRUE;
3040 if( !GetLinkLocation( link, &csidl, &link_name ) )
3042 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
3043 return TRUE;
3045 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
3047 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3048 ret = TRUE;
3049 goto cleanup;
3051 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
3053 hr = url->lpVtbl->GetURL(url, &urlPath);
3054 if (FAILED(hr))
3056 ret = TRUE;
3057 goto cleanup;
3059 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
3061 unix_link = wine_get_unix_file_name(link);
3062 if (unix_link == NULL)
3064 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
3065 goto cleanup;
3068 escaped_urlPath = escape(urlPath);
3069 if (escaped_urlPath == NULL)
3071 WINE_ERR("couldn't escape url, out of memory\n");
3072 goto cleanup;
3075 start_path = get_start_exe_path();
3076 if (start_path == NULL)
3078 WINE_ERR("out of memory\n");
3079 goto cleanup;
3082 ps[0].ulKind = PRSPEC_PROPID;
3083 ps[0].u.propid = PID_IS_ICONFILE;
3084 ps[1].ulKind = PRSPEC_PROPID;
3085 ps[1].u.propid = PID_IS_ICONINDEX;
3087 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
3088 if (SUCCEEDED(hr))
3090 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
3091 if (SUCCEEDED(hr))
3093 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
3094 if (SUCCEEDED(hr))
3096 if (pv[0].vt == VT_LPWSTR && pv[0].u.pwszVal && pv[0].u.pwszVal[0])
3098 has_icon = TRUE;
3099 icon_name = extract_icon( pv[0].u.pwszVal, pv[1].u.iVal, NULL, bWait );
3101 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);
3103 PropVariantClear(&pv[0]);
3104 PropVariantClear(&pv[1]);
3106 IPropertyStorage_Release(pPropStg);
3108 IPropertySetStorage_Release(pPropSetStg);
3111 /* fail - try once again after parent process exit */
3112 if( has_icon && !icon_name )
3114 if (bWait)
3116 WINE_WARN("Unable to extract icon, deferring.\n");
3117 ret = FALSE;
3118 goto cleanup;
3120 WINE_ERR("failed to extract icon from %s\n",
3121 wine_dbgstr_w( pv[0].u.pwszVal ));
3124 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3125 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3127 WINE_ERR("failed wait for semaphore\n");
3128 goto cleanup;
3130 if (in_desktop_dir(csidl))
3132 char *location;
3133 const char *lastEntry;
3134 lastEntry = strrchr(link_name, '/');
3135 if (lastEntry == NULL)
3136 lastEntry = link_name;
3137 else
3138 ++lastEntry;
3139 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
3140 if (location)
3142 r = !write_desktop_entry(NULL, location, lastEntry, start_path, escaped_urlPath, NULL, NULL, icon_name);
3143 if (r == 0)
3144 chmod(location, 0755);
3145 HeapFree(GetProcessHeap(), 0, location);
3148 else
3149 r = !write_menu_entry(unix_link, link_name, start_path, escaped_urlPath, NULL, NULL, icon_name);
3150 ret = (r == 0);
3151 ReleaseSemaphore(hSem, 1, NULL);
3153 cleanup:
3154 if (hSem)
3155 CloseHandle(hSem);
3156 HeapFree( GetProcessHeap(), 0, icon_name );
3157 HeapFree(GetProcessHeap(), 0, link_name);
3158 CoTaskMemFree( urlPath );
3159 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
3160 HeapFree(GetProcessHeap(), 0, unix_link);
3161 return ret;
3164 static BOOL WaitForParentProcess( void )
3166 PROCESSENTRY32 procentry;
3167 HANDLE hsnapshot = NULL, hprocess = NULL;
3168 DWORD ourpid = GetCurrentProcessId();
3169 BOOL ret = FALSE, rc;
3171 WINE_TRACE("Waiting for parent process\n");
3172 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
3173 INVALID_HANDLE_VALUE)
3175 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3176 goto done;
3179 procentry.dwSize = sizeof(PROCESSENTRY32);
3180 rc = Process32First( hsnapshot, &procentry );
3181 while (rc)
3183 if (procentry.th32ProcessID == ourpid) break;
3184 rc = Process32Next( hsnapshot, &procentry );
3186 if (!rc)
3188 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
3189 goto done;
3192 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
3193 NULL)
3195 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
3196 GetLastError());
3197 goto done;
3200 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
3201 ret = TRUE;
3202 else
3203 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3205 done:
3206 if (hprocess) CloseHandle( hprocess );
3207 if (hsnapshot) CloseHandle( hsnapshot );
3208 return ret;
3211 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
3213 IShellLinkW *sl;
3214 IPersistFile *pf;
3215 HRESULT r;
3216 WCHAR fullname[MAX_PATH];
3217 DWORD len;
3219 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
3221 if( !linkname[0] )
3223 WINE_ERR("link name missing\n");
3224 return FALSE;
3227 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
3228 if (len==0 || len>MAX_PATH)
3230 WINE_ERR("couldn't get full path of link file\n");
3231 return FALSE;
3234 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3235 &IID_IShellLinkW, (LPVOID *) &sl );
3236 if( FAILED( r ) )
3238 WINE_ERR("No IID_IShellLink\n");
3239 return FALSE;
3242 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
3243 if( FAILED( r ) )
3245 WINE_ERR("No IID_IPersistFile\n");
3246 return FALSE;
3249 r = IPersistFile_Load( pf, fullname, STGM_READ );
3250 if( SUCCEEDED( r ) )
3252 /* If something fails (eg. Couldn't extract icon)
3253 * wait for parent process and try again
3255 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
3257 WaitForParentProcess();
3258 InvokeShellLinker( sl, fullname, FALSE );
3261 else
3263 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
3266 IPersistFile_Release( pf );
3267 IShellLinkW_Release( sl );
3269 return !r;
3272 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
3274 IUniformResourceLocatorW *url;
3275 IPersistFile *pf;
3276 HRESULT r;
3277 WCHAR fullname[MAX_PATH];
3278 DWORD len;
3280 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
3282 if( !urlname[0] )
3284 WINE_ERR("URL name missing\n");
3285 return FALSE;
3288 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
3289 if (len==0 || len>MAX_PATH)
3291 WINE_ERR("couldn't get full path of URL file\n");
3292 return FALSE;
3295 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
3296 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
3297 if( FAILED( r ) )
3299 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3300 return FALSE;
3303 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
3304 if( FAILED( r ) )
3306 WINE_ERR("No IID_IPersistFile\n");
3307 return FALSE;
3309 r = IPersistFile_Load( pf, fullname, STGM_READ );
3310 if( SUCCEEDED( r ) )
3312 /* If something fails (eg. Couldn't extract icon)
3313 * wait for parent process and try again
3315 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
3317 WaitForParentProcess();
3318 InvokeShellLinkerForURL( url, fullname, FALSE );
3322 IPersistFile_Release( pf );
3323 url->lpVtbl->Release( url );
3325 return !r;
3328 static void RefreshFileTypeAssociations(void)
3330 HANDLE hSem = NULL;
3331 char *mime_dir = NULL;
3332 char *packages_dir = NULL;
3333 char *applications_dir = NULL;
3334 BOOL hasChanged;
3336 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3337 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3339 WINE_ERR("failed wait for semaphore\n");
3340 CloseHandle(hSem);
3341 hSem = NULL;
3342 goto end;
3345 mime_dir = heap_printf("%s/mime", xdg_data_dir);
3346 if (mime_dir == NULL)
3348 WINE_ERR("out of memory\n");
3349 goto end;
3351 create_directories(mime_dir);
3353 packages_dir = heap_printf("%s/packages", mime_dir);
3354 if (packages_dir == NULL)
3356 WINE_ERR("out of memory\n");
3357 goto end;
3359 create_directories(packages_dir);
3361 applications_dir = heap_printf("%s/applications", xdg_data_dir);
3362 if (applications_dir == NULL)
3364 WINE_ERR("out of memory\n");
3365 goto end;
3367 create_directories(applications_dir);
3369 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3370 hasChanged |= cleanup_associations();
3371 if (hasChanged)
3373 const char *argv[3];
3375 argv[0] = "update-mime-database";
3376 argv[1] = mime_dir;
3377 argv[2] = NULL;
3378 _spawnvp( _P_DETACH, argv[0], argv );
3380 argv[0] = "update-desktop-database";
3381 argv[1] = applications_dir;
3382 _spawnvp( _P_DETACH, argv[0], argv );
3385 end:
3386 if (hSem)
3388 ReleaseSemaphore(hSem, 1, NULL);
3389 CloseHandle(hSem);
3391 HeapFree(GetProcessHeap(), 0, mime_dir);
3392 HeapFree(GetProcessHeap(), 0, packages_dir);
3393 HeapFree(GetProcessHeap(), 0, applications_dir);
3396 static void cleanup_menus(void)
3398 HKEY hkey;
3400 hkey = open_menus_reg_key();
3401 if (hkey)
3403 int i;
3404 LSTATUS lret = ERROR_SUCCESS;
3405 for (i = 0; lret == ERROR_SUCCESS; )
3407 WCHAR *value = NULL;
3408 WCHAR *data = NULL;
3409 DWORD valueSize = 4096;
3410 DWORD dataSize = 4096;
3411 while (1)
3413 lret = ERROR_OUTOFMEMORY;
3414 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3415 if (value == NULL)
3416 break;
3417 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3418 if (data == NULL)
3419 break;
3420 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3421 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
3422 break;
3423 valueSize *= 2;
3424 dataSize *= 2;
3425 HeapFree(GetProcessHeap(), 0, value);
3426 HeapFree(GetProcessHeap(), 0, data);
3427 value = data = NULL;
3429 if (lret == ERROR_SUCCESS)
3431 char *unix_file;
3432 char *windows_file;
3433 unix_file = wchars_to_unix_chars(value);
3434 windows_file = wchars_to_unix_chars(data);
3435 if (unix_file != NULL && windows_file != NULL)
3437 struct stat filestats;
3438 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3440 WINE_TRACE("removing menu related file %s\n", unix_file);
3441 remove(unix_file);
3442 RegDeleteValueW(hkey, value);
3444 else
3445 i++;
3447 else
3449 WINE_ERR("out of memory enumerating menus\n");
3450 lret = ERROR_OUTOFMEMORY;
3452 HeapFree(GetProcessHeap(), 0, unix_file);
3453 HeapFree(GetProcessHeap(), 0, windows_file);
3455 else if (lret != ERROR_NO_MORE_ITEMS)
3456 WINE_ERR("error %d reading registry\n", lret);
3457 HeapFree(GetProcessHeap(), 0, value);
3458 HeapFree(GetProcessHeap(), 0, data);
3460 RegCloseKey(hkey);
3462 else
3463 WINE_ERR("error opening registry key, menu cleanup failed\n");
3466 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3468 char *utf8lnkPath = NULL;
3469 char *utf8OutputPath = NULL;
3470 WCHAR *winLnkPath = NULL;
3471 IShellLinkW *shellLink = NULL;
3472 IPersistFile *persistFile = NULL;
3473 WCHAR szTmp[MAX_PATH];
3474 WCHAR szPath[MAX_PATH];
3475 WCHAR szArgs[INFOTIPSIZE];
3476 WCHAR szIconPath[MAX_PATH];
3477 int iconId;
3478 IStream *stream = NULL;
3479 HRESULT hr;
3481 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3482 if (utf8lnkPath == NULL)
3484 WINE_ERR("out of memory converting paths\n");
3485 goto end;
3488 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3489 if (utf8OutputPath == NULL)
3491 WINE_ERR("out of memory converting paths\n");
3492 goto end;
3495 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3496 if (winLnkPath == NULL)
3498 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3499 goto end;
3502 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3503 &IID_IShellLinkW, (LPVOID*)&shellLink);
3504 if (FAILED(hr))
3506 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3507 goto end;
3510 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3511 if (FAILED(hr))
3513 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3514 goto end;
3517 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3518 if (FAILED(hr))
3520 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3521 goto end;
3524 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3525 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3526 szTmp[0] = 0;
3527 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3528 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3530 if(!szPath[0])
3532 LPITEMIDLIST pidl = NULL;
3533 IShellLinkW_GetIDList(shellLink, &pidl);
3534 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3535 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3538 if (szIconPath[0])
3540 hr = open_icon(szIconPath, iconId, FALSE, &stream);
3541 if (SUCCEEDED(hr))
3542 hr = write_native_icon(stream, utf8OutputPath, NULL);
3544 else
3546 hr = open_icon(szPath, iconId, FALSE, &stream);
3547 if (SUCCEEDED(hr))
3548 hr = write_native_icon(stream, utf8OutputPath, NULL);
3551 end:
3552 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3553 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3554 HeapFree(GetProcessHeap(), 0, winLnkPath);
3555 if (shellLink != NULL)
3556 IShellLinkW_Release(shellLink);
3557 if (persistFile != NULL)
3558 IPersistFile_Release(persistFile);
3559 if (stream != NULL)
3560 IStream_Release(stream);
3563 static WCHAR *next_token( LPWSTR *p )
3565 LPWSTR token = NULL, t = *p;
3567 if( !t )
3568 return NULL;
3570 while( t && !token )
3572 switch( *t )
3574 case ' ':
3575 t++;
3576 continue;
3577 case '"':
3578 /* unquote the token */
3579 token = ++t;
3580 t = strchrW( token, '"' );
3581 if( t )
3582 *t++ = 0;
3583 break;
3584 case 0:
3585 t = NULL;
3586 break;
3587 default:
3588 token = t;
3589 t = strchrW( token, ' ' );
3590 if( t )
3591 *t++ = 0;
3592 break;
3595 *p = t;
3596 return token;
3599 static BOOL init_xdg(void)
3601 WCHAR shellDesktopPath[MAX_PATH];
3602 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3603 if (SUCCEEDED(hr))
3604 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3605 if (xdg_desktop_dir == NULL)
3607 WINE_ERR("error looking up the desktop directory\n");
3608 return FALSE;
3611 if (getenv("XDG_CONFIG_HOME"))
3612 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3613 else
3614 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3615 if (xdg_config_dir)
3617 create_directories(xdg_config_dir);
3618 if (getenv("XDG_DATA_HOME"))
3619 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3620 else
3621 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3622 if (xdg_data_dir)
3624 char *buffer;
3625 create_directories(xdg_data_dir);
3626 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3627 if (buffer)
3629 mkdir(buffer, 0777);
3630 HeapFree(GetProcessHeap(), 0, buffer);
3632 return TRUE;
3634 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3636 WINE_ERR("out of memory\n");
3637 return FALSE;
3640 /***********************************************************************
3642 * wWinMain
3644 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3646 static const WCHAR dash_aW[] = {'-','a',0};
3647 static const WCHAR dash_rW[] = {'-','r',0};
3648 static const WCHAR dash_tW[] = {'-','t',0};
3649 static const WCHAR dash_uW[] = {'-','u',0};
3650 static const WCHAR dash_wW[] = {'-','w',0};
3652 LPWSTR token = NULL, p;
3653 BOOL bWait = FALSE;
3654 BOOL bURL = FALSE;
3655 HRESULT hr;
3656 int ret = 0;
3658 if (!init_xdg())
3659 return 1;
3661 hr = CoInitialize(NULL);
3662 if (FAILED(hr))
3664 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3665 return 1;
3668 for( p = cmdline; p && *p; )
3670 token = next_token( &p );
3671 if( !token )
3672 break;
3673 if( !strcmpW( token, dash_aW ) )
3675 RefreshFileTypeAssociations();
3676 continue;
3678 if( !strcmpW( token, dash_rW ) )
3680 cleanup_menus();
3681 continue;
3683 if( !strcmpW( token, dash_wW ) )
3684 bWait = TRUE;
3685 else if ( !strcmpW( token, dash_uW ) )
3686 bURL = TRUE;
3687 else if ( !strcmpW( token, dash_tW ) )
3689 WCHAR *lnkFile = next_token( &p );
3690 if (lnkFile)
3692 WCHAR *outputFile = next_token( &p );
3693 if (outputFile)
3694 thumbnail_lnk(lnkFile, outputFile);
3697 else if( token[0] == '-' )
3699 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3701 else
3703 BOOL bRet;
3705 if (bURL)
3706 bRet = Process_URL( token, bWait );
3707 else
3708 bRet = Process_Link( token, bWait );
3709 if (!bRet)
3711 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3712 ret = 1;
3717 CoUninitialize();
3718 return ret;