ntdll: Fix frame address check in RtlCaptureStackBackTrace to match what RtlUnwind...
[wine.git] / programs / winemenubuilder / winemenubuilder.c
blob070a8c2b331e4ad082a8f7f4627a32aba4356fe2
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;
151 #include "poppack.h"
153 typedef struct
155 HRSRC *pResInfo;
156 int nIndex;
157 } ENUMRESSTRUCT;
159 struct xdg_mime_type
161 char *mimeType;
162 char *glob;
163 struct list entry;
166 struct rb_string_entry
168 char *string;
169 struct wine_rb_entry entry;
172 DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
174 static char *xdg_config_dir;
175 static char *xdg_data_dir;
176 static char *xdg_desktop_dir;
178 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra);
179 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream);
181 /* Utility routines */
182 static unsigned short crc16(const char* string)
184 unsigned short crc = 0;
185 int i, j, xor_poly;
187 for (i = 0; string[i] != 0; i++)
189 char c = string[i];
190 for (j = 0; j < 8; c >>= 1, j++)
192 xor_poly = (c ^ crc) & 1;
193 crc >>= 1;
194 if (xor_poly)
195 crc ^= 0xa001;
198 return crc;
201 static char *strdupA( const char *str )
203 char *ret;
205 if (!str) return NULL;
206 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
207 return ret;
210 static char* heap_printf(const char *format, ...)
212 va_list args;
213 int size = 4096;
214 char *buffer, *ret;
215 int n;
217 va_start(args, format);
218 while (1)
220 buffer = HeapAlloc(GetProcessHeap(), 0, size);
221 if (buffer == NULL)
222 break;
223 n = vsnprintf(buffer, size, format, args);
224 if (n == -1)
225 size *= 2;
226 else if (n >= size)
227 size = n + 1;
228 else
229 break;
230 HeapFree(GetProcessHeap(), 0, buffer);
232 va_end(args);
233 if (!buffer) return NULL;
234 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
235 if (!ret) ret = buffer;
236 return ret;
239 static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
241 const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);
243 return strcmp((char*)key, t->string);
246 static void *winemenubuilder_rb_alloc(size_t size)
248 return HeapAlloc(GetProcessHeap(), 0, size);
251 static void *winemenubuilder_rb_realloc(void *ptr, size_t size)
253 return HeapReAlloc(GetProcessHeap(), 0, ptr, size);
256 static void winemenubuilder_rb_free(void *ptr)
258 HeapFree(GetProcessHeap(), 0, ptr);
261 static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
263 struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
264 HeapFree(GetProcessHeap(), 0, t->string);
265 HeapFree(GetProcessHeap(), 0, t);
268 static const struct wine_rb_functions winemenubuilder_rb_functions =
270 winemenubuilder_rb_alloc,
271 winemenubuilder_rb_realloc,
272 winemenubuilder_rb_free,
273 winemenubuilder_rb_string_compare,
276 static void write_xml_text(FILE *file, const char *text)
278 int i;
279 for (i = 0; text[i]; i++)
281 if (text[i] == '&')
282 fputs("&amp;", file);
283 else if (text[i] == '<')
284 fputs("&lt;", file);
285 else if (text[i] == '>')
286 fputs("&gt;", file);
287 else if (text[i] == '\'')
288 fputs("&apos;", file);
289 else if (text[i] == '"')
290 fputs("&quot;", file);
291 else
292 fputc(text[i], file);
296 static BOOL create_directories(char *directory)
298 BOOL ret = TRUE;
299 int i;
301 for (i = 0; directory[i]; i++)
303 if (i > 0 && directory[i] == '/')
305 directory[i] = 0;
306 mkdir(directory, 0777);
307 directory[i] = '/';
310 if (mkdir(directory, 0777) && errno != EEXIST)
311 ret = FALSE;
313 return ret;
316 static char* wchars_to_utf8_chars(LPCWSTR string)
318 char *ret;
319 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
320 ret = HeapAlloc(GetProcessHeap(), 0, size);
321 if (ret)
322 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
323 return ret;
326 static char* wchars_to_unix_chars(LPCWSTR string)
328 char *ret;
329 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
330 ret = HeapAlloc(GetProcessHeap(), 0, size);
331 if (ret)
332 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
333 return ret;
336 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
338 WCHAR *ret;
339 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
340 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
341 if (ret)
342 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
343 return ret;
346 /* Icon extraction routines
348 * FIXME: should use PrivateExtractIcons and friends
349 * FIXME: should not use stdio
352 static HRESULT convert_to_native_icon(IStream *icoFile, int *indeces, int numIndeces,
353 const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
355 WCHAR *dosOutputFileName = NULL;
356 IWICImagingFactory *factory = NULL;
357 IWICBitmapDecoder *decoder = NULL;
358 IWICBitmapEncoder *encoder = NULL;
359 IStream *outputFile = NULL;
360 int i;
361 HRESULT hr = E_FAIL;
363 dosOutputFileName = wine_get_dos_file_name(outputFileName);
364 if (dosOutputFileName == NULL)
366 WINE_ERR("error converting %s to DOS file name\n", outputFileName);
367 goto end;
369 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
370 &IID_IWICImagingFactory, (void**)&factory);
371 if (FAILED(hr))
373 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
374 goto end;
376 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
377 WICDecodeMetadataCacheOnDemand, &decoder);
378 if (FAILED(hr))
380 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
381 goto end;
383 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
384 &IID_IWICBitmapEncoder, (void**)&encoder);
385 if (FAILED(hr))
387 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
388 goto end;
390 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
391 if (FAILED(hr))
393 WINE_ERR("error 0x%08X creating output file\n", hr);
394 goto end;
396 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, GENERIC_WRITE);
397 if (FAILED(hr))
399 WINE_ERR("error 0x%08X initializing encoder\n", hr);
400 goto end;
403 for (i = 0; i < numIndeces; i++)
405 IWICBitmapFrameDecode *sourceFrame = NULL;
406 IWICBitmapSource *sourceBitmap = NULL;
407 IWICBitmapFrameEncode *dstFrame = NULL;
408 IPropertyBag2 *options = NULL;
409 UINT width, height;
411 hr = IWICBitmapDecoder_GetFrame(decoder, indeces[i], &sourceFrame);
412 if (FAILED(hr))
414 WINE_ERR("error 0x%08X getting frame %d\n", hr, indeces[i]);
415 goto endloop;
417 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
418 if (FAILED(hr))
420 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
421 goto endloop;
423 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
424 if (FAILED(hr))
426 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
427 goto endloop;
429 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
430 if (FAILED(hr))
432 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
433 goto endloop;
435 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
436 if (FAILED(hr))
438 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
439 goto endloop;
441 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
442 if (FAILED(hr))
444 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
445 goto endloop;
447 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
448 if (FAILED(hr))
450 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
451 goto endloop;
453 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
454 if (FAILED(hr))
456 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
457 goto endloop;
459 hr = IWICBitmapFrameEncode_Commit(dstFrame);
460 if (FAILED(hr))
462 WINE_ERR("error 0x%08X committing frame\n", hr);
463 goto endloop;
465 endloop:
466 if (sourceFrame)
467 IWICBitmapFrameDecode_Release(sourceFrame);
468 if (sourceBitmap)
469 IWICBitmapSource_Release(sourceBitmap);
470 if (dstFrame)
471 IWICBitmapFrameEncode_Release(dstFrame);
474 hr = IWICBitmapEncoder_Commit(encoder);
475 if (FAILED(hr))
477 WINE_ERR("error 0x%08X committing encoder\n", hr);
478 goto end;
481 end:
482 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
483 if (factory)
484 IWICImagingFactory_Release(factory);
485 if (decoder)
486 IWICBitmapDecoder_Release(decoder);
487 if (encoder)
488 IWICBitmapEncoder_Release(encoder);
489 if (outputFile)
490 IStream_Release(outputFile);
491 return hr;
494 static IStream *add_module_icons_to_stream(HMODULE hModule, GRPICONDIR *grpIconDir)
496 int i;
497 SIZE_T iconsSize = 0;
498 BYTE *icons = NULL;
499 ICONDIRENTRY *iconDirEntries = NULL;
500 IStream *stream = NULL;
501 HRESULT hr = E_FAIL;
502 ULONG bytesWritten;
503 ICONDIR iconDir;
504 SIZE_T iconOffset;
505 int validEntries = 0;
506 LARGE_INTEGER zero;
508 for (i = 0; i < grpIconDir->idCount; i++)
509 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
510 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
511 if (icons == NULL)
513 WINE_ERR("out of memory allocating icon\n");
514 goto end;
517 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
518 if (iconDirEntries == NULL)
520 WINE_ERR("out of memory allocating icon dir entries\n");
521 goto end;
524 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
525 if (FAILED(hr))
527 WINE_ERR("error creating icon stream\n");
528 goto end;
531 iconOffset = 0;
532 for (i = 0; i < grpIconDir->idCount; i++)
534 HRSRC hResInfo;
535 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
536 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
538 HGLOBAL hResData;
539 if ((hResData = LoadResource(hModule, hResInfo)))
541 BITMAPINFO *pIcon;
542 if ((pIcon = LockResource(hResData)))
544 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
545 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
546 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
547 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
548 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
549 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
550 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
551 iconDirEntries[validEntries].dwImageOffset = iconOffset;
552 validEntries++;
553 memcpy(&icons[iconOffset], pIcon, grpIconDir->idEntries[i].dwBytesInRes);
554 iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
556 FreeResource(hResData);
561 if (validEntries == 0)
563 WINE_ERR("no valid icon entries\n");
564 goto end;
567 iconDir.idReserved = 0;
568 iconDir.idType = 1;
569 iconDir.idCount = validEntries;
570 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
571 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
573 WINE_ERR("error 0x%08X writing icon stream\n", hr);
574 goto end;
576 for (i = 0; i < validEntries; i++)
577 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
578 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
579 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
581 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
582 goto end;
584 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
585 if (FAILED(hr) || bytesWritten != iconOffset)
587 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
588 goto end;
590 zero.QuadPart = 0;
591 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
593 end:
594 HeapFree(GetProcessHeap(), 0, icons);
595 HeapFree(GetProcessHeap(), 0, iconDirEntries);
596 if (FAILED(hr) && stream != NULL)
598 IStream_Release(stream);
599 stream = NULL;
601 return stream;
604 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
606 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
608 if (!sEnumRes->nIndex--)
610 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
611 return FALSE;
613 else
614 return TRUE;
617 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
619 HMODULE hModule;
620 HRSRC hResInfo;
621 HGLOBAL hResData;
622 GRPICONDIR *pIconDir;
623 ENUMRESSTRUCT sEnumRes;
624 HRESULT hr = E_FAIL;
626 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
627 if (!hModule)
629 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
630 wine_dbgstr_w(szFileName), GetLastError());
631 return HRESULT_FROM_WIN32(GetLastError());
634 if (nIndex < 0)
636 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
637 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
638 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
640 else
642 hResInfo=NULL;
643 sEnumRes.pResInfo = &hResInfo;
644 sEnumRes.nIndex = nIndex;
645 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
646 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
647 sEnumRes.nIndex != -1)
649 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
653 if (hResInfo)
655 if ((hResData = LoadResource(hModule, hResInfo)))
657 if ((pIconDir = LockResource(hResData)))
659 *ppStream = add_module_icons_to_stream(hModule, pIconDir);
660 if (*ppStream)
661 hr = S_OK;
664 FreeResource(hResData);
667 else
669 WINE_WARN("found no icon\n");
670 FreeLibrary(hModule);
671 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
674 FreeLibrary(hModule);
675 return hr;
678 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
680 ICONDIR iconDir;
681 ULONG bytesRead;
682 HRESULT hr;
684 *ppIconDirEntries = NULL;
686 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
687 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
688 (iconDir.idReserved != 0) || (iconDir.idType != 1))
690 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
691 hr = E_FAIL;
692 goto end;
694 *numEntries = iconDir.idCount;
696 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
698 hr = E_OUTOFMEMORY;
699 goto end;
701 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
702 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
704 if (SUCCEEDED(hr)) hr = E_FAIL;
705 goto end;
708 end:
709 if (FAILED(hr))
710 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
711 return hr;
714 static HRESULT write_native_icon(IStream *iconStream, const char *icon_name, LPCWSTR szFileName)
716 ICONDIRENTRY *pIconDirEntry = NULL;
717 int numEntries;
718 int nMax = 0, nMaxBits = 0;
719 int nIndex = 0;
720 int i;
721 LARGE_INTEGER position;
722 HRESULT hr;
724 hr = read_ico_direntries(iconStream, &pIconDirEntry, &numEntries);
725 if (FAILED(hr))
726 goto end;
728 for (i = 0; i < numEntries; i++)
730 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
731 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
732 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
734 nIndex = i;
735 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
736 nMaxBits = pIconDirEntry[i].wBitCount;
739 WINE_TRACE("Selected: %d\n", nIndex);
741 position.QuadPart = 0;
742 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
743 if (FAILED(hr))
744 goto end;
745 hr = convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
747 end:
748 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
749 return hr;
752 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
754 WCHAR *extension;
755 WCHAR *icon = NULL;
756 WCHAR *comma;
757 WCHAR *executable = NULL;
758 int index = 0;
759 char *output_path = NULL;
760 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
762 extension = strrchrW(szFileName, '.');
763 if (extension == NULL)
764 goto end;
766 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
767 if (icon)
769 comma = strrchrW(icon, ',');
770 if (comma)
772 *comma = 0;
773 index = atoiW(comma + 1);
775 hr = open_icon(icon, index, FALSE, ppStream);
777 else
779 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, NULL);
780 if (executable)
781 hr = open_icon(executable, 0, FALSE, ppStream);
784 end:
785 HeapFree(GetProcessHeap(), 0, icon);
786 HeapFree(GetProcessHeap(), 0, executable);
787 HeapFree(GetProcessHeap(), 0, output_path);
788 return hr;
791 static HRESULT open_default_icon(IStream **ppStream)
793 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
795 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
798 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream)
800 HRESULT hr;
802 hr = open_module_icon(filename, index, ppStream);
803 if (FAILED(hr))
805 static const WCHAR dot_icoW[] = {'.','i','c','o',0};
806 int len = strlenW(filename);
807 if (len >= 4 && strcmpiW(&filename[len - 4], dot_icoW) == 0)
808 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
810 if (FAILED(hr))
811 hr = open_file_type_icon(filename, ppStream);
812 if (FAILED(hr) && !bWait)
813 hr = open_default_icon(ppStream);
814 return hr;
817 #ifdef __APPLE__
818 #define ICNS_SLOTS 6
820 static inline int size_to_slot(int size)
822 switch (size)
824 case 16: return 0;
825 case 32: return 1;
826 case 48: return 2;
827 case 128: return 3;
828 case 256: return 4;
829 case 512: return 5;
832 return -1;
835 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex, LPCWSTR icoPathW,
836 const char *destFilename, char **nativeIdentifier)
838 ICONDIRENTRY *iconDirEntries = NULL;
839 int numEntries;
840 struct {
841 int index;
842 int maxBits;
843 } best[ICNS_SLOTS];
844 int indexes[ICNS_SLOTS];
845 int i;
846 GUID guid;
847 WCHAR *guidStrW = NULL;
848 char *guidStrA = NULL;
849 char *icnsPath = NULL;
850 LARGE_INTEGER zero;
851 HRESULT hr;
853 hr = read_ico_direntries(icoStream, &iconDirEntries, &numEntries);
854 if (FAILED(hr))
855 goto end;
856 for (i = 0; i < ICNS_SLOTS; i++)
858 best[i].index = -1;
859 best[i].maxBits = 0;
861 for (i = 0; i < numEntries; i++)
863 int slot;
864 int width = iconDirEntries[i].bWidth ? iconDirEntries[i].bWidth : 256;
865 int height = iconDirEntries[i].bHeight ? iconDirEntries[i].bHeight : 256;
867 WINE_TRACE("[%d]: %d x %d @ %d\n", i, width, height, iconDirEntries[i].wBitCount);
868 if (height != width)
869 continue;
870 slot = size_to_slot(width);
871 if (slot < 0)
872 continue;
873 if (iconDirEntries[i].wBitCount >= best[slot].maxBits)
875 best[slot].index = i;
876 best[slot].maxBits = iconDirEntries[i].wBitCount;
879 numEntries = 0;
880 for (i = 0; i < ICNS_SLOTS; i++)
882 if (best[i].index >= 0)
884 indexes[numEntries] = best[i].index;
885 numEntries++;
889 hr = CoCreateGuid(&guid);
890 if (FAILED(hr))
892 WINE_WARN("CoCreateGuid failed, error 0x%08X\n", hr);
893 goto end;
895 hr = StringFromCLSID(&guid, &guidStrW);
896 if (FAILED(hr))
898 WINE_WARN("StringFromCLSID failed, error 0x%08X\n", hr);
899 goto end;
901 guidStrA = wchars_to_utf8_chars(guidStrW);
902 if (guidStrA == NULL)
904 hr = E_OUTOFMEMORY;
905 WINE_WARN("out of memory converting GUID string\n");
906 goto end;
908 icnsPath = heap_printf("/tmp/%s.icns", guidStrA);
909 if (icnsPath == NULL)
911 hr = E_OUTOFMEMORY;
912 WINE_WARN("out of memory creating ICNS path\n");
913 goto end;
915 zero.QuadPart = 0;
916 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
917 if (FAILED(hr))
919 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
920 goto end;
922 hr = convert_to_native_icon(icoStream, indexes, numEntries, &CLSID_WICIcnsEncoder,
923 icnsPath, icoPathW);
924 if (FAILED(hr))
926 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
927 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
928 goto end;
931 end:
932 HeapFree(GetProcessHeap(), 0, iconDirEntries);
933 CoTaskMemFree(guidStrW);
934 HeapFree(GetProcessHeap(), 0, guidStrA);
935 if (SUCCEEDED(hr))
936 *nativeIdentifier = icnsPath;
937 else
938 HeapFree(GetProcessHeap(), 0, icnsPath);
939 return hr;
941 #else
942 static void refresh_icon_cache(const char *iconsDir)
944 /* The icon theme spec only requires the mtime on the "toplevel"
945 * directory (whatever that is) to be changed for a refresh,
946 * but on Gnome you have to create a file in that directory
947 * instead. Creating a file also works on KDE, XFCE and LXDE.
949 char *filename = heap_printf("%s/.wine-refresh-XXXXXX", iconsDir);
950 if (filename != NULL)
952 int fd = mkstemps(filename, 0);
953 if (fd >= 0)
955 close(fd);
956 unlink(filename);
958 HeapFree(GetProcessHeap(), 0, filename);
962 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex, LPCWSTR icoPathW,
963 const char *destFilename, char **nativeIdentifier)
965 ICONDIRENTRY *iconDirEntries = NULL;
966 int numEntries;
967 int i;
968 char *icoPathA = NULL;
969 char *iconsDir = NULL;
970 unsigned short crc;
971 char *p, *q;
972 HRESULT hr = S_OK;
973 LARGE_INTEGER zero;
975 hr = read_ico_direntries(icoStream, &iconDirEntries, &numEntries);
976 if (FAILED(hr))
977 goto end;
979 icoPathA = wchars_to_utf8_chars(icoPathW);
980 if (icoPathA == NULL)
982 hr = E_OUTOFMEMORY;
983 goto end;
985 crc = crc16(icoPathA);
986 p = strrchr(icoPathA, '\\');
987 if (p == NULL)
988 p = icoPathA;
989 else
991 *p = 0;
992 p++;
994 q = strrchr(p, '.');
995 if (q)
996 *q = 0;
997 if (destFilename)
998 *nativeIdentifier = heap_printf("%s", destFilename);
999 else
1000 *nativeIdentifier = heap_printf("%04X_%s.%d", crc, p, exeIndex);
1001 if (*nativeIdentifier == NULL)
1003 hr = E_OUTOFMEMORY;
1004 goto end;
1006 iconsDir = heap_printf("%s/icons/hicolor", xdg_data_dir);
1007 if (iconsDir == NULL)
1009 hr = E_OUTOFMEMORY;
1010 goto end;
1013 for (i = 0; i < numEntries; i++)
1015 int bestIndex;
1016 int maxBits = -1;
1017 int j;
1018 BOOLEAN duplicate = FALSE;
1019 int w, h;
1020 char *iconDir = NULL;
1021 char *pngPath = NULL;
1023 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
1024 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
1026 for (j = 0; j < i; j++)
1028 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1029 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
1031 duplicate = TRUE;
1032 break;
1035 if (duplicate)
1036 continue;
1037 for (j = i; j < numEntries; j++)
1039 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1040 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1041 iconDirEntries[j].wBitCount >= maxBits)
1043 bestIndex = j;
1044 maxBits = iconDirEntries[j].wBitCount;
1047 WINE_TRACE("Selected: %d\n", bestIndex);
1049 w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
1050 h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
1051 iconDir = heap_printf("%s/%dx%d/apps", iconsDir, w, h);
1052 if (iconDir == NULL)
1054 hr = E_OUTOFMEMORY;
1055 goto endloop;
1057 create_directories(iconDir);
1058 pngPath = heap_printf("%s/%s.png", iconDir, *nativeIdentifier);
1059 if (pngPath == NULL)
1061 hr = E_OUTOFMEMORY;
1062 goto endloop;
1064 zero.QuadPart = 0;
1065 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1066 if (FAILED(hr))
1067 goto endloop;
1068 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
1069 pngPath, icoPathW);
1071 endloop:
1072 HeapFree(GetProcessHeap(), 0, iconDir);
1073 HeapFree(GetProcessHeap(), 0, pngPath);
1075 refresh_icon_cache(iconsDir);
1077 end:
1078 HeapFree(GetProcessHeap(), 0, iconDirEntries);
1079 HeapFree(GetProcessHeap(), 0, icoPathA);
1080 HeapFree(GetProcessHeap(), 0, iconsDir);
1081 return hr;
1083 #endif /* defined(__APPLE__) */
1085 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1086 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
1088 IStream *stream = NULL;
1089 HRESULT hr;
1090 char *nativeIdentifier = NULL;
1092 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
1094 hr = open_icon(icoPathW, index, bWait, &stream);
1095 if (FAILED(hr))
1097 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
1098 goto end;
1100 hr = platform_write_icon(stream, index, icoPathW, destFilename, &nativeIdentifier);
1101 if (FAILED(hr))
1102 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
1104 end:
1105 if (stream)
1106 IStream_Release(stream);
1107 if (FAILED(hr))
1109 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
1110 nativeIdentifier = NULL;
1112 return nativeIdentifier;
1115 static HKEY open_menus_reg_key(void)
1117 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1118 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1119 HKEY assocKey;
1120 DWORD ret;
1121 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1122 if (ret == ERROR_SUCCESS)
1123 return assocKey;
1124 SetLastError(ret);
1125 return NULL;
1128 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1130 WCHAR *unix_fileW;
1131 WCHAR *windows_fileW;
1132 INT size;
1133 DWORD ret;
1135 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1136 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1137 if (unix_fileW)
1139 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1140 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1141 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1142 if (windows_fileW)
1144 HKEY hkey;
1145 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1146 hkey = open_menus_reg_key();
1147 if (hkey)
1149 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1150 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1151 RegCloseKey(hkey);
1153 else
1154 ret = GetLastError();
1155 HeapFree(GetProcessHeap(), 0, windows_fileW);
1157 else
1158 ret = ERROR_NOT_ENOUGH_MEMORY;
1159 HeapFree(GetProcessHeap(), 0, unix_fileW);
1161 else
1162 ret = ERROR_NOT_ENOUGH_MEMORY;
1163 return ret;
1166 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1167 const char *path, const char *args, const char *descr,
1168 const char *workdir, const char *icon)
1170 FILE *file;
1172 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1173 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1174 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1176 file = fopen(location, "w");
1177 if (file == NULL)
1178 return FALSE;
1180 fprintf(file, "[Desktop Entry]\n");
1181 fprintf(file, "Name=%s\n", linkname);
1182 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1183 wine_get_config_dir(), path, args);
1184 fprintf(file, "Type=Application\n");
1185 fprintf(file, "StartupNotify=true\n");
1186 if (descr && lstrlenA(descr))
1187 fprintf(file, "Comment=%s\n", descr);
1188 if (workdir && lstrlenA(workdir))
1189 fprintf(file, "Path=%s\n", workdir);
1190 if (icon && lstrlenA(icon))
1191 fprintf(file, "Icon=%s\n", icon);
1193 fclose(file);
1195 if (unix_link)
1197 DWORD ret = register_menus_entry(location, unix_link);
1198 if (ret != ERROR_SUCCESS)
1199 return FALSE;
1202 return TRUE;
1205 static BOOL write_directory_entry(const char *directory, const char *location)
1207 FILE *file;
1209 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1211 file = fopen(location, "w");
1212 if (file == NULL)
1213 return FALSE;
1215 fprintf(file, "[Desktop Entry]\n");
1216 fprintf(file, "Type=Directory\n");
1217 if (strcmp(directory, "wine") == 0)
1219 fprintf(file, "Name=Wine\n");
1220 fprintf(file, "Icon=wine\n");
1222 else
1224 fprintf(file, "Name=%s\n", directory);
1225 fprintf(file, "Icon=folder\n");
1228 fclose(file);
1229 return TRUE;
1232 static BOOL write_menu_file(const char *unix_link, const char *filename)
1234 char *tempfilename;
1235 FILE *tempfile = NULL;
1236 char *lastEntry;
1237 char *name = NULL;
1238 char *menuPath = NULL;
1239 int i;
1240 int count = 0;
1241 BOOL ret = FALSE;
1243 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1245 while (1)
1247 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1248 if (tempfilename)
1250 int tempfd = mkstemps(tempfilename, 0);
1251 if (tempfd >= 0)
1253 tempfile = fdopen(tempfd, "w");
1254 if (tempfile)
1255 break;
1256 close(tempfd);
1257 goto end;
1259 else if (errno == EEXIST)
1261 HeapFree(GetProcessHeap(), 0, tempfilename);
1262 continue;
1264 HeapFree(GetProcessHeap(), 0, tempfilename);
1266 return FALSE;
1269 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1270 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1271 fprintf(tempfile, "<Menu>\n");
1272 fprintf(tempfile, " <Name>Applications</Name>\n");
1274 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1275 if (name == NULL) goto end;
1276 lastEntry = name;
1277 for (i = 0; filename[i]; i++)
1279 name[i] = filename[i];
1280 if (filename[i] == '/')
1282 char *dir_file_name;
1283 struct stat st;
1284 name[i] = 0;
1285 fprintf(tempfile, " <Menu>\n");
1286 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1287 write_xml_text(tempfile, name);
1288 fprintf(tempfile, "</Name>\n");
1289 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1290 write_xml_text(tempfile, name);
1291 fprintf(tempfile, ".directory</Directory>\n");
1292 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1293 xdg_data_dir, count ? "" : "wine-", name);
1294 if (dir_file_name)
1296 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1297 write_directory_entry(lastEntry, dir_file_name);
1298 HeapFree(GetProcessHeap(), 0, dir_file_name);
1300 name[i] = '-';
1301 lastEntry = &name[i+1];
1302 ++count;
1305 name[i] = 0;
1307 fprintf(tempfile, " <Include>\n");
1308 fprintf(tempfile, " <Filename>");
1309 write_xml_text(tempfile, name);
1310 fprintf(tempfile, "</Filename>\n");
1311 fprintf(tempfile, " </Include>\n");
1312 for (i = 0; i < count; i++)
1313 fprintf(tempfile, " </Menu>\n");
1314 fprintf(tempfile, "</Menu>\n");
1316 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1317 if (menuPath == NULL) goto end;
1318 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1319 ret = TRUE;
1321 end:
1322 if (tempfile)
1323 fclose(tempfile);
1324 if (ret)
1325 ret = (rename(tempfilename, menuPath) == 0);
1326 if (!ret && tempfilename)
1327 remove(tempfilename);
1328 HeapFree(GetProcessHeap(), 0, tempfilename);
1329 if (ret)
1330 register_menus_entry(menuPath, unix_link);
1331 HeapFree(GetProcessHeap(), 0, name);
1332 HeapFree(GetProcessHeap(), 0, menuPath);
1333 return ret;
1336 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1337 const char *descr, const char *workdir, const char *icon)
1339 const char *linkname;
1340 char *desktopPath = NULL;
1341 char *desktopDir;
1342 char *filename = NULL;
1343 BOOL ret = TRUE;
1345 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1346 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1347 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1349 linkname = strrchr(link, '/');
1350 if (linkname == NULL)
1351 linkname = link;
1352 else
1353 ++linkname;
1355 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1356 if (!desktopPath)
1358 WINE_WARN("out of memory creating menu entry\n");
1359 ret = FALSE;
1360 goto end;
1362 desktopDir = strrchr(desktopPath, '/');
1363 *desktopDir = 0;
1364 if (!create_directories(desktopPath))
1366 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1367 ret = FALSE;
1368 goto end;
1370 *desktopDir = '/';
1371 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1373 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1374 ret = FALSE;
1375 goto end;
1378 filename = heap_printf("wine/%s.desktop", link);
1379 if (!filename || !write_menu_file(unix_link, filename))
1381 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1382 ret = FALSE;
1385 end:
1386 HeapFree(GetProcessHeap(), 0, desktopPath);
1387 HeapFree(GetProcessHeap(), 0, filename);
1388 return ret;
1391 /* This escapes reserved characters in .desktop files' Exec keys. */
1392 static LPSTR escape(LPCWSTR arg)
1394 int i, j;
1395 WCHAR *escaped_string;
1396 char *utf8_string;
1398 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1399 if (escaped_string == NULL) return NULL;
1400 for (i = j = 0; arg[i]; i++)
1402 switch (arg[i])
1404 case '\\':
1405 escaped_string[j++] = '\\';
1406 escaped_string[j++] = '\\';
1407 escaped_string[j++] = '\\';
1408 escaped_string[j++] = '\\';
1409 break;
1410 case ' ':
1411 case '\t':
1412 case '\n':
1413 case '"':
1414 case '\'':
1415 case '>':
1416 case '<':
1417 case '~':
1418 case '|':
1419 case '&':
1420 case ';':
1421 case '$':
1422 case '*':
1423 case '?':
1424 case '#':
1425 case '(':
1426 case ')':
1427 case '`':
1428 escaped_string[j++] = '\\';
1429 escaped_string[j++] = '\\';
1430 /* fall through */
1431 default:
1432 escaped_string[j++] = arg[i];
1433 break;
1436 escaped_string[j] = 0;
1438 utf8_string = wchars_to_utf8_chars(escaped_string);
1439 if (utf8_string == NULL)
1441 WINE_ERR("out of memory\n");
1442 goto end;
1445 end:
1446 HeapFree(GetProcessHeap(), 0, escaped_string);
1447 return utf8_string;
1450 /* Return a heap-allocated copy of the unix format difference between the two
1451 * Windows-format paths.
1452 * locn is the owning location
1453 * link is within locn
1455 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1457 char *unix_locn, *unix_link;
1458 char *relative = NULL;
1460 unix_locn = wine_get_unix_file_name(locn);
1461 unix_link = wine_get_unix_file_name(link);
1462 if (unix_locn && unix_link)
1464 size_t len_unix_locn, len_unix_link;
1465 len_unix_locn = strlen (unix_locn);
1466 len_unix_link = strlen (unix_link);
1467 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1469 size_t len_rel;
1470 char *p = strrchr (unix_link + len_unix_locn, '/');
1471 p = strrchr (p, '.');
1472 if (p)
1474 *p = '\0';
1475 len_unix_link = p - unix_link;
1477 len_rel = len_unix_link - len_unix_locn;
1478 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1479 if (relative)
1481 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1485 if (!relative)
1486 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1487 HeapFree(GetProcessHeap(), 0, unix_locn);
1488 HeapFree(GetProcessHeap(), 0, unix_link);
1489 return relative;
1492 /***********************************************************************
1494 * GetLinkLocation
1496 * returns TRUE if successful
1497 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1498 * *relative will contain the address of a heap-allocated copy of the portion
1499 * of the filename that is within the specified location, in unix form
1501 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1503 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1504 DWORD len, i, r, filelen;
1505 const DWORD locations[] = {
1506 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1507 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1508 CSIDL_COMMON_STARTMENU };
1510 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1511 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1512 if (filelen==0 || filelen>MAX_PATH)
1513 return FALSE;
1515 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1517 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1518 * expand or our hardcoded list won't match.
1520 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1521 if (filelen==0 || filelen>MAX_PATH)
1522 return FALSE;
1524 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1526 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1528 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1529 continue;
1531 len = lstrlenW(buffer);
1532 if (len >= MAX_PATH)
1533 continue; /* We've just trashed memory! Hopefully we are OK */
1535 if (len > filelen || filename[len]!='\\')
1536 continue;
1537 /* do a lstrcmpinW */
1538 filename[len] = 0;
1539 r = lstrcmpiW( filename, buffer );
1540 filename[len] = '\\';
1541 if ( r )
1542 continue;
1544 /* return the remainder of the string and link type */
1545 *loc = locations[i];
1546 *relative = relative_path (filename, buffer);
1547 return (*relative != NULL);
1550 return FALSE;
1553 /* gets the target path directly or through MSI */
1554 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1555 LPWSTR szArgs, DWORD argsSize)
1557 IShellLinkDataList *dl = NULL;
1558 EXP_DARWIN_LINK *dar = NULL;
1559 HRESULT hr;
1561 szPath[0] = 0;
1562 szArgs[0] = 0;
1564 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1565 if (hr == S_OK && szPath[0])
1567 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1568 return hr;
1571 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1572 if (FAILED(hr))
1573 return hr;
1575 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1576 if (SUCCEEDED(hr))
1578 WCHAR* szCmdline;
1579 DWORD cmdSize;
1581 cmdSize=0;
1582 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1583 if (hr == ERROR_SUCCESS)
1585 cmdSize++;
1586 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1587 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1588 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1589 if (hr == ERROR_SUCCESS)
1591 WCHAR *s, *d;
1592 int bcount, in_quotes;
1594 /* Extract the application path */
1595 bcount=0;
1596 in_quotes=0;
1597 s=szCmdline;
1598 d=szPath;
1599 while (*s)
1601 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1603 /* skip the remaining spaces */
1604 do {
1605 s++;
1606 } while (*s==0x0009 || *s==0x0020);
1607 break;
1609 else if (*s==0x005c)
1611 /* '\\' */
1612 *d++=*s++;
1613 bcount++;
1615 else if (*s==0x0022)
1617 /* '"' */
1618 if ((bcount & 1)==0)
1620 /* Preceded by an even number of '\', this is
1621 * half that number of '\', plus a quote which
1622 * we erase.
1624 d-=bcount/2;
1625 in_quotes=!in_quotes;
1626 s++;
1628 else
1630 /* Preceded by an odd number of '\', this is
1631 * half that number of '\' followed by a '"'
1633 d=d-bcount/2-1;
1634 *d++='"';
1635 s++;
1637 bcount=0;
1639 else
1641 /* a regular character */
1642 *d++=*s++;
1643 bcount=0;
1645 if ((d-szPath) == pathSize)
1647 /* Keep processing the path till we get to the
1648 * arguments, but 'stand still'
1650 d--;
1653 /* Close the application path */
1654 *d=0;
1656 lstrcpynW(szArgs, s, argsSize);
1658 HeapFree( GetProcessHeap(), 0, szCmdline );
1660 LocalFree( dar );
1663 IShellLinkDataList_Release( dl );
1664 return hr;
1667 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1669 HRESULT hr;
1670 WCHAR *value = NULL;
1671 DWORD size = 0;
1672 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1673 if (SUCCEEDED(hr))
1675 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1676 if (value)
1678 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1679 if (FAILED(hr))
1681 HeapFree(GetProcessHeap(), 0, value);
1682 value = NULL;
1686 return value;
1689 static char *slashes_to_minuses(const char *string)
1691 int i;
1692 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1693 if (ret)
1695 for (i = 0; string[i]; i++)
1697 if (string[i] == '/')
1698 ret[i] = '-';
1699 else
1700 ret[i] = string[i];
1702 ret[i] = 0;
1703 return ret;
1705 return NULL;
1708 static BOOL next_line(FILE *file, char **line, int *size)
1710 int pos = 0;
1711 char *cr;
1712 if (*line == NULL)
1714 *size = 4096;
1715 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1717 while (*line != NULL)
1719 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1721 HeapFree(GetProcessHeap(), 0, *line);
1722 *line = NULL;
1723 if (feof(file))
1724 return TRUE;
1725 return FALSE;
1727 pos = strlen(*line);
1728 cr = strchr(*line, '\n');
1729 if (cr == NULL)
1731 char *line2;
1732 (*size) *= 2;
1733 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1734 if (line2)
1735 *line = line2;
1736 else
1738 HeapFree(GetProcessHeap(), 0, *line);
1739 *line = NULL;
1742 else
1744 *cr = 0;
1745 return TRUE;
1748 return FALSE;
1751 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1753 char *globs_filename = NULL;
1754 BOOL ret = TRUE;
1755 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1756 if (globs_filename)
1758 FILE *globs_file = fopen(globs_filename, "r");
1759 if (globs_file) /* doesn't have to exist */
1761 char *line = NULL;
1762 int size = 0;
1763 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1765 char *pos;
1766 struct xdg_mime_type *mime_type_entry = NULL;
1767 if (line[0] != '#' && (pos = strchr(line, ':')))
1769 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1770 if (mime_type_entry)
1772 *pos = 0;
1773 mime_type_entry->mimeType = strdupA(line);
1774 mime_type_entry->glob = strdupA(pos + 1);
1775 if (mime_type_entry->mimeType && mime_type_entry->glob)
1776 list_add_tail(mime_types, &mime_type_entry->entry);
1777 else
1779 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1780 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1781 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1782 ret = FALSE;
1785 else
1786 ret = FALSE;
1789 HeapFree(GetProcessHeap(), 0, line);
1790 fclose(globs_file);
1792 HeapFree(GetProcessHeap(), 0, globs_filename);
1794 else
1795 ret = FALSE;
1796 return ret;
1799 static void free_native_mime_types(struct list *native_mime_types)
1801 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1803 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1805 list_remove(&mime_type_entry->entry);
1806 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1807 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1808 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1810 HeapFree(GetProcessHeap(), 0, native_mime_types);
1813 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1815 char *xdg_data_dirs;
1816 BOOL ret;
1818 *mime_types = NULL;
1820 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1821 if (xdg_data_dirs == NULL)
1822 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1823 else
1824 xdg_data_dirs = strdupA(xdg_data_dirs);
1826 if (xdg_data_dirs)
1828 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1829 if (*mime_types)
1831 const char *begin;
1832 char *end;
1834 list_init(*mime_types);
1835 ret = add_mimes(xdg_data_home, *mime_types);
1836 if (ret)
1838 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1840 *end = '\0';
1841 ret = add_mimes(begin, *mime_types);
1842 *end = ':';
1843 if (!ret)
1844 break;
1846 if (ret)
1847 ret = add_mimes(begin, *mime_types);
1850 else
1851 ret = FALSE;
1852 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1854 else
1855 ret = FALSE;
1856 if (!ret && *mime_types)
1858 free_native_mime_types(*mime_types);
1859 *mime_types = NULL;
1861 return ret;
1864 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1865 char **match)
1867 #ifdef HAVE_FNMATCH
1868 struct xdg_mime_type *mime_type_entry;
1869 int matchLength = 0;
1871 *match = NULL;
1873 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1875 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1877 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1879 *match = mime_type_entry->mimeType;
1880 matchLength = strlen(mime_type_entry->glob);
1885 if (*match != NULL)
1887 *match = strdupA(*match);
1888 if (*match == NULL)
1889 return FALSE;
1891 #else
1892 *match = NULL;
1893 #endif
1894 return TRUE;
1897 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1898 const char *extensionA,
1899 LPCWSTR extensionW,
1900 char **mime_type)
1902 WCHAR *lower_extensionW;
1903 INT len;
1904 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1905 if (ret == FALSE || *mime_type != NULL)
1906 return ret;
1907 len = strlenW(extensionW);
1908 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1909 if (lower_extensionW)
1911 char *lower_extensionA;
1912 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1913 strlwrW(lower_extensionW);
1914 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1915 if (lower_extensionA)
1917 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1918 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1920 else
1922 ret = FALSE;
1923 WINE_FIXME("out of memory\n");
1925 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1927 else
1929 ret = FALSE;
1930 WINE_FIXME("out of memory\n");
1932 return ret;
1935 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1937 DWORD size;
1938 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1940 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1941 if (ret)
1943 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1944 return ret;
1946 HeapFree(GetProcessHeap(), 0, ret);
1948 return NULL;
1951 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
1953 WCHAR *valW = reg_get_valW(key, subkey, name);
1954 if (valW)
1956 char *val = wchars_to_utf8_chars(valW);
1957 HeapFree(GetProcessHeap(), 0, valW);
1958 return val;
1960 return NULL;
1963 static HKEY open_associations_reg_key(void)
1965 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1966 '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};
1967 HKEY assocKey;
1968 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1969 return assocKey;
1970 return NULL;
1973 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
1974 LPCSTR appName, LPCWSTR docName, LPCSTR openWithIcon)
1976 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1977 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1978 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1979 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1980 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
1981 HKEY assocKey;
1982 BOOL ret;
1984 if ((assocKey = open_associations_reg_key()))
1986 CHAR *valueA;
1987 WCHAR *value;
1989 ret = FALSE;
1991 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
1992 if (!valueA || lstrcmpA(valueA, mimeType))
1993 ret = TRUE;
1994 HeapFree(GetProcessHeap(), 0, valueA);
1996 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1997 if (!value || strcmpW(value, progId))
1998 ret = TRUE;
1999 HeapFree(GetProcessHeap(), 0, value);
2001 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2002 if (!valueA || lstrcmpA(valueA, appName))
2003 ret = TRUE;
2004 HeapFree(GetProcessHeap(), 0, valueA);
2006 value = reg_get_valW(assocKey, extensionW, DocNameW);
2007 if (docName && (!value || strcmpW(value, docName)))
2008 ret = TRUE;
2009 HeapFree(GetProcessHeap(), 0, value);
2011 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
2012 if ((openWithIcon && !valueA) ||
2013 (!openWithIcon && valueA) ||
2014 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
2015 ret = TRUE;
2016 HeapFree(GetProcessHeap(), 0, valueA);
2018 RegCloseKey(assocKey);
2020 else
2022 WINE_ERR("error opening associations registry key\n");
2023 ret = FALSE;
2025 return ret;
2028 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2029 LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile, LPCSTR openWithIcon)
2031 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2032 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
2033 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2034 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2035 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2036 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2037 HKEY assocKey = NULL;
2038 HKEY subkey = NULL;
2039 WCHAR *mimeTypeW = NULL;
2040 WCHAR *appNameW = NULL;
2041 WCHAR *desktopFileW = NULL;
2042 WCHAR *openWithIconW = NULL;
2044 assocKey = open_associations_reg_key();
2045 if (assocKey == NULL)
2047 WINE_ERR("could not open file associations key\n");
2048 goto done;
2051 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2053 WINE_ERR("could not create extension subkey\n");
2054 goto done;
2057 mimeTypeW = utf8_chars_to_wchars(mimeType);
2058 if (mimeTypeW == NULL)
2060 WINE_ERR("out of memory\n");
2061 goto done;
2064 appNameW = utf8_chars_to_wchars(appName);
2065 if (appNameW == NULL)
2067 WINE_ERR("out of memory\n");
2068 goto done;
2071 desktopFileW = utf8_chars_to_wchars(desktopFile);
2072 if (desktopFileW == NULL)
2074 WINE_ERR("out of memory\n");
2075 goto done;
2078 if (openWithIcon)
2080 openWithIconW = utf8_chars_to_wchars(openWithIcon);
2081 if (openWithIconW == NULL)
2083 WINE_ERR("out of memory\n");
2084 goto done;
2088 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2089 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2090 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2091 if (docName)
2092 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
2093 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2094 if (openWithIcon)
2095 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
2096 else
2097 RegDeleteValueW(subkey, OpenWithIconW);
2099 done:
2100 RegCloseKey(assocKey);
2101 RegCloseKey(subkey);
2102 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2103 HeapFree(GetProcessHeap(), 0, appNameW);
2104 HeapFree(GetProcessHeap(), 0, desktopFileW);
2105 HeapFree(GetProcessHeap(), 0, openWithIconW);
2108 static BOOL cleanup_associations(void)
2110 static const WCHAR openW[] = {'o','p','e','n',0};
2111 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2112 HKEY assocKey;
2113 BOOL hasChanged = FALSE;
2114 if ((assocKey = open_associations_reg_key()))
2116 int i;
2117 BOOL done = FALSE;
2118 for (i = 0; !done; i++)
2120 WCHAR *extensionW = NULL;
2121 DWORD size = 1024;
2122 LSTATUS ret;
2126 HeapFree(GetProcessHeap(), 0, extensionW);
2127 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2128 if (extensionW == NULL)
2130 WINE_ERR("out of memory\n");
2131 ret = ERROR_OUTOFMEMORY;
2132 break;
2134 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2135 size *= 2;
2136 } while (ret == ERROR_MORE_DATA);
2138 if (ret == ERROR_SUCCESS)
2140 WCHAR *command;
2141 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2142 if (command == NULL)
2144 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2145 if (desktopFile)
2147 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2148 remove(desktopFile);
2150 RegDeleteKeyW(assocKey, extensionW);
2151 hasChanged = TRUE;
2152 HeapFree(GetProcessHeap(), 0, desktopFile);
2154 HeapFree(GetProcessHeap(), 0, command);
2156 else
2158 if (ret != ERROR_NO_MORE_ITEMS)
2159 WINE_ERR("error %d while reading registry\n", ret);
2160 done = TRUE;
2162 HeapFree(GetProcessHeap(), 0, extensionW);
2164 RegCloseKey(assocKey);
2166 else
2167 WINE_ERR("could not open file associations key\n");
2168 return hasChanged;
2171 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2172 const char *mime_type, const char *comment)
2174 BOOL ret = FALSE;
2175 char *filename;
2177 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2178 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2180 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2181 if (filename)
2183 FILE *packageFile = fopen(filename, "w");
2184 if (packageFile)
2186 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2187 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2188 fprintf(packageFile, " <mime-type type=\"");
2189 write_xml_text(packageFile, mime_type);
2190 fprintf(packageFile, "\">\n");
2191 fprintf(packageFile, " <glob pattern=\"*");
2192 write_xml_text(packageFile, dot_extension);
2193 fprintf(packageFile, "\"/>\n");
2194 if (comment)
2196 fprintf(packageFile, " <comment>");
2197 write_xml_text(packageFile, comment);
2198 fprintf(packageFile, "</comment>\n");
2200 fprintf(packageFile, " </mime-type>\n");
2201 fprintf(packageFile, "</mime-info>\n");
2202 ret = TRUE;
2203 fclose(packageFile);
2205 else
2206 WINE_ERR("error writing file %s\n", filename);
2207 HeapFree(GetProcessHeap(), 0, filename);
2209 else
2210 WINE_ERR("out of memory\n");
2211 return ret;
2214 static BOOL is_extension_blacklisted(LPCWSTR extension)
2216 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2217 static const WCHAR comW[] = {'.','c','o','m',0};
2218 static const WCHAR exeW[] = {'.','e','x','e',0};
2219 static const WCHAR msiW[] = {'.','m','s','i',0};
2221 if (!strcmpiW(extension, comW) ||
2222 !strcmpiW(extension, exeW) ||
2223 !strcmpiW(extension, msiW))
2224 return TRUE;
2225 return FALSE;
2228 static const char* get_special_mime_type(LPCWSTR extension)
2230 static const WCHAR lnkW[] = {'.','l','n','k',0};
2231 if (!strcmpiW(extension, lnkW))
2232 return "application/x-ms-shortcut";
2233 return NULL;
2236 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2237 const char *friendlyAppName, const char *mimeType,
2238 const char *progId, const char *openWithIcon)
2240 BOOL ret = FALSE;
2241 FILE *desktop;
2243 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2244 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2245 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2247 desktop = fopen(desktopPath, "w");
2248 if (desktop)
2250 fprintf(desktop, "[Desktop Entry]\n");
2251 fprintf(desktop, "Type=Application\n");
2252 fprintf(desktop, "Name=%s\n", friendlyAppName);
2253 fprintf(desktop, "MimeType=%s;\n", mimeType);
2254 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
2255 fprintf(desktop, "NoDisplay=true\n");
2256 fprintf(desktop, "StartupNotify=true\n");
2257 if (openWithIcon)
2258 fprintf(desktop, "Icon=%s\n", openWithIcon);
2259 ret = TRUE;
2260 fclose(desktop);
2262 else
2263 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2264 return ret;
2267 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2269 static const WCHAR openW[] = {'o','p','e','n',0};
2270 struct wine_rb_tree mimeProgidTree;
2271 struct list *nativeMimeTypes = NULL;
2272 LSTATUS ret = 0;
2273 int i;
2274 BOOL hasChanged = FALSE;
2276 if (wine_rb_init(&mimeProgidTree, &winemenubuilder_rb_functions))
2278 WINE_ERR("wine_rb_init failed\n");
2279 return FALSE;
2281 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2283 WINE_ERR("could not build native MIME types\n");
2284 return FALSE;
2287 for (i = 0; ; i++)
2289 WCHAR *extensionW = NULL;
2290 DWORD size = 1024;
2294 HeapFree(GetProcessHeap(), 0, extensionW);
2295 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2296 if (extensionW == NULL)
2298 WINE_ERR("out of memory\n");
2299 ret = ERROR_OUTOFMEMORY;
2300 break;
2302 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2303 size *= 2;
2304 } while (ret == ERROR_MORE_DATA);
2306 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2308 char *extensionA = NULL;
2309 WCHAR *commandW = NULL;
2310 WCHAR *executableW = NULL;
2311 char *openWithIconA = NULL;
2312 WCHAR *friendlyDocNameW = NULL;
2313 char *friendlyDocNameA = NULL;
2314 WCHAR *iconW = NULL;
2315 char *iconA = NULL;
2316 WCHAR *contentTypeW = NULL;
2317 char *mimeTypeA = NULL;
2318 WCHAR *friendlyAppNameW = NULL;
2319 char *friendlyAppNameA = NULL;
2320 WCHAR *progIdW = NULL;
2321 char *progIdA = NULL;
2322 char *mimeProgId = NULL;
2324 extensionA = wchars_to_utf8_chars(extensionW);
2325 if (extensionA == NULL)
2327 WINE_ERR("out of memory\n");
2328 goto end;
2331 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2332 if (friendlyDocNameW)
2334 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2335 if (friendlyDocNameA == NULL)
2337 WINE_ERR("out of memory\n");
2338 goto end;
2342 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2344 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2345 if (contentTypeW)
2346 strlwrW(contentTypeW);
2348 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2349 goto end;
2351 if (mimeTypeA == NULL)
2353 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2354 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2355 else if ((get_special_mime_type(extensionW)))
2356 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2357 else
2358 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2360 if (mimeTypeA != NULL)
2362 /* Gnome seems to ignore the <icon> tag in MIME packages,
2363 * and the default name is more intuitive anyway.
2365 if (iconW)
2367 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2368 if (flattened_mime)
2370 int index = 0;
2371 WCHAR *comma = strrchrW(iconW, ',');
2372 if (comma)
2374 *comma = 0;
2375 index = atoiW(comma + 1);
2377 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2378 HeapFree(GetProcessHeap(), 0, flattened_mime);
2382 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2383 hasChanged = TRUE;
2385 else
2387 WINE_FIXME("out of memory\n");
2388 goto end;
2392 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2393 if (commandW == NULL)
2394 /* no command => no application is associated */
2395 goto end;
2397 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2398 if (executableW)
2399 openWithIconA = extract_icon(executableW, 0, NULL, FALSE);
2401 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2402 if (friendlyAppNameW)
2404 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2405 if (friendlyAppNameA == NULL)
2407 WINE_ERR("out of memory\n");
2408 goto end;
2411 else
2413 friendlyAppNameA = heap_printf("A Wine application");
2414 if (friendlyAppNameA == NULL)
2416 WINE_ERR("out of memory\n");
2417 goto end;
2421 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2422 if (progIdW)
2424 progIdA = escape(progIdW);
2425 if (progIdA == NULL)
2427 WINE_ERR("out of memory\n");
2428 goto end;
2431 else
2432 goto end; /* no progID => not a file type association */
2434 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2435 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2436 if (mimeProgId)
2438 struct rb_string_entry *entry;
2439 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2441 HeapFree(GetProcessHeap(), 0, mimeProgId);
2442 goto end;
2444 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2445 if (!entry)
2447 WINE_ERR("out of memory allocating rb_string_entry\n");
2448 goto end;
2450 entry->string = mimeProgId;
2451 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2453 WINE_ERR("error updating rb tree\n");
2454 goto end;
2458 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, openWithIconA))
2460 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2461 if (desktopPath)
2463 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2465 hasChanged = TRUE;
2466 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath, openWithIconA);
2468 HeapFree(GetProcessHeap(), 0, desktopPath);
2472 end:
2473 HeapFree(GetProcessHeap(), 0, extensionA);
2474 HeapFree(GetProcessHeap(), 0, commandW);
2475 HeapFree(GetProcessHeap(), 0, executableW);
2476 HeapFree(GetProcessHeap(), 0, openWithIconA);
2477 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2478 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2479 HeapFree(GetProcessHeap(), 0, iconW);
2480 HeapFree(GetProcessHeap(), 0, iconA);
2481 HeapFree(GetProcessHeap(), 0, contentTypeW);
2482 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2483 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2484 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2485 HeapFree(GetProcessHeap(), 0, progIdW);
2486 HeapFree(GetProcessHeap(), 0, progIdA);
2488 HeapFree(GetProcessHeap(), 0, extensionW);
2489 if (ret != ERROR_SUCCESS)
2490 break;
2493 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2494 free_native_mime_types(nativeMimeTypes);
2495 return hasChanged;
2498 static char *get_start_exe_path(void)
2500 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2501 '\\','s','t','a','r','t','.','e','x','e',0};
2502 WCHAR start_path[MAX_PATH];
2503 GetWindowsDirectoryW(start_path, MAX_PATH);
2504 lstrcatW(start_path, startW);
2505 return escape(start_path);
2508 static char* escape_unix_link_arg(LPCSTR unix_link)
2510 char *ret = NULL;
2511 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2512 if (unix_linkW)
2514 char *escaped_lnk = escape(unix_linkW);
2515 if (escaped_lnk)
2517 ret = heap_printf("/Unix %s", escaped_lnk);
2518 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2520 HeapFree(GetProcessHeap(), 0, unix_linkW);
2522 return ret;
2525 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2527 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2528 '\\','s','t','a','r','t','.','e','x','e',0};
2529 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2530 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2531 WCHAR szTmp[INFOTIPSIZE];
2532 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2533 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2534 int iIconId = 0, r = -1;
2535 DWORD csidl = -1;
2536 HANDLE hsem = NULL;
2537 char *unix_link = NULL;
2538 char *start_path = NULL;
2540 if ( !link )
2542 WINE_ERR("Link name is null\n");
2543 return FALSE;
2546 if( !GetLinkLocation( link, &csidl, &link_name ) )
2548 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2549 return TRUE;
2551 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2553 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2554 return TRUE;
2556 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2558 szTmp[0] = 0;
2559 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2560 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2561 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2563 szTmp[0] = 0;
2564 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2565 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2566 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2568 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2569 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2570 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2571 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2573 szTmp[0] = 0;
2574 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2575 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2576 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2578 if( !szPath[0] )
2580 LPITEMIDLIST pidl = NULL;
2581 IShellLinkW_GetIDList( sl, &pidl );
2582 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2583 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2586 /* extract the icon */
2587 if( szIconPath[0] )
2588 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2589 else
2590 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2592 /* fail - try once again after parent process exit */
2593 if( !icon_name )
2595 if (bWait)
2597 WINE_WARN("Unable to extract icon, deferring.\n");
2598 goto cleanup;
2600 WINE_ERR("failed to extract icon from %s\n",
2601 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2604 unix_link = wine_get_unix_file_name(link);
2605 if (unix_link == NULL)
2607 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2608 goto cleanup;
2611 /* check the path */
2612 if( szPath[0] )
2614 static const WCHAR exeW[] = {'.','e','x','e',0};
2615 WCHAR *p;
2617 /* check for .exe extension */
2618 if (!(p = strrchrW( szPath, '.' )) ||
2619 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2620 lstrcmpiW( p, exeW ))
2622 /* Not .exe - use 'start.exe' to launch this file */
2623 p = szArgs + lstrlenW(szPath) + 2;
2624 if (szArgs[0])
2626 p[0] = ' ';
2627 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2628 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2630 else
2631 p[0] = 0;
2633 szArgs[0] = '"';
2634 lstrcpyW(szArgs + 1, szPath);
2635 p[-1] = '"';
2637 GetWindowsDirectoryW(szPath, MAX_PATH);
2638 lstrcatW(szPath, startW);
2641 /* convert app working dir */
2642 if (szWorkDir[0])
2643 work_dir = wine_get_unix_file_name( szWorkDir );
2645 else
2647 /* if there's no path... try run the link itself */
2648 lstrcpynW(szArgs, link, MAX_PATH);
2649 GetWindowsDirectoryW(szPath, MAX_PATH);
2650 lstrcatW(szPath, startW);
2653 /* escape the path and parameters */
2654 escaped_path = escape(szPath);
2655 escaped_args = escape(szArgs);
2656 description = wchars_to_utf8_chars(szDescription);
2657 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2659 WINE_ERR("out of memory allocating/escaping parameters\n");
2660 goto cleanup;
2663 start_path = get_start_exe_path();
2664 if (start_path == NULL)
2666 WINE_ERR("out of memory\n");
2667 goto cleanup;
2670 /* building multiple menus concurrently has race conditions */
2671 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2672 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2674 WINE_ERR("failed wait for semaphore\n");
2675 goto cleanup;
2678 if (in_desktop_dir(csidl))
2680 char *location;
2681 const char *lastEntry;
2682 lastEntry = strrchr(link_name, '/');
2683 if (lastEntry == NULL)
2684 lastEntry = link_name;
2685 else
2686 ++lastEntry;
2687 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2688 if (location)
2690 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2692 char *link_arg = escape_unix_link_arg(unix_link);
2693 if (link_arg)
2695 r = !write_desktop_entry(unix_link, location, lastEntry,
2696 start_path, link_arg, description, work_dir, icon_name);
2697 HeapFree(GetProcessHeap(), 0, link_arg);
2700 else
2701 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2702 if (r == 0)
2703 chmod(location, 0755);
2704 HeapFree(GetProcessHeap(), 0, location);
2707 else
2709 char *link_arg = escape_unix_link_arg(unix_link);
2710 if (link_arg)
2712 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name);
2713 HeapFree(GetProcessHeap(), 0, link_arg);
2717 ReleaseSemaphore( hsem, 1, NULL );
2719 cleanup:
2720 if (hsem) CloseHandle( hsem );
2721 HeapFree( GetProcessHeap(), 0, icon_name );
2722 HeapFree( GetProcessHeap(), 0, work_dir );
2723 HeapFree( GetProcessHeap(), 0, link_name );
2724 HeapFree( GetProcessHeap(), 0, escaped_args );
2725 HeapFree( GetProcessHeap(), 0, escaped_path );
2726 HeapFree( GetProcessHeap(), 0, description );
2727 HeapFree( GetProcessHeap(), 0, unix_link );
2728 HeapFree( GetProcessHeap(), 0, start_path );
2730 if (r && !bWait)
2731 WINE_ERR("failed to build the menu\n" );
2733 return ( r == 0 );
2736 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2738 char *link_name = NULL, *icon_name = NULL;
2739 DWORD csidl = -1;
2740 LPWSTR urlPath;
2741 char *escaped_urlPath = NULL;
2742 HRESULT hr;
2743 HANDLE hSem = NULL;
2744 BOOL ret = TRUE;
2745 int r = -1;
2746 char *unix_link = NULL;
2747 IPropertySetStorage *pPropSetStg;
2748 IPropertyStorage *pPropStg;
2749 PROPSPEC ps[2];
2750 PROPVARIANT pv[2];
2752 if ( !link )
2754 WINE_ERR("Link name is null\n");
2755 return TRUE;
2758 if( !GetLinkLocation( link, &csidl, &link_name ) )
2760 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2761 return TRUE;
2763 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2765 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2766 ret = TRUE;
2767 goto cleanup;
2769 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2771 hr = url->lpVtbl->GetURL(url, &urlPath);
2772 if (FAILED(hr))
2774 ret = TRUE;
2775 goto cleanup;
2777 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2779 unix_link = wine_get_unix_file_name(link);
2780 if (unix_link == NULL)
2782 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2783 goto cleanup;
2786 escaped_urlPath = escape(urlPath);
2787 if (escaped_urlPath == NULL)
2789 WINE_ERR("couldn't escape url, out of memory\n");
2790 goto cleanup;
2793 ps[0].ulKind = PRSPEC_PROPID;
2794 ps[0].u.propid = PID_IS_ICONFILE;
2795 ps[1].ulKind = PRSPEC_PROPID;
2796 ps[1].u.propid = PID_IS_ICONINDEX;
2798 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
2799 if (SUCCEEDED(hr))
2801 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
2802 if (SUCCEEDED(hr))
2804 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
2805 if (SUCCEEDED(hr))
2807 if (pv[0].vt == VT_LPWSTR && pv[0].u.pwszVal)
2809 icon_name = extract_icon( pv[0].u.pwszVal, pv[1].u.iVal, NULL, bWait );
2811 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);
2813 PropVariantClear(&pv[0]);
2814 PropVariantClear(&pv[1]);
2816 IPropertyStorage_Release(pPropStg);
2818 IPropertySetStorage_Release(pPropSetStg);
2821 /* fail - try once again after parent process exit */
2822 if( !icon_name )
2824 if (bWait)
2826 WINE_WARN("Unable to extract icon, deferring.\n");
2827 ret = FALSE;
2828 goto cleanup;
2830 WINE_ERR("failed to extract icon from %s\n",
2831 wine_dbgstr_w( pv[0].u.pwszVal ));
2834 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2835 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2837 WINE_ERR("failed wait for semaphore\n");
2838 goto cleanup;
2840 if (in_desktop_dir(csidl))
2842 char *location;
2843 const char *lastEntry;
2844 lastEntry = strrchr(link_name, '/');
2845 if (lastEntry == NULL)
2846 lastEntry = link_name;
2847 else
2848 ++lastEntry;
2849 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2850 if (location)
2852 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, icon_name);
2853 if (r == 0)
2854 chmod(location, 0755);
2855 HeapFree(GetProcessHeap(), 0, location);
2858 else
2859 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, icon_name);
2860 ret = (r != 0);
2861 ReleaseSemaphore(hSem, 1, NULL);
2863 cleanup:
2864 if (hSem)
2865 CloseHandle(hSem);
2866 HeapFree( GetProcessHeap(), 0, icon_name );
2867 HeapFree(GetProcessHeap(), 0, link_name);
2868 CoTaskMemFree( urlPath );
2869 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2870 HeapFree(GetProcessHeap(), 0, unix_link);
2871 return ret;
2874 static BOOL WaitForParentProcess( void )
2876 PROCESSENTRY32 procentry;
2877 HANDLE hsnapshot = NULL, hprocess = NULL;
2878 DWORD ourpid = GetCurrentProcessId();
2879 BOOL ret = FALSE, rc;
2881 WINE_TRACE("Waiting for parent process\n");
2882 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2883 INVALID_HANDLE_VALUE)
2885 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2886 goto done;
2889 procentry.dwSize = sizeof(PROCESSENTRY32);
2890 rc = Process32First( hsnapshot, &procentry );
2891 while (rc)
2893 if (procentry.th32ProcessID == ourpid) break;
2894 rc = Process32Next( hsnapshot, &procentry );
2896 if (!rc)
2898 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2899 goto done;
2902 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2903 NULL)
2905 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2906 GetLastError());
2907 goto done;
2910 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2911 ret = TRUE;
2912 else
2913 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2915 done:
2916 if (hprocess) CloseHandle( hprocess );
2917 if (hsnapshot) CloseHandle( hsnapshot );
2918 return ret;
2921 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2923 IShellLinkW *sl;
2924 IPersistFile *pf;
2925 HRESULT r;
2926 WCHAR fullname[MAX_PATH];
2927 DWORD len;
2929 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2931 if( !linkname[0] )
2933 WINE_ERR("link name missing\n");
2934 return 1;
2937 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2938 if (len==0 || len>MAX_PATH)
2940 WINE_ERR("couldn't get full path of link file\n");
2941 return 1;
2944 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2945 &IID_IShellLinkW, (LPVOID *) &sl );
2946 if( FAILED( r ) )
2948 WINE_ERR("No IID_IShellLink\n");
2949 return 1;
2952 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2953 if( FAILED( r ) )
2955 WINE_ERR("No IID_IPersistFile\n");
2956 return 1;
2959 r = IPersistFile_Load( pf, fullname, STGM_READ );
2960 if( SUCCEEDED( r ) )
2962 /* If something fails (eg. Couldn't extract icon)
2963 * wait for parent process and try again
2965 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2967 WaitForParentProcess();
2968 InvokeShellLinker( sl, fullname, FALSE );
2971 else
2973 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2976 IPersistFile_Release( pf );
2977 IShellLinkW_Release( sl );
2979 return !r;
2982 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2984 IUniformResourceLocatorW *url;
2985 IPersistFile *pf;
2986 HRESULT r;
2987 WCHAR fullname[MAX_PATH];
2988 DWORD len;
2990 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2992 if( !urlname[0] )
2994 WINE_ERR("URL name missing\n");
2995 return 1;
2998 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2999 if (len==0 || len>MAX_PATH)
3001 WINE_ERR("couldn't get full path of URL file\n");
3002 return 1;
3005 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
3006 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
3007 if( FAILED( r ) )
3009 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3010 return 1;
3013 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
3014 if( FAILED( r ) )
3016 WINE_ERR("No IID_IPersistFile\n");
3017 return 1;
3019 r = IPersistFile_Load( pf, fullname, STGM_READ );
3020 if( SUCCEEDED( r ) )
3022 /* If something fails (eg. Couldn't extract icon)
3023 * wait for parent process and try again
3025 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
3027 WaitForParentProcess();
3028 InvokeShellLinkerForURL( url, fullname, FALSE );
3032 IPersistFile_Release( pf );
3033 url->lpVtbl->Release( url );
3035 return !r;
3038 static void RefreshFileTypeAssociations(void)
3040 HANDLE hSem = NULL;
3041 char *mime_dir = NULL;
3042 char *packages_dir = NULL;
3043 char *applications_dir = NULL;
3044 BOOL hasChanged;
3046 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3047 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3049 WINE_ERR("failed wait for semaphore\n");
3050 CloseHandle(hSem);
3051 hSem = NULL;
3052 goto end;
3055 mime_dir = heap_printf("%s/mime", xdg_data_dir);
3056 if (mime_dir == NULL)
3058 WINE_ERR("out of memory\n");
3059 goto end;
3061 create_directories(mime_dir);
3063 packages_dir = heap_printf("%s/packages", mime_dir);
3064 if (packages_dir == NULL)
3066 WINE_ERR("out of memory\n");
3067 goto end;
3069 create_directories(packages_dir);
3071 applications_dir = heap_printf("%s/applications", xdg_data_dir);
3072 if (applications_dir == NULL)
3074 WINE_ERR("out of memory\n");
3075 goto end;
3077 create_directories(applications_dir);
3079 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3080 hasChanged |= cleanup_associations();
3081 if (hasChanged)
3083 const char *argv[3];
3085 argv[0] = "update-mime-database";
3086 argv[1] = mime_dir;
3087 argv[2] = NULL;
3088 spawnvp( _P_NOWAIT, argv[0], argv );
3090 argv[0] = "update-desktop-database";
3091 argv[1] = applications_dir;
3092 spawnvp( _P_NOWAIT, argv[0], argv );
3095 end:
3096 if (hSem)
3098 ReleaseSemaphore(hSem, 1, NULL);
3099 CloseHandle(hSem);
3101 HeapFree(GetProcessHeap(), 0, mime_dir);
3102 HeapFree(GetProcessHeap(), 0, packages_dir);
3103 HeapFree(GetProcessHeap(), 0, applications_dir);
3106 static void cleanup_menus(void)
3108 HKEY hkey;
3110 hkey = open_menus_reg_key();
3111 if (hkey)
3113 int i;
3114 LSTATUS lret = ERROR_SUCCESS;
3115 for (i = 0; lret == ERROR_SUCCESS; )
3117 WCHAR *value = NULL;
3118 WCHAR *data = NULL;
3119 DWORD valueSize = 4096;
3120 DWORD dataSize = 4096;
3121 while (1)
3123 lret = ERROR_OUTOFMEMORY;
3124 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3125 if (value == NULL)
3126 break;
3127 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3128 if (data == NULL)
3129 break;
3130 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3131 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
3132 break;
3133 valueSize *= 2;
3134 dataSize *= 2;
3135 HeapFree(GetProcessHeap(), 0, value);
3136 HeapFree(GetProcessHeap(), 0, data);
3137 value = data = NULL;
3139 if (lret == ERROR_SUCCESS)
3141 char *unix_file;
3142 char *windows_file;
3143 unix_file = wchars_to_unix_chars(value);
3144 windows_file = wchars_to_unix_chars(data);
3145 if (unix_file != NULL && windows_file != NULL)
3147 struct stat filestats;
3148 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3150 WINE_TRACE("removing menu related file %s\n", unix_file);
3151 remove(unix_file);
3152 RegDeleteValueW(hkey, value);
3154 else
3155 i++;
3157 else
3159 WINE_ERR("out of memory enumerating menus\n");
3160 lret = ERROR_OUTOFMEMORY;
3162 HeapFree(GetProcessHeap(), 0, unix_file);
3163 HeapFree(GetProcessHeap(), 0, windows_file);
3165 else if (lret != ERROR_NO_MORE_ITEMS)
3166 WINE_ERR("error %d reading registry\n", lret);
3167 HeapFree(GetProcessHeap(), 0, value);
3168 HeapFree(GetProcessHeap(), 0, data);
3170 RegCloseKey(hkey);
3172 else
3173 WINE_ERR("error opening registry key, menu cleanup failed\n");
3176 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3178 char *utf8lnkPath = NULL;
3179 char *utf8OutputPath = NULL;
3180 WCHAR *winLnkPath = NULL;
3181 IShellLinkW *shellLink = NULL;
3182 IPersistFile *persistFile = NULL;
3183 WCHAR szTmp[MAX_PATH];
3184 WCHAR szPath[MAX_PATH];
3185 WCHAR szArgs[INFOTIPSIZE];
3186 WCHAR szIconPath[MAX_PATH];
3187 int iconId;
3188 IStream *stream = NULL;
3189 HRESULT hr;
3191 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3192 if (utf8lnkPath == NULL)
3194 WINE_ERR("out of memory converting paths\n");
3195 goto end;
3198 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3199 if (utf8OutputPath == NULL)
3201 WINE_ERR("out of memory converting paths\n");
3202 goto end;
3205 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3206 if (winLnkPath == NULL)
3208 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3209 goto end;
3212 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3213 &IID_IShellLinkW, (LPVOID*)&shellLink);
3214 if (FAILED(hr))
3216 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3217 goto end;
3220 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3221 if (FAILED(hr))
3223 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3224 goto end;
3227 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3228 if (FAILED(hr))
3230 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3231 goto end;
3234 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3235 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3236 szTmp[0] = 0;
3237 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3238 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3240 if(!szPath[0])
3242 LPITEMIDLIST pidl = NULL;
3243 IShellLinkW_GetIDList(shellLink, &pidl);
3244 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3245 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3248 if (szIconPath[0])
3250 hr = open_icon(szIconPath, iconId, FALSE, &stream);
3251 if (SUCCEEDED(hr))
3252 hr = write_native_icon(stream, utf8OutputPath, NULL);
3254 else
3256 hr = open_icon(szPath, iconId, FALSE, &stream);
3257 if (SUCCEEDED(hr))
3258 hr = write_native_icon(stream, utf8OutputPath, NULL);
3261 end:
3262 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3263 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3264 HeapFree(GetProcessHeap(), 0, winLnkPath);
3265 if (shellLink != NULL)
3266 IShellLinkW_Release(shellLink);
3267 if (persistFile != NULL)
3268 IPersistFile_Release(persistFile);
3269 if (stream != NULL)
3270 IStream_Release(stream);
3273 static WCHAR *next_token( LPWSTR *p )
3275 LPWSTR token = NULL, t = *p;
3277 if( !t )
3278 return NULL;
3280 while( t && !token )
3282 switch( *t )
3284 case ' ':
3285 t++;
3286 continue;
3287 case '"':
3288 /* unquote the token */
3289 token = ++t;
3290 t = strchrW( token, '"' );
3291 if( t )
3292 *t++ = 0;
3293 break;
3294 case 0:
3295 t = NULL;
3296 break;
3297 default:
3298 token = t;
3299 t = strchrW( token, ' ' );
3300 if( t )
3301 *t++ = 0;
3302 break;
3305 *p = t;
3306 return token;
3309 static BOOL init_xdg(void)
3311 WCHAR shellDesktopPath[MAX_PATH];
3312 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3313 if (SUCCEEDED(hr))
3314 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3315 if (xdg_desktop_dir == NULL)
3317 WINE_ERR("error looking up the desktop directory\n");
3318 return FALSE;
3321 if (getenv("XDG_CONFIG_HOME"))
3322 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3323 else
3324 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3325 if (xdg_config_dir)
3327 create_directories(xdg_config_dir);
3328 if (getenv("XDG_DATA_HOME"))
3329 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3330 else
3331 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3332 if (xdg_data_dir)
3334 char *buffer;
3335 create_directories(xdg_data_dir);
3336 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3337 if (buffer)
3339 mkdir(buffer, 0777);
3340 HeapFree(GetProcessHeap(), 0, buffer);
3342 return TRUE;
3344 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3346 WINE_ERR("out of memory\n");
3347 return FALSE;
3350 /***********************************************************************
3352 * wWinMain
3354 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3356 static const WCHAR dash_aW[] = {'-','a',0};
3357 static const WCHAR dash_rW[] = {'-','r',0};
3358 static const WCHAR dash_tW[] = {'-','t',0};
3359 static const WCHAR dash_uW[] = {'-','u',0};
3360 static const WCHAR dash_wW[] = {'-','w',0};
3362 LPWSTR token = NULL, p;
3363 BOOL bWait = FALSE;
3364 BOOL bURL = FALSE;
3365 HRESULT hr;
3366 int ret = 0;
3368 if (!init_xdg())
3369 return 1;
3371 hr = CoInitialize(NULL);
3372 if (FAILED(hr))
3374 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3375 return 1;
3378 for( p = cmdline; p && *p; )
3380 token = next_token( &p );
3381 if( !token )
3382 break;
3383 if( !strcmpW( token, dash_aW ) )
3385 RefreshFileTypeAssociations();
3386 continue;
3388 if( !strcmpW( token, dash_rW ) )
3390 cleanup_menus();
3391 continue;
3393 if( !strcmpW( token, dash_wW ) )
3394 bWait = TRUE;
3395 else if ( !strcmpW( token, dash_uW ) )
3396 bURL = TRUE;
3397 else if ( !strcmpW( token, dash_tW ) )
3399 WCHAR *lnkFile = next_token( &p );
3400 if (lnkFile)
3402 WCHAR *outputFile = next_token( &p );
3403 if (outputFile)
3404 thumbnail_lnk(lnkFile, outputFile);
3407 else if( token[0] == '-' )
3409 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3411 else
3413 BOOL bRet;
3415 if (bURL)
3416 bRet = Process_URL( token, bWait );
3417 else
3418 bRet = Process_Link( token, bWait );
3419 if (!bRet)
3421 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3422 ret = 1;
3427 CoUninitialize();
3428 return ret;