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.
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
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
53 * Clean up fd.o menu icons and .directory files when the menu is deleted
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
61 * Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
62 * that write associations there won't associate (#17019).
66 #include "wine/port.h"
93 #include "wine/unicode.h"
94 #include "wine/debug.h"
95 #include "wine/library.h"
96 #include "wine/list.h"
97 #include "wine/rbtree.h"
99 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
101 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
102 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
103 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
104 (csidl)==CSIDL_COMMON_STARTMENU)
106 /* link file formats */
108 #include "pshpack1.h"
127 GRPICONDIRENTRY idEntries[1];
165 struct rb_string_entry
168 struct wine_rb_entry entry;
171 DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
173 static char *xdg_config_dir;
174 static char *xdg_data_dir;
175 static char *xdg_desktop_dir;
177 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra);
178 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream);
180 /* Utility routines */
181 static unsigned short crc16(const char* string)
183 unsigned short crc = 0;
186 for (i = 0; string[i] != 0; i++)
189 for (j = 0; j < 8; c >>= 1, j++)
191 xor_poly = (c ^ crc) & 1;
200 static char *strdupA( const char *str )
204 if (!str) return NULL;
205 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
209 static char* heap_printf(const char *format, ...)
216 va_start(args, format);
219 buffer = HeapAlloc(GetProcessHeap(), 0, size);
222 n = vsnprintf(buffer, size, format, args);
229 HeapFree(GetProcessHeap(), 0, buffer);
232 if (!buffer) return NULL;
233 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
234 if (!ret) ret = buffer;
238 static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
240 const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);
242 return strcmp((char*)key, t->string);
245 static void *winemenubuilder_rb_alloc(size_t size)
247 return HeapAlloc(GetProcessHeap(), 0, size);
250 static void *winemenubuilder_rb_realloc(void *ptr, size_t size)
252 return HeapReAlloc(GetProcessHeap(), 0, ptr, size);
255 static void winemenubuilder_rb_free(void *ptr)
257 HeapFree(GetProcessHeap(), 0, ptr);
260 static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
262 struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
263 HeapFree(GetProcessHeap(), 0, t->string);
264 HeapFree(GetProcessHeap(), 0, t);
267 static const struct wine_rb_functions winemenubuilder_rb_functions =
269 winemenubuilder_rb_alloc,
270 winemenubuilder_rb_realloc,
271 winemenubuilder_rb_free,
272 winemenubuilder_rb_string_compare,
275 static void write_xml_text(FILE *file, const char *text)
278 for (i = 0; text[i]; i++)
281 fputs("&", file);
282 else if (text[i] == '<')
284 else if (text[i] == '>')
286 else if (text[i] == '\'')
287 fputs("'", file);
288 else if (text[i] == '"')
289 fputs(""", file);
291 fputc(text[i], file);
295 static BOOL create_directories(char *directory)
300 for (i = 0; directory[i]; i++)
302 if (i > 0 && directory[i] == '/')
305 mkdir(directory, 0777);
309 if (mkdir(directory, 0777) && errno != EEXIST)
315 static char* wchars_to_utf8_chars(LPCWSTR string)
318 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
319 ret = HeapAlloc(GetProcessHeap(), 0, size);
321 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
325 static char* wchars_to_unix_chars(LPCWSTR string)
328 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
329 ret = HeapAlloc(GetProcessHeap(), 0, size);
331 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
335 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
338 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
339 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
341 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
345 /* Icon extraction routines
347 * FIXME: should use PrivateExtractIcons and friends
348 * FIXME: should not use stdio
351 static HRESULT convert_to_native_icon(IStream *icoFile, int *indeces, int numIndeces,
352 const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
354 WCHAR *dosOutputFileName = NULL;
355 IWICImagingFactory *factory = NULL;
356 IWICBitmapDecoder *decoder = NULL;
357 IWICBitmapEncoder *encoder = NULL;
358 IStream *outputFile = NULL;
362 dosOutputFileName = wine_get_dos_file_name(outputFileName);
363 if (dosOutputFileName == NULL)
365 WINE_ERR("error converting %s to DOS file name\n", outputFileName);
368 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
369 &IID_IWICImagingFactory, (void**)&factory);
372 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
375 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
376 WICDecodeMetadataCacheOnDemand, &decoder);
379 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
382 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
383 &IID_IWICBitmapEncoder, (void**)&encoder);
386 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
389 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
392 WINE_ERR("error 0x%08X creating output file\n", hr);
395 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, GENERIC_WRITE);
398 WINE_ERR("error 0x%08X initializing encoder\n", hr);
402 for (i = 0; i < numIndeces; i++)
404 IWICBitmapFrameDecode *sourceFrame = NULL;
405 IWICBitmapSource *sourceBitmap = NULL;
406 IWICBitmapFrameEncode *dstFrame = NULL;
407 IPropertyBag2 *options = NULL;
410 hr = IWICBitmapDecoder_GetFrame(decoder, indeces[i], &sourceFrame);
413 WINE_ERR("error 0x%08X getting frame %d\n", hr, indeces[i]);
416 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
419 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
422 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
425 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
428 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
431 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
434 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
437 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
440 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
443 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
446 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
449 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
452 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
455 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
458 hr = IWICBitmapFrameEncode_Commit(dstFrame);
461 WINE_ERR("error 0x%08X committing frame\n", hr);
466 IWICBitmapFrameDecode_Release(sourceFrame);
468 IWICBitmapSource_Release(sourceBitmap);
470 IWICBitmapFrameEncode_Release(dstFrame);
473 hr = IWICBitmapEncoder_Commit(encoder);
476 WINE_ERR("error 0x%08X committing encoder\n", hr);
481 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
483 IWICImagingFactory_Release(factory);
485 IWICBitmapDecoder_Release(decoder);
487 IWICBitmapEncoder_Release(encoder);
489 IStream_Release(outputFile);
493 static IStream *add_module_icons_to_stream(HMODULE hModule, GRPICONDIR *grpIconDir)
496 SIZE_T iconsSize = 0;
498 ICONDIRENTRY *iconDirEntries = NULL;
499 IStream *stream = NULL;
504 int validEntries = 0;
507 for (i = 0; i < grpIconDir->idCount; i++)
508 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
509 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
512 WINE_ERR("out of memory allocating icon\n");
516 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
517 if (iconDirEntries == NULL)
519 WINE_ERR("out of memory allocating icon dir entries\n");
523 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
526 WINE_ERR("error creating icon stream\n");
531 for (i = 0; i < grpIconDir->idCount; i++)
534 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
535 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
538 if ((hResData = LoadResource(hModule, hResInfo)))
541 if ((pIcon = LockResource(hResData)))
543 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
544 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
545 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
546 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
547 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
548 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
549 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
550 iconDirEntries[validEntries].dwImageOffset = iconOffset;
552 memcpy(&icons[iconOffset], pIcon, grpIconDir->idEntries[i].dwBytesInRes);
553 iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
555 FreeResource(hResData);
560 if (validEntries == 0)
562 WINE_ERR("no valid icon entries\n");
566 iconDir.idReserved = 0;
568 iconDir.idCount = validEntries;
569 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
570 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
572 WINE_ERR("error 0x%08X writing icon stream\n", hr);
575 for (i = 0; i < validEntries; i++)
576 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
577 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
578 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
580 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
583 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
584 if (FAILED(hr) || bytesWritten != iconOffset)
586 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
590 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
593 HeapFree(GetProcessHeap(), 0, icons);
594 HeapFree(GetProcessHeap(), 0, iconDirEntries);
595 if (FAILED(hr) && stream != NULL)
597 IStream_Release(stream);
603 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
605 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
607 if (!sEnumRes->nIndex--)
609 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
616 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
621 GRPICONDIR *pIconDir;
622 ENUMRESSTRUCT sEnumRes;
625 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
628 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
629 wine_dbgstr_w(szFileName), GetLastError());
630 return HRESULT_FROM_WIN32(GetLastError());
635 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
636 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
637 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
642 sEnumRes.pResInfo = &hResInfo;
643 sEnumRes.nIndex = nIndex;
644 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
645 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
646 sEnumRes.nIndex != -1)
648 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
654 if ((hResData = LoadResource(hModule, hResInfo)))
656 if ((pIconDir = LockResource(hResData)))
658 *ppStream = add_module_icons_to_stream(hModule, pIconDir);
663 FreeResource(hResData);
668 WINE_WARN("found no icon\n");
669 FreeLibrary(hModule);
670 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
673 FreeLibrary(hModule);
677 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
683 *ppIconDirEntries = NULL;
685 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
686 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
687 (iconDir.idReserved != 0) || (iconDir.idType != 1))
689 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
693 *numEntries = iconDir.idCount;
695 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
700 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
701 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
703 if (SUCCEEDED(hr)) hr = E_FAIL;
709 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
713 static HRESULT write_native_icon(IStream *iconStream, const char *icon_name, LPCWSTR szFileName)
715 ICONDIRENTRY *pIconDirEntry = NULL;
717 int nMax = 0, nMaxBits = 0;
720 LARGE_INTEGER position;
723 hr = read_ico_direntries(iconStream, &pIconDirEntry, &numEntries);
727 for (i = 0; i < numEntries; i++)
729 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
730 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
731 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
734 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
735 nMaxBits = pIconDirEntry[i].wBitCount;
738 WINE_TRACE("Selected: %d\n", nIndex);
740 position.QuadPart = 0;
741 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
744 hr = convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
747 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
751 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
756 WCHAR *executable = NULL;
758 char *output_path = NULL;
759 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
761 extension = strrchrW(szFileName, '.');
762 if (extension == NULL)
765 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
768 comma = strrchrW(icon, ',');
772 index = atoiW(comma + 1);
774 hr = open_icon(icon, index, FALSE, ppStream);
778 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, NULL);
780 hr = open_icon(executable, 0, FALSE, ppStream);
784 HeapFree(GetProcessHeap(), 0, icon);
785 HeapFree(GetProcessHeap(), 0, executable);
786 HeapFree(GetProcessHeap(), 0, output_path);
790 static HRESULT open_default_icon(IStream **ppStream)
792 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
794 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
797 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream)
801 hr = open_module_icon(filename, index, ppStream);
804 static const WCHAR dot_icoW[] = {'.','i','c','o',0};
805 int len = strlenW(filename);
806 if (len >= 4 && strcmpiW(&filename[len - 4], dot_icoW) == 0)
807 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
810 hr = open_file_type_icon(filename, ppStream);
811 if (FAILED(hr) && !bWait)
812 hr = open_default_icon(ppStream);
817 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex,
818 int bestIndex, LPCWSTR icoPathW,
819 const char *destFilename, char **nativeIdentifier)
822 WCHAR *guidStrW = NULL;
823 char *guidStrA = NULL;
824 char *icnsPath = NULL;
828 hr = CoCreateGuid(&guid);
831 WINE_WARN("CoCreateGuid failed, error 0x%08X\n", hr);
834 hr = StringFromCLSID(&guid, &guidStrW);
837 WINE_WARN("StringFromCLSID failed, error 0x%08X\n", hr);
840 guidStrA = wchars_to_utf8_chars(guidStrW);
841 if (guidStrA == NULL)
844 WINE_WARN("out of memory converting GUID string\n");
847 icnsPath = heap_printf("/tmp/%s.icns", guidStrA);
848 if (icnsPath == NULL)
851 WINE_WARN("out of memory creating ICNS path\n");
855 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
858 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
861 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICIcnsEncoder,
865 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
866 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
871 CoTaskMemFree(guidStrW);
872 HeapFree(GetProcessHeap(), 0, guidStrA);
874 *nativeIdentifier = icnsPath;
876 HeapFree(GetProcessHeap(), 0, icnsPath);
880 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex,
881 int bestIndex, LPCWSTR icoPathW,
882 const char *destFilename, char **nativeIdentifier)
884 char *icoPathA = NULL;
885 char *iconsDir = NULL;
886 char *pngPath = NULL;
892 icoPathA = wchars_to_utf8_chars(icoPathW);
893 if (icoPathA == NULL)
898 crc = crc16(icoPathA);
899 p = strrchr(icoPathA, '\\');
911 *nativeIdentifier = heap_printf("%s", destFilename);
913 *nativeIdentifier = heap_printf("%04X_%s.%d", crc, p, exeIndex);
914 if (*nativeIdentifier == NULL)
919 iconsDir = heap_printf("%s/icons", xdg_data_dir);
920 if (iconsDir == NULL)
925 create_directories(iconsDir);
926 pngPath = heap_printf("%s/%s.png", iconsDir, *nativeIdentifier);
933 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
936 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
940 HeapFree(GetProcessHeap(), 0, icoPathA);
941 HeapFree(GetProcessHeap(), 0, iconsDir);
942 HeapFree(GetProcessHeap(), 0, pngPath);
945 #endif /* defined(__APPLE__) */
947 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
948 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
950 IStream *stream = NULL;
952 char *nativeIdentifier = NULL;
953 ICONDIRENTRY *iconDirEntries = NULL;
960 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
962 hr = open_icon(icoPathW, index, bWait, &stream);
965 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
968 hr = read_ico_direntries(stream, &iconDirEntries, &numEntries);
971 for (i = 0; i < numEntries; i++)
973 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
974 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
975 if (iconDirEntries[i].wBitCount >= maxBits &&
976 (iconDirEntries[i].bHeight * iconDirEntries[i].bWidth) >= maxPixels)
979 maxPixels = iconDirEntries[i].bHeight * iconDirEntries[i].bWidth;
980 maxBits = iconDirEntries[i].wBitCount;
983 WINE_TRACE("Selected: %d\n", bestIndex);
984 hr = platform_write_icon(stream, index, bestIndex, icoPathW, destFilename, &nativeIdentifier);
986 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
990 IStream_Release(stream);
991 HeapFree(GetProcessHeap(), 0, iconDirEntries);
994 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
995 nativeIdentifier = NULL;
997 return nativeIdentifier;
1000 static HKEY open_menus_reg_key(void)
1002 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1003 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1006 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1007 if (ret == ERROR_SUCCESS)
1013 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1016 WCHAR *windows_fileW;
1020 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1021 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1024 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1025 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1026 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1030 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1031 hkey = open_menus_reg_key();
1034 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1035 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1039 ret = GetLastError();
1040 HeapFree(GetProcessHeap(), 0, windows_fileW);
1043 ret = ERROR_NOT_ENOUGH_MEMORY;
1044 HeapFree(GetProcessHeap(), 0, unix_fileW);
1047 ret = ERROR_NOT_ENOUGH_MEMORY;
1051 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1052 const char *path, const char *args, const char *descr,
1053 const char *workdir, const char *icon)
1057 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1058 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1059 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1061 file = fopen(location, "w");
1065 fprintf(file, "[Desktop Entry]\n");
1066 fprintf(file, "Name=%s\n", linkname);
1067 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1068 wine_get_config_dir(), path, args);
1069 fprintf(file, "Type=Application\n");
1070 fprintf(file, "StartupNotify=true\n");
1071 if (descr && lstrlenA(descr))
1072 fprintf(file, "Comment=%s\n", descr);
1073 if (workdir && lstrlenA(workdir))
1074 fprintf(file, "Path=%s\n", workdir);
1075 if (icon && lstrlenA(icon))
1076 fprintf(file, "Icon=%s\n", icon);
1082 DWORD ret = register_menus_entry(location, unix_link);
1083 if (ret != ERROR_SUCCESS)
1090 static BOOL write_directory_entry(const char *directory, const char *location)
1094 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1096 file = fopen(location, "w");
1100 fprintf(file, "[Desktop Entry]\n");
1101 fprintf(file, "Type=Directory\n");
1102 if (strcmp(directory, "wine") == 0)
1104 fprintf(file, "Name=Wine\n");
1105 fprintf(file, "Icon=wine\n");
1109 fprintf(file, "Name=%s\n", directory);
1110 fprintf(file, "Icon=folder\n");
1117 static BOOL write_menu_file(const char *unix_link, const char *filename)
1120 FILE *tempfile = NULL;
1123 char *menuPath = NULL;
1128 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1132 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1135 int tempfd = mkstemps(tempfilename, 0);
1138 tempfile = fdopen(tempfd, "w");
1144 else if (errno == EEXIST)
1146 HeapFree(GetProcessHeap(), 0, tempfilename);
1149 HeapFree(GetProcessHeap(), 0, tempfilename);
1154 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1155 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1156 fprintf(tempfile, "<Menu>\n");
1157 fprintf(tempfile, " <Name>Applications</Name>\n");
1159 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1160 if (name == NULL) goto end;
1162 for (i = 0; filename[i]; i++)
1164 name[i] = filename[i];
1165 if (filename[i] == '/')
1167 char *dir_file_name;
1170 fprintf(tempfile, " <Menu>\n");
1171 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1172 write_xml_text(tempfile, name);
1173 fprintf(tempfile, "</Name>\n");
1174 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1175 write_xml_text(tempfile, name);
1176 fprintf(tempfile, ".directory</Directory>\n");
1177 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1178 xdg_data_dir, count ? "" : "wine-", name);
1181 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1182 write_directory_entry(lastEntry, dir_file_name);
1183 HeapFree(GetProcessHeap(), 0, dir_file_name);
1186 lastEntry = &name[i+1];
1192 fprintf(tempfile, " <Include>\n");
1193 fprintf(tempfile, " <Filename>");
1194 write_xml_text(tempfile, name);
1195 fprintf(tempfile, "</Filename>\n");
1196 fprintf(tempfile, " </Include>\n");
1197 for (i = 0; i < count; i++)
1198 fprintf(tempfile, " </Menu>\n");
1199 fprintf(tempfile, "</Menu>\n");
1201 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1202 if (menuPath == NULL) goto end;
1203 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1210 ret = (rename(tempfilename, menuPath) == 0);
1211 if (!ret && tempfilename)
1212 remove(tempfilename);
1213 HeapFree(GetProcessHeap(), 0, tempfilename);
1215 register_menus_entry(menuPath, unix_link);
1216 HeapFree(GetProcessHeap(), 0, name);
1217 HeapFree(GetProcessHeap(), 0, menuPath);
1221 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1222 const char *descr, const char *workdir, const char *icon)
1224 const char *linkname;
1225 char *desktopPath = NULL;
1227 char *filename = NULL;
1230 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1231 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1232 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1234 linkname = strrchr(link, '/');
1235 if (linkname == NULL)
1240 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1243 WINE_WARN("out of memory creating menu entry\n");
1247 desktopDir = strrchr(desktopPath, '/');
1249 if (!create_directories(desktopPath))
1251 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1256 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1258 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1263 filename = heap_printf("wine/%s.desktop", link);
1264 if (!filename || !write_menu_file(unix_link, filename))
1266 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1271 HeapFree(GetProcessHeap(), 0, desktopPath);
1272 HeapFree(GetProcessHeap(), 0, filename);
1276 /* This escapes reserved characters in .desktop files' Exec keys. */
1277 static LPSTR escape(LPCWSTR arg)
1280 WCHAR *escaped_string;
1283 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1284 if (escaped_string == NULL) return NULL;
1285 for (i = j = 0; arg[i]; i++)
1290 escaped_string[j++] = '\\';
1291 escaped_string[j++] = '\\';
1292 escaped_string[j++] = '\\';
1293 escaped_string[j++] = '\\';
1313 escaped_string[j++] = '\\';
1314 escaped_string[j++] = '\\';
1317 escaped_string[j++] = arg[i];
1321 escaped_string[j] = 0;
1323 utf8_string = wchars_to_utf8_chars(escaped_string);
1324 if (utf8_string == NULL)
1326 WINE_ERR("out of memory\n");
1331 HeapFree(GetProcessHeap(), 0, escaped_string);
1335 /* Return a heap-allocated copy of the unix format difference between the two
1336 * Windows-format paths.
1337 * locn is the owning location
1338 * link is within locn
1340 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1342 char *unix_locn, *unix_link;
1343 char *relative = NULL;
1345 unix_locn = wine_get_unix_file_name(locn);
1346 unix_link = wine_get_unix_file_name(link);
1347 if (unix_locn && unix_link)
1349 size_t len_unix_locn, len_unix_link;
1350 len_unix_locn = strlen (unix_locn);
1351 len_unix_link = strlen (unix_link);
1352 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1355 char *p = strrchr (unix_link + len_unix_locn, '/');
1356 p = strrchr (p, '.');
1360 len_unix_link = p - unix_link;
1362 len_rel = len_unix_link - len_unix_locn;
1363 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1366 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1371 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1372 HeapFree(GetProcessHeap(), 0, unix_locn);
1373 HeapFree(GetProcessHeap(), 0, unix_link);
1377 /***********************************************************************
1381 * returns TRUE if successful
1382 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1383 * *relative will contain the address of a heap-allocated copy of the portion
1384 * of the filename that is within the specified location, in unix form
1386 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1388 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1389 DWORD len, i, r, filelen;
1390 const DWORD locations[] = {
1391 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1392 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1393 CSIDL_COMMON_STARTMENU };
1395 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1396 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1397 if (filelen==0 || filelen>MAX_PATH)
1400 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1402 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1403 * expand or our hardcoded list won't match.
1405 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1406 if (filelen==0 || filelen>MAX_PATH)
1409 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1411 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1413 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1416 len = lstrlenW(buffer);
1417 if (len >= MAX_PATH)
1418 continue; /* We've just trashed memory! Hopefully we are OK */
1420 if (len > filelen || filename[len]!='\\')
1422 /* do a lstrcmpinW */
1424 r = lstrcmpiW( filename, buffer );
1425 filename[len] = '\\';
1429 /* return the remainder of the string and link type */
1430 *loc = locations[i];
1431 *relative = relative_path (filename, buffer);
1432 return (*relative != NULL);
1438 /* gets the target path directly or through MSI */
1439 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1440 LPWSTR szArgs, DWORD argsSize)
1442 IShellLinkDataList *dl = NULL;
1443 EXP_DARWIN_LINK *dar = NULL;
1449 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1450 if (hr == S_OK && szPath[0])
1452 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1456 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1460 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1467 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1468 if (hr == ERROR_SUCCESS)
1471 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1472 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1473 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1474 if (hr == ERROR_SUCCESS)
1477 int bcount, in_quotes;
1479 /* Extract the application path */
1486 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1488 /* skip the remaining spaces */
1491 } while (*s==0x0009 || *s==0x0020);
1494 else if (*s==0x005c)
1500 else if (*s==0x0022)
1503 if ((bcount & 1)==0)
1505 /* Preceded by an even number of '\', this is
1506 * half that number of '\', plus a quote which
1510 in_quotes=!in_quotes;
1515 /* Preceded by an odd number of '\', this is
1516 * half that number of '\' followed by a '"'
1526 /* a regular character */
1530 if ((d-szPath) == pathSize)
1532 /* Keep processing the path till we get to the
1533 * arguments, but 'stand still'
1538 /* Close the application path */
1541 lstrcpynW(szArgs, s, argsSize);
1543 HeapFree( GetProcessHeap(), 0, szCmdline );
1548 IShellLinkDataList_Release( dl );
1552 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1555 WCHAR *value = NULL;
1557 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1560 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1563 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1566 HeapFree(GetProcessHeap(), 0, value);
1574 static char *slashes_to_minuses(const char *string)
1577 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1580 for (i = 0; string[i]; i++)
1582 if (string[i] == '/')
1593 static BOOL next_line(FILE *file, char **line, int *size)
1600 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1602 while (*line != NULL)
1604 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1606 HeapFree(GetProcessHeap(), 0, *line);
1612 pos = strlen(*line);
1613 cr = strchr(*line, '\n');
1618 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1623 HeapFree(GetProcessHeap(), 0, *line);
1636 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1638 char *globs_filename = NULL;
1640 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1643 FILE *globs_file = fopen(globs_filename, "r");
1644 if (globs_file) /* doesn't have to exist */
1648 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1651 struct xdg_mime_type *mime_type_entry = NULL;
1652 if (line[0] != '#' && (pos = strchr(line, ':')))
1654 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1655 if (mime_type_entry)
1658 mime_type_entry->mimeType = strdupA(line);
1659 mime_type_entry->glob = strdupA(pos + 1);
1660 if (mime_type_entry->mimeType && mime_type_entry->glob)
1661 list_add_tail(mime_types, &mime_type_entry->entry);
1664 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1665 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1666 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1674 HeapFree(GetProcessHeap(), 0, line);
1677 HeapFree(GetProcessHeap(), 0, globs_filename);
1684 static void free_native_mime_types(struct list *native_mime_types)
1686 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1688 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1690 list_remove(&mime_type_entry->entry);
1691 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1692 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1693 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1695 HeapFree(GetProcessHeap(), 0, native_mime_types);
1698 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1700 char *xdg_data_dirs;
1705 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1706 if (xdg_data_dirs == NULL)
1707 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1709 xdg_data_dirs = strdupA(xdg_data_dirs);
1713 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1719 list_init(*mime_types);
1720 ret = add_mimes(xdg_data_home, *mime_types);
1723 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1726 ret = add_mimes(begin, *mime_types);
1732 ret = add_mimes(begin, *mime_types);
1737 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1741 if (!ret && *mime_types)
1743 free_native_mime_types(*mime_types);
1749 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1753 struct xdg_mime_type *mime_type_entry;
1754 int matchLength = 0;
1758 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1760 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1762 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1764 *match = mime_type_entry->mimeType;
1765 matchLength = strlen(mime_type_entry->glob);
1772 *match = strdupA(*match);
1782 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1783 const char *extensionA,
1787 WCHAR *lower_extensionW;
1789 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1790 if (ret == FALSE || *mime_type != NULL)
1792 len = strlenW(extensionW);
1793 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1794 if (lower_extensionW)
1796 char *lower_extensionA;
1797 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1798 strlwrW(lower_extensionW);
1799 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1800 if (lower_extensionA)
1802 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1803 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1808 WINE_FIXME("out of memory\n");
1810 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1815 WINE_FIXME("out of memory\n");
1820 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1823 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1825 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1828 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1831 HeapFree(GetProcessHeap(), 0, ret);
1836 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
1838 WCHAR *valW = reg_get_valW(key, subkey, name);
1841 char *val = wchars_to_utf8_chars(valW);
1842 HeapFree(GetProcessHeap(), 0, valW);
1848 static HKEY open_associations_reg_key(void)
1850 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1851 '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};
1853 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1858 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
1859 LPCSTR appName, LPCWSTR docName, LPCSTR openWithIcon)
1861 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1862 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1863 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1864 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1865 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
1869 if ((assocKey = open_associations_reg_key()))
1876 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
1877 if (!valueA || lstrcmpA(valueA, mimeType))
1879 HeapFree(GetProcessHeap(), 0, valueA);
1881 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1882 if (!value || strcmpW(value, progId))
1884 HeapFree(GetProcessHeap(), 0, value);
1886 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
1887 if (!valueA || lstrcmpA(valueA, appName))
1889 HeapFree(GetProcessHeap(), 0, valueA);
1891 value = reg_get_valW(assocKey, extensionW, DocNameW);
1892 if (docName && (!value || strcmpW(value, docName)))
1894 HeapFree(GetProcessHeap(), 0, value);
1896 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
1897 if ((openWithIcon && !valueA) ||
1898 (!openWithIcon && valueA) ||
1899 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
1901 HeapFree(GetProcessHeap(), 0, valueA);
1903 RegCloseKey(assocKey);
1907 WINE_ERR("error opening associations registry key\n");
1913 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
1914 LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile, LPCSTR openWithIcon)
1916 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1917 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1918 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1919 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1920 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
1921 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
1922 HKEY assocKey = NULL;
1924 WCHAR *mimeTypeW = NULL;
1925 WCHAR *appNameW = NULL;
1926 WCHAR *desktopFileW = NULL;
1927 WCHAR *openWithIconW = NULL;
1929 assocKey = open_associations_reg_key();
1930 if (assocKey == NULL)
1932 WINE_ERR("could not open file associations key\n");
1936 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
1938 WINE_ERR("could not create extension subkey\n");
1942 mimeTypeW = utf8_chars_to_wchars(mimeType);
1943 if (mimeTypeW == NULL)
1945 WINE_ERR("out of memory\n");
1949 appNameW = utf8_chars_to_wchars(appName);
1950 if (appNameW == NULL)
1952 WINE_ERR("out of memory\n");
1956 desktopFileW = utf8_chars_to_wchars(desktopFile);
1957 if (desktopFileW == NULL)
1959 WINE_ERR("out of memory\n");
1965 openWithIconW = utf8_chars_to_wchars(openWithIcon);
1966 if (openWithIconW == NULL)
1968 WINE_ERR("out of memory\n");
1973 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
1974 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1975 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
1977 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1978 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
1980 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
1982 RegDeleteValueW(subkey, OpenWithIconW);
1985 RegCloseKey(assocKey);
1986 RegCloseKey(subkey);
1987 HeapFree(GetProcessHeap(), 0, mimeTypeW);
1988 HeapFree(GetProcessHeap(), 0, appNameW);
1989 HeapFree(GetProcessHeap(), 0, desktopFileW);
1990 HeapFree(GetProcessHeap(), 0, openWithIconW);
1993 static BOOL cleanup_associations(void)
1995 static const WCHAR openW[] = {'o','p','e','n',0};
1996 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
1998 BOOL hasChanged = FALSE;
1999 if ((assocKey = open_associations_reg_key()))
2003 for (i = 0; !done; i++)
2005 WCHAR *extensionW = NULL;
2011 HeapFree(GetProcessHeap(), 0, extensionW);
2012 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2013 if (extensionW == NULL)
2015 WINE_ERR("out of memory\n");
2016 ret = ERROR_OUTOFMEMORY;
2019 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2021 } while (ret == ERROR_MORE_DATA);
2023 if (ret == ERROR_SUCCESS)
2026 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2027 if (command == NULL)
2029 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2032 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2033 remove(desktopFile);
2035 RegDeleteKeyW(assocKey, extensionW);
2037 HeapFree(GetProcessHeap(), 0, desktopFile);
2039 HeapFree(GetProcessHeap(), 0, command);
2043 if (ret != ERROR_NO_MORE_ITEMS)
2044 WINE_ERR("error %d while reading registry\n", ret);
2047 HeapFree(GetProcessHeap(), 0, extensionW);
2049 RegCloseKey(assocKey);
2052 WINE_ERR("could not open file associations key\n");
2056 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2057 const char *mime_type, const char *comment)
2062 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2063 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2065 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2068 FILE *packageFile = fopen(filename, "w");
2071 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2072 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2073 fprintf(packageFile, " <mime-type type=\"");
2074 write_xml_text(packageFile, mime_type);
2075 fprintf(packageFile, "\">\n");
2076 fprintf(packageFile, " <glob pattern=\"*");
2077 write_xml_text(packageFile, dot_extension);
2078 fprintf(packageFile, "\"/>\n");
2081 fprintf(packageFile, " <comment>");
2082 write_xml_text(packageFile, comment);
2083 fprintf(packageFile, "</comment>\n");
2085 fprintf(packageFile, " </mime-type>\n");
2086 fprintf(packageFile, "</mime-info>\n");
2088 fclose(packageFile);
2091 WINE_ERR("error writing file %s\n", filename);
2092 HeapFree(GetProcessHeap(), 0, filename);
2095 WINE_ERR("out of memory\n");
2099 static BOOL is_extension_blacklisted(LPCWSTR extension)
2101 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2102 static const WCHAR comW[] = {'.','c','o','m',0};
2103 static const WCHAR exeW[] = {'.','e','x','e',0};
2104 static const WCHAR msiW[] = {'.','m','s','i',0};
2106 if (!strcmpiW(extension, comW) ||
2107 !strcmpiW(extension, exeW) ||
2108 !strcmpiW(extension, msiW))
2113 static const char* get_special_mime_type(LPCWSTR extension)
2115 static const WCHAR lnkW[] = {'.','l','n','k',0};
2116 if (!strcmpiW(extension, lnkW))
2117 return "application/x-ms-shortcut";
2121 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2122 const char *friendlyAppName, const char *mimeType,
2123 const char *progId, const char *openWithIcon)
2128 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2129 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2130 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2132 desktop = fopen(desktopPath, "w");
2135 fprintf(desktop, "[Desktop Entry]\n");
2136 fprintf(desktop, "Type=Application\n");
2137 fprintf(desktop, "Name=%s\n", friendlyAppName);
2138 fprintf(desktop, "MimeType=%s\n", mimeType);
2139 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
2140 fprintf(desktop, "NoDisplay=true\n");
2141 fprintf(desktop, "StartupNotify=true\n");
2143 fprintf(desktop, "Icon=%s\n", openWithIcon);
2148 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2152 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2154 static const WCHAR openW[] = {'o','p','e','n',0};
2155 struct wine_rb_tree mimeProgidTree;
2156 struct list *nativeMimeTypes = NULL;
2159 BOOL hasChanged = FALSE;
2161 if (wine_rb_init(&mimeProgidTree, &winemenubuilder_rb_functions))
2163 WINE_ERR("wine_rb_init failed\n");
2166 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2168 WINE_ERR("could not build native MIME types\n");
2174 WCHAR *extensionW = NULL;
2179 HeapFree(GetProcessHeap(), 0, extensionW);
2180 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2181 if (extensionW == NULL)
2183 WINE_ERR("out of memory\n");
2184 ret = ERROR_OUTOFMEMORY;
2187 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2189 } while (ret == ERROR_MORE_DATA);
2191 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2193 char *extensionA = NULL;
2194 WCHAR *commandW = NULL;
2195 WCHAR *executableW = NULL;
2196 char *openWithIconA = NULL;
2197 WCHAR *friendlyDocNameW = NULL;
2198 char *friendlyDocNameA = NULL;
2199 WCHAR *iconW = NULL;
2201 WCHAR *contentTypeW = NULL;
2202 char *mimeTypeA = NULL;
2203 WCHAR *friendlyAppNameW = NULL;
2204 char *friendlyAppNameA = NULL;
2205 WCHAR *progIdW = NULL;
2206 char *progIdA = NULL;
2207 char *mimeProgId = NULL;
2209 extensionA = wchars_to_utf8_chars(extensionW);
2210 if (extensionA == NULL)
2212 WINE_ERR("out of memory\n");
2216 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2217 if (friendlyDocNameW)
2219 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2220 if (friendlyDocNameA == NULL)
2222 WINE_ERR("out of memory\n");
2227 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2229 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2231 strlwrW(contentTypeW);
2233 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2236 if (mimeTypeA == NULL)
2238 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2239 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2240 else if ((get_special_mime_type(extensionW)))
2241 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2243 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2245 if (mimeTypeA != NULL)
2247 /* Gnome seems to ignore the <icon> tag in MIME packages,
2248 * and the default name is more intuitive anyway.
2252 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2256 WCHAR *comma = strrchrW(iconW, ',');
2260 index = atoiW(comma + 1);
2262 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2263 HeapFree(GetProcessHeap(), 0, flattened_mime);
2267 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2272 WINE_FIXME("out of memory\n");
2277 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2278 if (commandW == NULL)
2279 /* no command => no application is associated */
2282 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2284 openWithIconA = extract_icon(executableW, 0, NULL, FALSE);
2286 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2287 if (friendlyAppNameW)
2289 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2290 if (friendlyAppNameA == NULL)
2292 WINE_ERR("out of memory\n");
2298 friendlyAppNameA = heap_printf("A Wine application");
2299 if (friendlyAppNameA == NULL)
2301 WINE_ERR("out of memory\n");
2306 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2309 progIdA = escape(progIdW);
2310 if (progIdA == NULL)
2312 WINE_ERR("out of memory\n");
2317 goto end; /* no progID => not a file type association */
2319 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2320 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2323 struct rb_string_entry *entry;
2324 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2326 HeapFree(GetProcessHeap(), 0, mimeProgId);
2329 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2332 WINE_ERR("out of memory allocating rb_string_entry\n");
2335 entry->string = mimeProgId;
2336 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2338 WINE_ERR("error updating rb tree\n");
2343 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, openWithIconA))
2345 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2348 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2351 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath, openWithIconA);
2353 HeapFree(GetProcessHeap(), 0, desktopPath);
2358 HeapFree(GetProcessHeap(), 0, extensionA);
2359 HeapFree(GetProcessHeap(), 0, commandW);
2360 HeapFree(GetProcessHeap(), 0, executableW);
2361 HeapFree(GetProcessHeap(), 0, openWithIconA);
2362 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2363 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2364 HeapFree(GetProcessHeap(), 0, iconW);
2365 HeapFree(GetProcessHeap(), 0, iconA);
2366 HeapFree(GetProcessHeap(), 0, contentTypeW);
2367 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2368 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2369 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2370 HeapFree(GetProcessHeap(), 0, progIdW);
2371 HeapFree(GetProcessHeap(), 0, progIdA);
2373 HeapFree(GetProcessHeap(), 0, extensionW);
2374 if (ret != ERROR_SUCCESS)
2378 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2379 free_native_mime_types(nativeMimeTypes);
2383 static char *get_start_exe_path(void)
2385 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2386 '\\','s','t','a','r','t','.','e','x','e',0};
2387 WCHAR start_path[MAX_PATH];
2388 GetWindowsDirectoryW(start_path, MAX_PATH);
2389 lstrcatW(start_path, startW);
2390 return escape(start_path);
2393 static char* escape_unix_link_arg(LPCSTR unix_link)
2396 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2399 char *escaped_lnk = escape(unix_linkW);
2402 ret = heap_printf("/Unix %s", escaped_lnk);
2403 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2405 HeapFree(GetProcessHeap(), 0, unix_linkW);
2410 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2412 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2413 '\\','s','t','a','r','t','.','e','x','e',0};
2414 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2415 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2416 WCHAR szTmp[INFOTIPSIZE];
2417 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2418 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2419 int iIconId = 0, r = -1;
2422 char *unix_link = NULL;
2423 char *start_path = NULL;
2427 WINE_ERR("Link name is null\n");
2431 if( !GetLinkLocation( link, &csidl, &link_name ) )
2433 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2436 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2438 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2441 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2444 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2445 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2446 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2449 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2450 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2451 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2453 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2454 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2455 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2456 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2459 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2460 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2461 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2465 LPITEMIDLIST pidl = NULL;
2466 IShellLinkW_GetIDList( sl, &pidl );
2467 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2468 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2471 /* extract the icon */
2473 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2475 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2477 /* fail - try once again after parent process exit */
2482 WINE_WARN("Unable to extract icon, deferring.\n");
2485 WINE_ERR("failed to extract icon from %s\n",
2486 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2489 unix_link = wine_get_unix_file_name(link);
2490 if (unix_link == NULL)
2492 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2496 /* check the path */
2499 static const WCHAR exeW[] = {'.','e','x','e',0};
2502 /* check for .exe extension */
2503 if (!(p = strrchrW( szPath, '.' )) ||
2504 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2505 lstrcmpiW( p, exeW ))
2507 /* Not .exe - use 'start.exe' to launch this file */
2508 p = szArgs + lstrlenW(szPath) + 2;
2512 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2513 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2519 lstrcpyW(szArgs + 1, szPath);
2522 GetWindowsDirectoryW(szPath, MAX_PATH);
2523 lstrcatW(szPath, startW);
2526 /* convert app working dir */
2528 work_dir = wine_get_unix_file_name( szWorkDir );
2532 /* if there's no path... try run the link itself */
2533 lstrcpynW(szArgs, link, MAX_PATH);
2534 GetWindowsDirectoryW(szPath, MAX_PATH);
2535 lstrcatW(szPath, startW);
2538 /* escape the path and parameters */
2539 escaped_path = escape(szPath);
2540 escaped_args = escape(szArgs);
2541 description = wchars_to_utf8_chars(szDescription);
2542 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2544 WINE_ERR("out of memory allocating/escaping parameters\n");
2548 start_path = get_start_exe_path();
2549 if (start_path == NULL)
2551 WINE_ERR("out of memory\n");
2555 /* building multiple menus concurrently has race conditions */
2556 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2557 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2559 WINE_ERR("failed wait for semaphore\n");
2563 if (in_desktop_dir(csidl))
2566 const char *lastEntry;
2567 lastEntry = strrchr(link_name, '/');
2568 if (lastEntry == NULL)
2569 lastEntry = link_name;
2572 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2575 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2577 char *link_arg = escape_unix_link_arg(unix_link);
2580 r = !write_desktop_entry(unix_link, location, lastEntry,
2581 start_path, link_arg, description, work_dir, icon_name);
2582 HeapFree(GetProcessHeap(), 0, link_arg);
2586 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2588 chmod(location, 0755);
2589 HeapFree(GetProcessHeap(), 0, location);
2594 char *link_arg = escape_unix_link_arg(unix_link);
2597 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name);
2598 HeapFree(GetProcessHeap(), 0, link_arg);
2602 ReleaseSemaphore( hsem, 1, NULL );
2605 if (hsem) CloseHandle( hsem );
2606 HeapFree( GetProcessHeap(), 0, icon_name );
2607 HeapFree( GetProcessHeap(), 0, work_dir );
2608 HeapFree( GetProcessHeap(), 0, link_name );
2609 HeapFree( GetProcessHeap(), 0, escaped_args );
2610 HeapFree( GetProcessHeap(), 0, escaped_path );
2611 HeapFree( GetProcessHeap(), 0, description );
2612 HeapFree( GetProcessHeap(), 0, unix_link );
2613 HeapFree( GetProcessHeap(), 0, start_path );
2616 WINE_ERR("failed to build the menu\n" );
2621 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2623 char *link_name = NULL, *icon_name = NULL;
2626 char *escaped_urlPath = NULL;
2631 char *unix_link = NULL;
2632 IPropertySetStorage *pPropSetStg;
2633 IPropertyStorage *pPropStg;
2639 WINE_ERR("Link name is null\n");
2643 if( !GetLinkLocation( link, &csidl, &link_name ) )
2645 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2648 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2650 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2654 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2656 hr = url->lpVtbl->GetURL(url, &urlPath);
2662 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2664 unix_link = wine_get_unix_file_name(link);
2665 if (unix_link == NULL)
2667 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2671 escaped_urlPath = escape(urlPath);
2672 if (escaped_urlPath == NULL)
2674 WINE_ERR("couldn't escape url, out of memory\n");
2678 ps[0].ulKind = PRSPEC_PROPID;
2679 ps[0].propid = PID_IS_ICONFILE;
2680 ps[1].ulKind = PRSPEC_PROPID;
2681 ps[1].propid = PID_IS_ICONINDEX;
2683 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
2686 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
2689 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
2692 icon_name = extract_icon( pv[0].pwszVal, pv[1].iVal, NULL, bWait );
2694 WINE_TRACE("URL icon path: %s icon index: %d icon name: %s\n", wine_dbgstr_w(pv[0].pwszVal), pv[1].iVal, icon_name);
2696 IPropertyStorage_Release(pPropStg);
2698 IPropertySetStorage_Release(pPropSetStg);
2701 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2702 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2704 WINE_ERR("failed wait for semaphore\n");
2707 if (in_desktop_dir(csidl))
2710 const char *lastEntry;
2711 lastEntry = strrchr(link_name, '/');
2712 if (lastEntry == NULL)
2713 lastEntry = link_name;
2716 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2719 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, icon_name);
2721 chmod(location, 0755);
2722 HeapFree(GetProcessHeap(), 0, location);
2726 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, icon_name);
2728 ReleaseSemaphore(hSem, 1, NULL);
2733 HeapFree( GetProcessHeap(), 0, icon_name );
2734 HeapFree(GetProcessHeap(), 0, link_name);
2735 CoTaskMemFree( urlPath );
2736 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2737 HeapFree(GetProcessHeap(), 0, unix_link);
2741 static BOOL WaitForParentProcess( void )
2743 PROCESSENTRY32 procentry;
2744 HANDLE hsnapshot = NULL, hprocess = NULL;
2745 DWORD ourpid = GetCurrentProcessId();
2746 BOOL ret = FALSE, rc;
2748 WINE_TRACE("Waiting for parent process\n");
2749 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2750 INVALID_HANDLE_VALUE)
2752 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2756 procentry.dwSize = sizeof(PROCESSENTRY32);
2757 rc = Process32First( hsnapshot, &procentry );
2760 if (procentry.th32ProcessID == ourpid) break;
2761 rc = Process32Next( hsnapshot, &procentry );
2765 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2769 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2772 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2777 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2780 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2783 if (hprocess) CloseHandle( hprocess );
2784 if (hsnapshot) CloseHandle( hsnapshot );
2788 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2793 WCHAR fullname[MAX_PATH];
2796 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2800 WINE_ERR("link name missing\n");
2804 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2805 if (len==0 || len>MAX_PATH)
2807 WINE_ERR("couldn't get full path of link file\n");
2811 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2812 &IID_IShellLinkW, (LPVOID *) &sl );
2815 WINE_ERR("No IID_IShellLink\n");
2819 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2822 WINE_ERR("No IID_IPersistFile\n");
2826 r = IPersistFile_Load( pf, fullname, STGM_READ );
2827 if( SUCCEEDED( r ) )
2829 /* If something fails (eg. Couldn't extract icon)
2830 * wait for parent process and try again
2832 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2834 WaitForParentProcess();
2835 InvokeShellLinker( sl, fullname, FALSE );
2840 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2843 IPersistFile_Release( pf );
2844 IShellLinkW_Release( sl );
2849 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2851 IUniformResourceLocatorW *url;
2854 WCHAR fullname[MAX_PATH];
2857 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2861 WINE_ERR("URL name missing\n");
2865 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2866 if (len==0 || len>MAX_PATH)
2868 WINE_ERR("couldn't get full path of URL file\n");
2872 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2873 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2876 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2880 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2883 WINE_ERR("No IID_IPersistFile\n");
2886 r = IPersistFile_Load( pf, fullname, STGM_READ );
2887 if( SUCCEEDED( r ) )
2889 /* If something fails (eg. Couldn't extract icon)
2890 * wait for parent process and try again
2892 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2894 WaitForParentProcess();
2895 InvokeShellLinkerForURL( url, fullname, FALSE );
2899 IPersistFile_Release( pf );
2900 url->lpVtbl->Release( url );
2905 static void RefreshFileTypeAssociations(void)
2908 char *mime_dir = NULL;
2909 char *packages_dir = NULL;
2910 char *applications_dir = NULL;
2913 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2914 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2916 WINE_ERR("failed wait for semaphore\n");
2922 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2923 if (mime_dir == NULL)
2925 WINE_ERR("out of memory\n");
2928 create_directories(mime_dir);
2930 packages_dir = heap_printf("%s/packages", mime_dir);
2931 if (packages_dir == NULL)
2933 WINE_ERR("out of memory\n");
2936 create_directories(packages_dir);
2938 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2939 if (applications_dir == NULL)
2941 WINE_ERR("out of memory\n");
2944 create_directories(applications_dir);
2946 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2947 hasChanged |= cleanup_associations();
2950 const char *argv[3];
2952 argv[0] = "update-mime-database";
2955 spawnvp( _P_NOWAIT, argv[0], argv );
2957 argv[0] = "update-desktop-database";
2958 argv[1] = applications_dir;
2959 spawnvp( _P_NOWAIT, argv[0], argv );
2965 ReleaseSemaphore(hSem, 1, NULL);
2968 HeapFree(GetProcessHeap(), 0, mime_dir);
2969 HeapFree(GetProcessHeap(), 0, packages_dir);
2970 HeapFree(GetProcessHeap(), 0, applications_dir);
2973 static void cleanup_menus(void)
2977 hkey = open_menus_reg_key();
2981 LSTATUS lret = ERROR_SUCCESS;
2982 for (i = 0; lret == ERROR_SUCCESS; )
2984 WCHAR *value = NULL;
2986 DWORD valueSize = 4096;
2987 DWORD dataSize = 4096;
2990 lret = ERROR_OUTOFMEMORY;
2991 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
2994 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
2997 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2998 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
3002 HeapFree(GetProcessHeap(), 0, value);
3003 HeapFree(GetProcessHeap(), 0, data);
3004 value = data = NULL;
3006 if (lret == ERROR_SUCCESS)
3010 unix_file = wchars_to_unix_chars(value);
3011 windows_file = wchars_to_unix_chars(data);
3012 if (unix_file != NULL && windows_file != NULL)
3014 struct stat filestats;
3015 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3017 WINE_TRACE("removing menu related file %s\n", unix_file);
3019 RegDeleteValueW(hkey, value);
3026 WINE_ERR("out of memory enumerating menus\n");
3027 lret = ERROR_OUTOFMEMORY;
3029 HeapFree(GetProcessHeap(), 0, unix_file);
3030 HeapFree(GetProcessHeap(), 0, windows_file);
3032 else if (lret != ERROR_NO_MORE_ITEMS)
3033 WINE_ERR("error %d reading registry\n", lret);
3034 HeapFree(GetProcessHeap(), 0, value);
3035 HeapFree(GetProcessHeap(), 0, data);
3040 WINE_ERR("error opening registry key, menu cleanup failed\n");
3043 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3045 char *utf8lnkPath = NULL;
3046 char *utf8OutputPath = NULL;
3047 WCHAR *winLnkPath = NULL;
3048 IShellLinkW *shellLink = NULL;
3049 IPersistFile *persistFile = NULL;
3050 WCHAR szTmp[MAX_PATH];
3051 WCHAR szPath[MAX_PATH];
3052 WCHAR szArgs[INFOTIPSIZE];
3053 WCHAR szIconPath[MAX_PATH];
3055 IStream *stream = NULL;
3058 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3059 if (utf8lnkPath == NULL)
3061 WINE_ERR("out of memory converting paths\n");
3065 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3066 if (utf8OutputPath == NULL)
3068 WINE_ERR("out of memory converting paths\n");
3072 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3073 if (winLnkPath == NULL)
3075 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3079 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3080 &IID_IShellLinkW, (LPVOID*)&shellLink);
3083 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3087 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3090 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3094 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3097 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3101 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3102 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3104 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3105 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3109 LPITEMIDLIST pidl = NULL;
3110 IShellLinkW_GetIDList(shellLink, &pidl);
3111 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3112 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3117 hr = open_icon(szIconPath, iconId, FALSE, &stream);
3119 hr = write_native_icon(stream, utf8OutputPath, NULL);
3123 hr = open_icon(szPath, iconId, FALSE, &stream);
3125 hr = write_native_icon(stream, utf8OutputPath, NULL);
3129 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3130 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3131 HeapFree(GetProcessHeap(), 0, winLnkPath);
3132 if (shellLink != NULL)
3133 IShellLinkW_Release(shellLink);
3134 if (persistFile != NULL)
3135 IPersistFile_Release(persistFile);
3137 IStream_Release(stream);
3140 static WCHAR *next_token( LPWSTR *p )
3142 LPWSTR token = NULL, t = *p;
3147 while( t && !token )
3155 /* unquote the token */
3157 t = strchrW( token, '"' );
3166 t = strchrW( token, ' ' );
3176 static BOOL init_xdg(void)
3178 WCHAR shellDesktopPath[MAX_PATH];
3179 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3181 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3182 if (xdg_desktop_dir == NULL)
3184 WINE_ERR("error looking up the desktop directory\n");
3188 if (getenv("XDG_CONFIG_HOME"))
3189 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3191 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3194 create_directories(xdg_config_dir);
3195 if (getenv("XDG_DATA_HOME"))
3196 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3198 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3202 create_directories(xdg_data_dir);
3203 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3206 mkdir(buffer, 0777);
3207 HeapFree(GetProcessHeap(), 0, buffer);
3211 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3213 WINE_ERR("out of memory\n");
3217 /***********************************************************************
3221 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3223 static const WCHAR dash_aW[] = {'-','a',0};
3224 static const WCHAR dash_rW[] = {'-','r',0};
3225 static const WCHAR dash_tW[] = {'-','t',0};
3226 static const WCHAR dash_uW[] = {'-','u',0};
3227 static const WCHAR dash_wW[] = {'-','w',0};
3229 LPWSTR token = NULL, p;
3238 hr = CoInitialize(NULL);
3241 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3245 for( p = cmdline; p && *p; )
3247 token = next_token( &p );
3250 if( !strcmpW( token, dash_aW ) )
3252 RefreshFileTypeAssociations();
3255 if( !strcmpW( token, dash_rW ) )
3260 if( !strcmpW( token, dash_wW ) )
3262 else if ( !strcmpW( token, dash_uW ) )
3264 else if ( !strcmpW( token, dash_tW ) )
3266 WCHAR *lnkFile = next_token( &p );
3269 WCHAR *outputFile = next_token( &p );
3271 thumbnail_lnk(lnkFile, outputFile);
3274 else if( token[0] == '-' )
3276 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3283 bRet = Process_URL( token, bWait );
3285 bRet = Process_Link( token, bWait );
3288 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );