d2d1/tests: Run the tests in parallel.
[wine.git] / programs / winemenubuilder / winemenubuilder.c
blob9adfed6307936e6f80dbea9debb632072f30936c
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 #define IS_OPTION_TRUE(ch) \
108 ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
110 /* link file formats */
112 #include "pshpack1.h"
114 typedef struct
116 BYTE bWidth;
117 BYTE bHeight;
118 BYTE bColorCount;
119 BYTE bReserved;
120 WORD wPlanes;
121 WORD wBitCount;
122 DWORD dwBytesInRes;
123 WORD nID;
124 } GRPICONDIRENTRY;
126 typedef struct
128 WORD idReserved;
129 WORD idType;
130 WORD idCount;
131 GRPICONDIRENTRY idEntries[1];
132 } GRPICONDIR;
134 typedef struct
136 BYTE bWidth;
137 BYTE bHeight;
138 BYTE bColorCount;
139 BYTE bReserved;
140 WORD wPlanes;
141 WORD wBitCount;
142 DWORD dwBytesInRes;
143 DWORD dwImageOffset;
144 } ICONDIRENTRY;
146 typedef struct
148 WORD idReserved;
149 WORD idType;
150 WORD idCount;
151 } ICONDIR;
153 typedef struct
155 WORD offset;
156 WORD length;
157 WORD flags;
158 WORD id;
159 WORD handle;
160 WORD usage;
161 } NE_NAMEINFO;
163 typedef struct
165 WORD type_id;
166 WORD count;
167 DWORD resloader;
168 } NE_TYPEINFO;
170 #define NE_RSCTYPE_ICON 0x8003
171 #define NE_RSCTYPE_GROUP_ICON 0x800e
173 #include "poppack.h"
175 typedef struct
177 HRSRC *pResInfo;
178 int nIndex;
179 } ENUMRESSTRUCT;
181 struct xdg_mime_type
183 char *mimeType;
184 char *glob;
185 char *lower_glob;
186 struct list entry;
189 struct rb_string_entry
191 char *string;
192 struct wine_rb_entry entry;
195 DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
197 static char *xdg_config_dir;
198 static char *xdg_data_dir;
199 static char *xdg_desktop_dir;
202 /* Utility routines */
203 static unsigned short crc16(const char* string)
205 unsigned short crc = 0;
206 int i, j, xor_poly;
208 for (i = 0; string[i] != 0; i++)
210 char c = string[i];
211 for (j = 0; j < 8; c >>= 1, j++)
213 xor_poly = (c ^ crc) & 1;
214 crc >>= 1;
215 if (xor_poly)
216 crc ^= 0xa001;
219 return crc;
222 static char *strdupA( const char *str )
224 char *ret;
226 if (!str) return NULL;
227 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
228 return ret;
231 static char* heap_printf(const char *format, ...)
233 va_list args;
234 int size = 4096;
235 char *buffer, *ret;
236 int n;
238 while (1)
240 buffer = HeapAlloc(GetProcessHeap(), 0, size);
241 if (buffer == NULL)
242 break;
243 va_start(args, format);
244 n = vsnprintf(buffer, size, format, args);
245 va_end(args);
246 if (n == -1)
247 size *= 2;
248 else if (n >= size)
249 size = n + 1;
250 else
251 break;
252 HeapFree(GetProcessHeap(), 0, buffer);
255 if (!buffer) return NULL;
256 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
257 if (!ret) ret = buffer;
258 return ret;
261 static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
263 const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);
265 return strcmp((char*)key, t->string);
268 static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
270 struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
271 HeapFree(GetProcessHeap(), 0, t->string);
272 HeapFree(GetProcessHeap(), 0, t);
275 static void write_xml_text(FILE *file, const char *text)
277 int i;
278 for (i = 0; text[i]; i++)
280 if (text[i] == '&')
281 fputs("&amp;", file);
282 else if (text[i] == '<')
283 fputs("&lt;", file);
284 else if (text[i] == '>')
285 fputs("&gt;", file);
286 else if (text[i] == '\'')
287 fputs("&apos;", file);
288 else if (text[i] == '"')
289 fputs("&quot;", file);
290 else
291 fputc(text[i], file);
295 static BOOL create_directories(char *directory)
297 BOOL ret = TRUE;
298 int i;
300 for (i = 0; directory[i]; i++)
302 if (i > 0 && directory[i] == '/')
304 directory[i] = 0;
305 mkdir(directory, 0777);
306 directory[i] = '/';
309 if (mkdir(directory, 0777) && errno != EEXIST)
310 ret = FALSE;
312 return ret;
315 static char* wchars_to_utf8_chars(LPCWSTR string)
317 char *ret;
318 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
319 ret = HeapAlloc(GetProcessHeap(), 0, size);
320 if (ret)
321 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
322 return ret;
325 static char* wchars_to_unix_chars(LPCWSTR string)
327 char *ret;
328 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
329 ret = HeapAlloc(GetProcessHeap(), 0, size);
330 if (ret)
331 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
332 return ret;
335 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
337 WCHAR *ret;
338 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
339 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
340 if (ret)
341 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
342 return ret;
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 *indices, int numIndices,
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 IWICBitmapScaler *scaler = 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 if (IsEqualCLSID(outputFormat,&CLSID_WICIcnsEncoder))
385 hr = IWICImagingFactory_CreateBitmapScaler(factory, &scaler);
386 if (FAILED(hr))
388 WINE_WARN("error 0x%08X creating IWICBitmapScaler\n", hr);
391 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
392 &IID_IWICBitmapEncoder, (void**)&encoder);
393 if (FAILED(hr))
395 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
396 goto end;
398 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
399 if (FAILED(hr))
401 WINE_ERR("error 0x%08X creating output file %s\n", hr, wine_dbgstr_w(dosOutputFileName));
402 goto end;
404 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, GENERIC_WRITE);
405 if (FAILED(hr))
407 WINE_ERR("error 0x%08X initializing encoder\n", hr);
408 goto end;
411 for (i = 0; i < numIndices; i++)
413 IWICBitmapFrameDecode *sourceFrame = NULL;
414 IWICBitmapSource *sourceBitmap = NULL;
415 IWICBitmapFrameEncode *dstFrame = NULL;
416 IPropertyBag2 *options = NULL;
417 UINT width, height;
419 hr = IWICBitmapDecoder_GetFrame(decoder, indices[i], &sourceFrame);
420 if (FAILED(hr))
422 WINE_ERR("error 0x%08X getting frame %d\n", hr, indices[i]);
423 goto endloop;
425 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
426 if (FAILED(hr))
428 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
429 goto endloop;
431 if ( scaler)
433 IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
434 if (width == 64) /* Classic Mode */
436 hr = IWICBitmapScaler_Initialize( scaler, sourceBitmap, 128, 128,
437 WICBitmapInterpolationModeNearestNeighbor);
438 if (FAILED(hr))
439 WINE_ERR("error 0x%08X scaling bitmap\n", hr);
440 else
442 IWICBitmapSource_Release(sourceBitmap);
443 IWICBitmapScaler_QueryInterface(scaler, &IID_IWICBitmapSource, (LPVOID)&sourceBitmap);
447 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
448 if (FAILED(hr))
450 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
451 goto endloop;
453 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
454 if (FAILED(hr))
456 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
457 goto endloop;
459 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
460 if (FAILED(hr))
462 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
463 goto endloop;
465 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
466 if (FAILED(hr))
468 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
469 goto endloop;
471 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
472 if (FAILED(hr))
474 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
475 goto endloop;
477 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
478 if (FAILED(hr))
480 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
481 goto endloop;
483 hr = IWICBitmapFrameEncode_Commit(dstFrame);
484 if (FAILED(hr))
486 WINE_ERR("error 0x%08X committing frame\n", hr);
487 goto endloop;
489 endloop:
490 if (sourceFrame)
491 IWICBitmapFrameDecode_Release(sourceFrame);
492 if (sourceBitmap)
493 IWICBitmapSource_Release(sourceBitmap);
494 if (dstFrame)
495 IWICBitmapFrameEncode_Release(dstFrame);
496 if (options)
497 IPropertyBag2_Release(options);
500 hr = IWICBitmapEncoder_Commit(encoder);
501 if (FAILED(hr))
503 WINE_ERR("error 0x%08X committing encoder\n", hr);
504 goto end;
507 end:
508 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
509 if (factory)
510 IWICImagingFactory_Release(factory);
511 if (decoder)
512 IWICBitmapDecoder_Release(decoder);
513 if (scaler)
514 IWICBitmapScaler_Release(scaler);
515 if (encoder)
516 IWICBitmapEncoder_Release(encoder);
517 if (outputFile)
518 IStream_Release(outputFile);
519 return hr;
522 struct IconData16 {
523 BYTE *fileBytes;
524 DWORD fileSize;
525 NE_TYPEINFO *iconResources;
526 WORD alignmentShiftCount;
529 static int populate_module16_icons(struct IconData16 *iconData16, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
531 int i, j;
532 int validEntries = 0;
534 for (i = 0; i < grpIconDir->idCount; i++)
536 BYTE *iconPtr = (BYTE*)iconData16->iconResources;
537 NE_NAMEINFO *matchingIcon = NULL;
538 iconPtr += sizeof(NE_TYPEINFO);
539 for (j = 0; j < iconData16->iconResources->count; j++)
541 NE_NAMEINFO *iconInfo = (NE_NAMEINFO*)iconPtr;
542 if ((((BYTE*)iconPtr) + sizeof(NE_NAMEINFO)) > (iconData16->fileBytes + iconData16->fileSize))
544 WINE_WARN("file too small for icon NE_NAMEINFO\n");
545 break;
547 if (iconInfo->id == (0x8000 | grpIconDir->idEntries[i].nID))
549 matchingIcon = iconInfo;
550 break;
552 iconPtr += sizeof(NE_NAMEINFO);
555 if (matchingIcon == NULL)
556 continue;
557 if (((matchingIcon->offset << iconData16->alignmentShiftCount) + grpIconDir->idEntries[i].dwBytesInRes) > iconData16->fileSize)
559 WINE_WARN("file too small for icon contents\n");
560 break;
563 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
564 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
565 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
566 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
567 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
568 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
569 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
570 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
571 validEntries++;
572 memcpy(&icons[*iconOffset], &iconData16->fileBytes[matchingIcon->offset << iconData16->alignmentShiftCount], grpIconDir->idEntries[i].dwBytesInRes);
573 *iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
575 return validEntries;
578 static int populate_module_icons(HMODULE hModule, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
580 int i;
581 int validEntries = 0;
583 for (i = 0; i < grpIconDir->idCount; i++)
585 HRSRC hResInfo;
586 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
587 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
589 HGLOBAL hResData;
590 if ((hResData = LoadResource(hModule, hResInfo)))
592 BITMAPINFO *pIcon;
593 DWORD size = min( grpIconDir->idEntries[i].dwBytesInRes, ((IMAGE_RESOURCE_DATA_ENTRY *)hResInfo)->Size );
594 if ((pIcon = LockResource(hResData)))
596 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
597 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
598 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
599 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
600 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
601 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
602 iconDirEntries[validEntries].dwBytesInRes = size;
603 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
604 validEntries++;
605 memcpy(&icons[*iconOffset], pIcon, size);
606 *iconOffset += size;
608 FreeResource(hResData);
612 return validEntries;
615 static IStream *add_module_icons_to_stream(struct IconData16 *iconData16, HMODULE hModule, GRPICONDIR *grpIconDir)
617 int i;
618 SIZE_T iconsSize = 0;
619 BYTE *icons = NULL;
620 ICONDIRENTRY *iconDirEntries = NULL;
621 IStream *stream = NULL;
622 HRESULT hr = E_FAIL;
623 ULONG bytesWritten;
624 ICONDIR iconDir;
625 SIZE_T iconOffset;
626 int validEntries = 0;
627 LARGE_INTEGER zero;
629 for (i = 0; i < grpIconDir->idCount; i++)
630 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
631 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
632 if (icons == NULL)
634 WINE_ERR("out of memory allocating icon\n");
635 goto end;
638 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
639 if (iconDirEntries == NULL)
641 WINE_ERR("out of memory allocating icon dir entries\n");
642 goto end;
645 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
646 if (FAILED(hr))
648 WINE_ERR("error creating icon stream\n");
649 goto end;
652 iconOffset = 0;
653 if (iconData16)
654 validEntries = populate_module16_icons(iconData16, grpIconDir, iconDirEntries, icons, &iconOffset);
655 else if (hModule)
656 validEntries = populate_module_icons(hModule, grpIconDir, iconDirEntries, icons, &iconOffset);
658 if (validEntries == 0)
660 WINE_ERR("no valid icon entries\n");
661 goto end;
664 iconDir.idReserved = 0;
665 iconDir.idType = 1;
666 iconDir.idCount = validEntries;
667 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
668 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
670 WINE_ERR("error 0x%08X writing icon stream\n", hr);
671 goto end;
673 for (i = 0; i < validEntries; i++)
674 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
675 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
676 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
678 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
679 goto end;
681 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
682 if (FAILED(hr) || bytesWritten != iconOffset)
684 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
685 goto end;
687 zero.QuadPart = 0;
688 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
690 end:
691 HeapFree(GetProcessHeap(), 0, icons);
692 HeapFree(GetProcessHeap(), 0, iconDirEntries);
693 if (FAILED(hr) && stream != NULL)
695 IStream_Release(stream);
696 stream = NULL;
698 return stream;
701 static HRESULT open_module16_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
703 HANDLE hFile = INVALID_HANDLE_VALUE;
704 HANDLE hFileMapping = NULL;
705 DWORD fileSize;
706 BYTE *fileBytes = NULL;
707 IMAGE_DOS_HEADER *dosHeader;
708 IMAGE_OS2_HEADER *neHeader;
709 BYTE *rsrcTab;
710 NE_TYPEINFO *iconGroupResources;
711 NE_TYPEINFO *iconResources;
712 NE_NAMEINFO *iconDirPtr;
713 GRPICONDIR *iconDir;
714 WORD alignmentShiftCount;
715 struct IconData16 iconData16;
716 HRESULT hr = E_FAIL;
718 hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
719 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
720 if (hFile == INVALID_HANDLE_VALUE)
722 WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName), GetLastError());
723 goto end;
726 hFileMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
727 if (hFileMapping == NULL)
729 WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
730 goto end;
733 fileSize = GetFileSize(hFile, NULL);
735 fileBytes = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
736 if (fileBytes == NULL)
738 WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
739 goto end;
742 dosHeader = (IMAGE_DOS_HEADER*)fileBytes;
743 if (sizeof(IMAGE_DOS_HEADER) >= fileSize || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
745 WINE_WARN("file too small for MZ header\n");
746 goto end;
749 neHeader = (IMAGE_OS2_HEADER*)(fileBytes + dosHeader->e_lfanew);
750 if ((((BYTE*)neHeader) + sizeof(IMAGE_OS2_HEADER)) > (fileBytes + fileSize) ||
751 neHeader->ne_magic != IMAGE_OS2_SIGNATURE)
753 WINE_WARN("file too small for NE header\n");
754 goto end;
757 rsrcTab = ((BYTE*)neHeader) + neHeader->ne_rsrctab;
758 if ((rsrcTab + 2) > (fileBytes + fileSize))
760 WINE_WARN("file too small for resource table\n");
761 goto end;
764 alignmentShiftCount = *(WORD*)rsrcTab;
765 rsrcTab += 2;
766 iconGroupResources = NULL;
767 iconResources = NULL;
768 for (;;)
770 NE_TYPEINFO *neTypeInfo = (NE_TYPEINFO*)rsrcTab;
771 if ((rsrcTab + sizeof(NE_TYPEINFO)) > (fileBytes + fileSize))
773 WINE_WARN("file too small for resource table\n");
774 goto end;
776 if (neTypeInfo->type_id == 0)
777 break;
778 else if (neTypeInfo->type_id == NE_RSCTYPE_GROUP_ICON)
779 iconGroupResources = neTypeInfo;
780 else if (neTypeInfo->type_id == NE_RSCTYPE_ICON)
781 iconResources = neTypeInfo;
782 rsrcTab += sizeof(NE_TYPEINFO) + neTypeInfo->count*sizeof(NE_NAMEINFO);
784 if (iconGroupResources == NULL)
786 WINE_WARN("no group icon resource type found\n");
787 goto end;
789 if (iconResources == NULL)
791 WINE_WARN("no icon resource type found\n");
792 goto end;
795 if (nIndex >= iconGroupResources->count)
797 WINE_WARN("icon index out of range\n");
798 goto end;
801 iconDirPtr = (NE_NAMEINFO*)(((BYTE*)iconGroupResources) + sizeof(NE_TYPEINFO) + nIndex*sizeof(NE_NAMEINFO));
802 if ((((BYTE*)iconDirPtr) + sizeof(NE_NAMEINFO)) > (fileBytes + fileSize))
804 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
805 goto end;
807 iconDir = (GRPICONDIR*)(fileBytes + (iconDirPtr->offset << alignmentShiftCount));
808 if ((((BYTE*)iconDir) + sizeof(GRPICONDIR) + iconDir->idCount*sizeof(GRPICONDIRENTRY)) > (fileBytes + fileSize))
810 WINE_WARN("file too small for GRPICONDIR\n");
811 goto end;
814 iconData16.fileBytes = fileBytes;
815 iconData16.fileSize = fileSize;
816 iconData16.iconResources = iconResources;
817 iconData16.alignmentShiftCount = alignmentShiftCount;
818 *ppStream = add_module_icons_to_stream(&iconData16, NULL, iconDir);
819 if (*ppStream)
820 hr = S_OK;
822 end:
823 if (hFile != INVALID_HANDLE_VALUE)
824 CloseHandle(hFile);
825 if (hFileMapping != NULL)
826 CloseHandle(hFileMapping);
827 if (fileBytes != NULL)
828 UnmapViewOfFile(fileBytes);
829 return hr;
832 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
834 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
836 if (!sEnumRes->nIndex--)
838 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
839 return FALSE;
841 else
842 return TRUE;
845 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
847 HMODULE hModule;
848 HRSRC hResInfo;
849 HGLOBAL hResData;
850 GRPICONDIR *pIconDir;
851 ENUMRESSTRUCT sEnumRes;
852 HRESULT hr = E_FAIL;
854 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
855 if (!hModule)
857 if (GetLastError() == ERROR_BAD_EXE_FORMAT)
858 return open_module16_icon(szFileName, nIndex, ppStream);
859 else
861 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
862 wine_dbgstr_w(szFileName), GetLastError());
863 return HRESULT_FROM_WIN32(GetLastError());
867 if (nIndex < 0)
869 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
870 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
871 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
873 else
875 hResInfo=NULL;
876 sEnumRes.pResInfo = &hResInfo;
877 sEnumRes.nIndex = nIndex;
878 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
879 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
880 sEnumRes.nIndex != -1)
882 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
886 if (hResInfo)
888 if ((hResData = LoadResource(hModule, hResInfo)))
890 if ((pIconDir = LockResource(hResData)))
892 *ppStream = add_module_icons_to_stream(0, hModule, pIconDir);
893 if (*ppStream)
894 hr = S_OK;
897 FreeResource(hResData);
900 else
902 WINE_WARN("found no icon\n");
903 FreeLibrary(hModule);
904 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
907 FreeLibrary(hModule);
908 return hr;
911 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
913 ICONDIR iconDir;
914 ULONG bytesRead;
915 HRESULT hr;
917 *ppIconDirEntries = NULL;
919 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
920 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
921 (iconDir.idReserved != 0) || (iconDir.idType != 1))
923 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
924 hr = E_FAIL;
925 goto end;
927 *numEntries = iconDir.idCount;
929 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
931 hr = E_OUTOFMEMORY;
932 goto end;
934 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
935 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
937 if (SUCCEEDED(hr)) hr = E_FAIL;
938 goto end;
941 end:
942 if (FAILED(hr))
943 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
944 return hr;
947 static HRESULT validate_ico(IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
949 HRESULT hr;
951 hr = read_ico_direntries(*ppStream, ppIconDirEntries, numEntries);
952 if (SUCCEEDED(hr))
954 if (*numEntries)
955 return hr;
956 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
957 *ppIconDirEntries = NULL;
959 IStream_Release(*ppStream);
960 *ppStream = NULL;
961 return E_FAIL;
964 static HRESULT write_native_icon(IStream *iconStream, ICONDIRENTRY *pIconDirEntry,
965 int numEntries, const char *icon_name, LPCWSTR szFileName)
967 int nMax = 0, nMaxBits = 0;
968 int nIndex = 0;
969 int i;
970 LARGE_INTEGER position;
971 HRESULT hr;
973 for (i = 0; i < numEntries; i++)
975 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
976 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
977 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
979 nIndex = i;
980 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
981 nMaxBits = pIconDirEntry[i].wBitCount;
984 WINE_TRACE("Selected: %d\n", nIndex);
986 position.QuadPart = 0;
987 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
988 if (FAILED(hr)) return hr;
989 return convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
992 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
994 HRESULT hr;
995 WCHAR *value = NULL;
996 DWORD size = 0;
997 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
998 if (SUCCEEDED(hr))
1000 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1001 if (value)
1003 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1004 if (FAILED(hr))
1006 HeapFree(GetProcessHeap(), 0, value);
1007 value = NULL;
1011 return value;
1014 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
1016 static const WCHAR openW[] = {'o','p','e','n',0};
1017 WCHAR *extension;
1018 WCHAR *icon = NULL;
1019 WCHAR *comma;
1020 WCHAR *executable = NULL;
1021 int index = 0;
1022 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
1024 extension = strrchrW(szFileName, '.');
1025 if (extension == NULL)
1026 goto end;
1028 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
1029 if (icon)
1031 comma = strrchrW(icon, ',');
1032 if (comma)
1034 *comma = 0;
1035 index = atoiW(comma + 1);
1037 hr = open_module_icon(icon, index, ppStream);
1039 else
1041 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, openW);
1042 if (executable)
1043 hr = open_module_icon(executable, 0, ppStream);
1046 end:
1047 HeapFree(GetProcessHeap(), 0, icon);
1048 HeapFree(GetProcessHeap(), 0, executable);
1049 return hr;
1052 static HRESULT open_default_icon(IStream **ppStream)
1054 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
1056 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
1059 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
1061 HRESULT hr;
1063 hr = open_module_icon(filename, index, ppStream);
1064 if (FAILED(hr))
1066 if(bWait && hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
1068 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1069 wine_dbgstr_w(filename));
1070 return hr;
1072 else
1074 /* This might be a raw .ico file */
1075 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
1078 if (SUCCEEDED(hr))
1079 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1081 if (FAILED(hr))
1083 hr = open_file_type_icon(filename, ppStream);
1084 if (SUCCEEDED(hr))
1085 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1087 if (FAILED(hr) && !bWait)
1089 hr = open_default_icon(ppStream);
1090 if (SUCCEEDED(hr))
1091 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1093 return hr;
1096 static char* compute_native_identifier(int exeIndex, LPCWSTR icoPathW)
1098 char* nativeIdentifier;
1099 char *icoPathA;
1100 unsigned short crc;
1101 char *basename, *ext;
1103 icoPathA = wchars_to_utf8_chars(icoPathW);
1104 if (icoPathA == NULL)
1105 return NULL;
1107 crc = crc16(icoPathA);
1108 basename = strrchr(icoPathA, '\\');
1109 if (basename == NULL)
1110 basename = icoPathA;
1111 else
1113 *basename = 0;
1114 basename++;
1116 ext = strrchr(basename, '.');
1117 if (ext)
1118 *ext = 0;
1120 nativeIdentifier = heap_printf("%04X_%s.%d", crc, basename, exeIndex);
1121 HeapFree(GetProcessHeap(), 0, icoPathA);
1122 return nativeIdentifier;
1125 #ifdef __APPLE__
1126 #define ICNS_SLOTS 6
1128 static inline int size_to_slot(int size)
1130 switch (size)
1132 case 16: return 0;
1133 case 32: return 1;
1134 case 48: return 2;
1135 case 64: return -2; /* Classic Mode */
1136 case 128: return 3;
1137 case 256: return 4;
1138 case 512: return 5;
1141 return -1;
1144 #define CLASSIC_SLOT 3
1146 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1147 int numEntries, int exeIndex, LPCWSTR icoPathW,
1148 const char *destFilename, char **nativeIdentifier)
1150 struct {
1151 int index;
1152 int maxBits;
1153 BOOL scaled;
1154 } best[ICNS_SLOTS];
1155 int indexes[ICNS_SLOTS];
1156 int i;
1157 const char* tmpdir;
1158 char *icnsPath = NULL;
1159 LARGE_INTEGER zero;
1160 HRESULT hr;
1162 for (i = 0; i < ICNS_SLOTS; i++)
1164 best[i].index = -1;
1165 best[i].maxBits = 0;
1167 for (i = 0; i < numEntries; i++)
1169 int slot;
1170 int width = iconDirEntries[i].bWidth ? iconDirEntries[i].bWidth : 256;
1171 int height = iconDirEntries[i].bHeight ? iconDirEntries[i].bHeight : 256;
1172 BOOL scaled = FALSE;
1174 WINE_TRACE("[%d]: %d x %d @ %d\n", i, width, height, iconDirEntries[i].wBitCount);
1175 if (height != width)
1176 continue;
1177 slot = size_to_slot(width);
1178 if (slot == -2)
1180 scaled = TRUE;
1181 slot = CLASSIC_SLOT;
1183 else if (slot < 0)
1184 continue;
1185 if (scaled && best[slot].maxBits && !best[slot].scaled)
1186 continue; /* don't replace unscaled with scaled */
1187 if (iconDirEntries[i].wBitCount >= best[slot].maxBits || (!scaled && best[slot].scaled))
1189 best[slot].index = i;
1190 best[slot].maxBits = iconDirEntries[i].wBitCount;
1191 best[slot].scaled = scaled;
1194 /* remove the scaled icon if a larger unscaled icon exists */
1195 if (best[CLASSIC_SLOT].scaled)
1197 for (i = CLASSIC_SLOT+1; i < ICNS_SLOTS; i++)
1198 if (best[i].index >= 0 && !best[i].scaled)
1200 best[CLASSIC_SLOT].index = -1;
1201 break;
1205 numEntries = 0;
1206 for (i = 0; i < ICNS_SLOTS; i++)
1208 if (best[i].index >= 0)
1210 indexes[numEntries] = best[i].index;
1211 numEntries++;
1215 if (destFilename)
1216 *nativeIdentifier = heap_printf("%s", destFilename);
1217 else
1218 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1219 if (*nativeIdentifier == NULL)
1221 hr = E_OUTOFMEMORY;
1222 goto end;
1224 if (!(tmpdir = getenv("TMPDIR"))) tmpdir = "/tmp";
1225 icnsPath = heap_printf("%s/%s.icns", tmpdir, *nativeIdentifier);
1226 if (icnsPath == NULL)
1228 hr = E_OUTOFMEMORY;
1229 WINE_WARN("out of memory creating ICNS path\n");
1230 goto end;
1232 zero.QuadPart = 0;
1233 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1234 if (FAILED(hr))
1236 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
1237 goto end;
1239 hr = convert_to_native_icon(icoStream, indexes, numEntries, &CLSID_WICIcnsEncoder,
1240 icnsPath, icoPathW);
1241 if (FAILED(hr))
1243 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
1244 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
1245 goto end;
1248 end:
1249 HeapFree(GetProcessHeap(), 0, icnsPath);
1250 return hr;
1252 #else
1253 static void refresh_icon_cache(const char *iconsDir)
1255 /* The icon theme spec only requires the mtime on the "toplevel"
1256 * directory (whatever that is) to be changed for a refresh,
1257 * but on GNOME you have to create a file in that directory
1258 * instead. Creating a file also works on KDE, Xfce and LXDE.
1260 char *filename = heap_printf("%s/.wine-refresh-XXXXXX", iconsDir);
1261 if (filename != NULL)
1263 int fd = mkstemps(filename, 0);
1264 if (fd >= 0)
1266 close(fd);
1267 unlink(filename);
1269 HeapFree(GetProcessHeap(), 0, filename);
1273 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1274 int numEntries, int exeIndex, LPCWSTR icoPathW,
1275 const char *destFilename, char **nativeIdentifier)
1277 int i;
1278 char *iconsDir = NULL;
1279 HRESULT hr = S_OK;
1280 LARGE_INTEGER zero;
1282 if (destFilename)
1283 *nativeIdentifier = heap_printf("%s", destFilename);
1284 else
1285 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1286 if (*nativeIdentifier == NULL)
1288 hr = E_OUTOFMEMORY;
1289 goto end;
1291 iconsDir = heap_printf("%s/icons/hicolor", xdg_data_dir);
1292 if (iconsDir == NULL)
1294 hr = E_OUTOFMEMORY;
1295 goto end;
1298 for (i = 0; i < numEntries; i++)
1300 int bestIndex = i;
1301 int j;
1302 BOOLEAN duplicate = FALSE;
1303 int w, h;
1304 char *iconDir = NULL;
1305 char *pngPath = NULL;
1307 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
1308 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
1310 for (j = 0; j < i; j++)
1312 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1313 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
1315 duplicate = TRUE;
1316 break;
1319 if (duplicate)
1320 continue;
1321 for (j = i + 1; j < numEntries; j++)
1323 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1324 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1325 iconDirEntries[j].wBitCount >= iconDirEntries[bestIndex].wBitCount)
1327 bestIndex = j;
1330 WINE_TRACE("Selected: %d\n", bestIndex);
1332 w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
1333 h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
1334 iconDir = heap_printf("%s/%dx%d/apps", iconsDir, w, h);
1335 if (iconDir == NULL)
1337 hr = E_OUTOFMEMORY;
1338 goto endloop;
1340 create_directories(iconDir);
1341 pngPath = heap_printf("%s/%s.png", iconDir, *nativeIdentifier);
1342 if (pngPath == NULL)
1344 hr = E_OUTOFMEMORY;
1345 goto endloop;
1347 zero.QuadPart = 0;
1348 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1349 if (FAILED(hr))
1350 goto endloop;
1351 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
1352 pngPath, icoPathW);
1354 endloop:
1355 HeapFree(GetProcessHeap(), 0, iconDir);
1356 HeapFree(GetProcessHeap(), 0, pngPath);
1358 refresh_icon_cache(iconsDir);
1360 end:
1361 HeapFree(GetProcessHeap(), 0, iconsDir);
1362 return hr;
1364 #endif /* defined(__APPLE__) */
1366 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1367 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
1369 IStream *stream = NULL;
1370 ICONDIRENTRY *pIconDirEntries = NULL;
1371 int numEntries;
1372 HRESULT hr;
1373 char *nativeIdentifier = NULL;
1375 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
1377 hr = open_icon(icoPathW, index, bWait, &stream, &pIconDirEntries, &numEntries);
1378 if (FAILED(hr))
1380 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
1381 goto end;
1383 hr = platform_write_icon(stream, pIconDirEntries, numEntries, index, icoPathW, destFilename, &nativeIdentifier);
1384 if (FAILED(hr))
1385 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
1387 end:
1388 if (stream)
1389 IStream_Release(stream);
1390 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
1391 if (FAILED(hr))
1393 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
1394 nativeIdentifier = NULL;
1396 return nativeIdentifier;
1399 static HKEY open_menus_reg_key(void)
1401 static const WCHAR Software_Wine_FileOpenMenuFilesW[] = {
1402 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1403 HKEY assocKey;
1404 DWORD ret;
1405 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenMenuFilesW, &assocKey);
1406 if (ret == ERROR_SUCCESS)
1407 return assocKey;
1408 SetLastError(ret);
1409 return NULL;
1412 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1414 WCHAR *unix_fileW;
1415 WCHAR *windows_fileW;
1416 INT size;
1417 DWORD ret;
1419 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1420 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1421 if (unix_fileW)
1423 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1424 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1425 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1426 if (windows_fileW)
1428 HKEY hkey;
1429 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1430 hkey = open_menus_reg_key();
1431 if (hkey)
1433 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1434 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1435 RegCloseKey(hkey);
1437 else
1438 ret = GetLastError();
1439 HeapFree(GetProcessHeap(), 0, windows_fileW);
1441 else
1442 ret = ERROR_NOT_ENOUGH_MEMORY;
1443 HeapFree(GetProcessHeap(), 0, unix_fileW);
1445 else
1446 ret = ERROR_NOT_ENOUGH_MEMORY;
1447 return ret;
1450 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1451 const char *path, const char *args, const char *descr,
1452 const char *workdir, const char *icon, const char *wmclass)
1454 FILE *file;
1456 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1457 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1458 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon),
1459 wine_dbgstr_a(wmclass));
1461 file = fopen(location, "w");
1462 if (file == NULL)
1463 return FALSE;
1465 fprintf(file, "[Desktop Entry]\n");
1466 fprintf(file, "Name=%s\n", linkname);
1467 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1468 wine_get_config_dir(), path, args);
1469 fprintf(file, "Type=Application\n");
1470 fprintf(file, "StartupNotify=true\n");
1471 if (descr && lstrlenA(descr))
1472 fprintf(file, "Comment=%s\n", descr);
1473 if (workdir && lstrlenA(workdir))
1474 fprintf(file, "Path=%s\n", workdir);
1475 if (icon && lstrlenA(icon))
1476 fprintf(file, "Icon=%s\n", icon);
1477 if (wmclass && lstrlenA(wmclass))
1478 fprintf(file, "StartupWMClass=%s\n", wmclass);
1480 fclose(file);
1482 if (unix_link)
1484 DWORD ret = register_menus_entry(location, unix_link);
1485 if (ret != ERROR_SUCCESS)
1486 return FALSE;
1489 return TRUE;
1492 static BOOL write_directory_entry(const char *directory, const char *location)
1494 FILE *file;
1496 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1498 file = fopen(location, "w");
1499 if (file == NULL)
1500 return FALSE;
1502 fprintf(file, "[Desktop Entry]\n");
1503 fprintf(file, "Type=Directory\n");
1504 if (strcmp(directory, "wine") == 0)
1506 fprintf(file, "Name=Wine\n");
1507 fprintf(file, "Icon=wine\n");
1509 else
1511 fprintf(file, "Name=%s\n", directory);
1512 fprintf(file, "Icon=folder\n");
1515 fclose(file);
1516 return TRUE;
1519 static BOOL write_menu_file(const char *unix_link, const char *filename)
1521 char *tempfilename;
1522 FILE *tempfile = NULL;
1523 char *lastEntry;
1524 char *name = NULL;
1525 char *menuPath = NULL;
1526 int i;
1527 int count = 0;
1528 BOOL ret = FALSE;
1530 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1532 while (1)
1534 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1535 if (tempfilename)
1537 int tempfd = mkstemps(tempfilename, 0);
1538 if (tempfd >= 0)
1540 tempfile = fdopen(tempfd, "w");
1541 if (tempfile)
1542 break;
1543 close(tempfd);
1544 goto end;
1546 else if (errno == EEXIST)
1548 HeapFree(GetProcessHeap(), 0, tempfilename);
1549 continue;
1551 HeapFree(GetProcessHeap(), 0, tempfilename);
1553 return FALSE;
1556 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1557 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1558 fprintf(tempfile, "<Menu>\n");
1559 fprintf(tempfile, " <Name>Applications</Name>\n");
1561 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1562 if (name == NULL) goto end;
1563 lastEntry = name;
1564 for (i = 0; filename[i]; i++)
1566 name[i] = filename[i];
1567 if (filename[i] == '/')
1569 char *dir_file_name;
1570 struct stat st;
1571 name[i] = 0;
1572 fprintf(tempfile, " <Menu>\n");
1573 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1574 write_xml_text(tempfile, name);
1575 fprintf(tempfile, "</Name>\n");
1576 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1577 write_xml_text(tempfile, name);
1578 fprintf(tempfile, ".directory</Directory>\n");
1579 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1580 xdg_data_dir, count ? "" : "wine-", name);
1581 if (dir_file_name)
1583 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1584 write_directory_entry(lastEntry, dir_file_name);
1585 HeapFree(GetProcessHeap(), 0, dir_file_name);
1587 name[i] = '-';
1588 lastEntry = &name[i+1];
1589 ++count;
1592 name[i] = 0;
1594 fprintf(tempfile, " <Include>\n");
1595 fprintf(tempfile, " <Filename>");
1596 write_xml_text(tempfile, name);
1597 fprintf(tempfile, "</Filename>\n");
1598 fprintf(tempfile, " </Include>\n");
1599 for (i = 0; i < count; i++)
1600 fprintf(tempfile, " </Menu>\n");
1601 fprintf(tempfile, "</Menu>\n");
1603 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1604 if (menuPath == NULL) goto end;
1605 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1606 ret = TRUE;
1608 end:
1609 if (tempfile)
1610 fclose(tempfile);
1611 if (ret)
1612 ret = (rename(tempfilename, menuPath) == 0);
1613 if (!ret && tempfilename)
1614 remove(tempfilename);
1615 HeapFree(GetProcessHeap(), 0, tempfilename);
1616 if (ret)
1617 register_menus_entry(menuPath, unix_link);
1618 HeapFree(GetProcessHeap(), 0, name);
1619 HeapFree(GetProcessHeap(), 0, menuPath);
1620 return ret;
1623 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1624 const char *descr, const char *workdir, const char *icon, const char *wmclass)
1626 const char *linkname;
1627 char *desktopPath = NULL;
1628 char *desktopDir;
1629 char *filename = NULL;
1630 BOOL ret = TRUE;
1632 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1633 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1634 wine_dbgstr_a(workdir), wine_dbgstr_a(icon), wine_dbgstr_a(wmclass));
1636 linkname = strrchr(link, '/');
1637 if (linkname == NULL)
1638 linkname = link;
1639 else
1640 ++linkname;
1642 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1643 if (!desktopPath)
1645 WINE_WARN("out of memory creating menu entry\n");
1646 ret = FALSE;
1647 goto end;
1649 desktopDir = strrchr(desktopPath, '/');
1650 *desktopDir = 0;
1651 if (!create_directories(desktopPath))
1653 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1654 ret = FALSE;
1655 goto end;
1657 *desktopDir = '/';
1658 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon, wmclass))
1660 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1661 ret = FALSE;
1662 goto end;
1665 filename = heap_printf("wine/%s.desktop", link);
1666 if (!filename || !write_menu_file(unix_link, filename))
1668 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1669 ret = FALSE;
1672 end:
1673 HeapFree(GetProcessHeap(), 0, desktopPath);
1674 HeapFree(GetProcessHeap(), 0, filename);
1675 return ret;
1678 /* This escapes reserved characters in .desktop files' Exec keys. */
1679 static LPSTR escape(LPCWSTR arg)
1681 int i, j;
1682 WCHAR *escaped_string;
1683 char *utf8_string;
1685 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1686 if (escaped_string == NULL) return NULL;
1687 for (i = j = 0; arg[i]; i++)
1689 switch (arg[i])
1691 case '\\':
1692 escaped_string[j++] = '\\';
1693 escaped_string[j++] = '\\';
1694 escaped_string[j++] = '\\';
1695 escaped_string[j++] = '\\';
1696 break;
1697 case ' ':
1698 case '\t':
1699 case '\n':
1700 case '"':
1701 case '\'':
1702 case '>':
1703 case '<':
1704 case '~':
1705 case '|':
1706 case '&':
1707 case ';':
1708 case '$':
1709 case '*':
1710 case '?':
1711 case '#':
1712 case '(':
1713 case ')':
1714 case '`':
1715 escaped_string[j++] = '\\';
1716 escaped_string[j++] = '\\';
1717 /* fall through */
1718 default:
1719 escaped_string[j++] = arg[i];
1720 break;
1723 escaped_string[j] = 0;
1725 utf8_string = wchars_to_utf8_chars(escaped_string);
1726 if (utf8_string == NULL)
1728 WINE_ERR("out of memory\n");
1729 goto end;
1732 end:
1733 HeapFree(GetProcessHeap(), 0, escaped_string);
1734 return utf8_string;
1737 /* Return a heap-allocated copy of the unix format difference between the two
1738 * Windows-format paths.
1739 * locn is the owning location
1740 * link is within locn
1742 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1744 char *unix_locn, *unix_link;
1745 char *relative = NULL;
1747 unix_locn = wine_get_unix_file_name(locn);
1748 unix_link = wine_get_unix_file_name(link);
1749 if (unix_locn && unix_link)
1751 size_t len_unix_locn, len_unix_link;
1752 len_unix_locn = strlen (unix_locn);
1753 len_unix_link = strlen (unix_link);
1754 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1756 size_t len_rel;
1757 char *p = strrchr (unix_link + len_unix_locn, '/');
1758 p = strrchr (p, '.');
1759 if (p)
1761 *p = '\0';
1762 len_unix_link = p - unix_link;
1764 len_rel = len_unix_link - len_unix_locn;
1765 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1766 if (relative)
1768 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1772 if (!relative)
1773 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1774 HeapFree(GetProcessHeap(), 0, unix_locn);
1775 HeapFree(GetProcessHeap(), 0, unix_link);
1776 return relative;
1779 /***********************************************************************
1781 * GetLinkLocation
1783 * returns TRUE if successful
1784 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1785 * *relative will contain the address of a heap-allocated copy of the portion
1786 * of the filename that is within the specified location, in unix form
1788 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1790 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1791 DWORD len, i, r, filelen;
1792 const DWORD locations[] = {
1793 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1794 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1795 CSIDL_COMMON_STARTMENU };
1797 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1798 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1799 if (filelen==0 || filelen>MAX_PATH)
1800 return FALSE;
1802 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1804 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1805 * expand or our hardcoded list won't match.
1807 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1808 if (filelen==0 || filelen>MAX_PATH)
1809 return FALSE;
1811 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1813 for( i=0; i<ARRAY_SIZE( locations ); i++ )
1815 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1816 continue;
1818 len = lstrlenW(buffer);
1819 if (len >= MAX_PATH)
1820 continue; /* We've just trashed memory! Hopefully we are OK */
1822 if (len > filelen || filename[len]!='\\')
1823 continue;
1824 /* do a lstrcmpinW */
1825 filename[len] = 0;
1826 r = lstrcmpiW( filename, buffer );
1827 filename[len] = '\\';
1828 if ( r )
1829 continue;
1831 /* return the remainder of the string and link type */
1832 *loc = locations[i];
1833 *relative = relative_path (filename, buffer);
1834 return (*relative != NULL);
1837 return FALSE;
1840 /* gets the target path directly or through MSI */
1841 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1842 LPWSTR szArgs, DWORD argsSize)
1844 IShellLinkDataList *dl = NULL;
1845 EXP_DARWIN_LINK *dar = NULL;
1846 HRESULT hr;
1848 szPath[0] = 0;
1849 szArgs[0] = 0;
1851 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1852 if (hr == S_OK && szPath[0])
1854 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1855 return hr;
1858 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1859 if (FAILED(hr))
1860 return hr;
1862 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1863 if (SUCCEEDED(hr))
1865 WCHAR* szCmdline;
1866 DWORD cmdSize;
1868 cmdSize=0;
1869 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1870 if (hr == ERROR_SUCCESS)
1872 cmdSize++;
1873 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1874 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1875 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1876 if (hr == ERROR_SUCCESS)
1878 WCHAR *s, *d;
1879 int bcount = 0;
1880 BOOL in_quotes = FALSE;
1882 /* Extract the application path */
1883 s=szCmdline;
1884 d=szPath;
1885 while (*s)
1887 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1889 /* skip the remaining spaces */
1890 do {
1891 s++;
1892 } while (*s==0x0009 || *s==0x0020);
1893 break;
1895 else if (*s==0x005c)
1897 /* '\\' */
1898 *d++=*s++;
1899 bcount++;
1901 else if (*s==0x0022)
1903 /* '"' */
1904 if ((bcount & 1)==0)
1906 /* Preceded by an even number of '\', this is
1907 * half that number of '\', plus a quote which
1908 * we erase.
1910 d-=bcount/2;
1911 in_quotes=!in_quotes;
1912 s++;
1914 else
1916 /* Preceded by an odd number of '\', this is
1917 * half that number of '\' followed by a '"'
1919 d=d-bcount/2-1;
1920 *d++='"';
1921 s++;
1923 bcount=0;
1925 else
1927 /* a regular character */
1928 *d++=*s++;
1929 bcount=0;
1931 if ((d-szPath) == pathSize)
1933 /* Keep processing the path till we get to the
1934 * arguments, but 'stand still'
1936 d--;
1939 /* Close the application path */
1940 *d=0;
1942 lstrcpynW(szArgs, s, argsSize);
1944 HeapFree( GetProcessHeap(), 0, szCmdline );
1946 LocalFree( dar );
1949 IShellLinkDataList_Release( dl );
1950 return hr;
1953 static char *slashes_to_minuses(const char *string)
1955 int i;
1956 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1957 if (ret)
1959 for (i = 0; string[i]; i++)
1961 if (string[i] == '/')
1962 ret[i] = '-';
1963 else
1964 ret[i] = string[i];
1966 ret[i] = 0;
1967 return ret;
1969 return NULL;
1972 static BOOL next_line(FILE *file, char **line, int *size)
1974 int pos = 0;
1975 char *cr;
1976 if (*line == NULL)
1978 *size = 4096;
1979 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1981 while (*line != NULL)
1983 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1985 HeapFree(GetProcessHeap(), 0, *line);
1986 *line = NULL;
1987 if (feof(file))
1988 return TRUE;
1989 return FALSE;
1991 pos = strlen(*line);
1992 cr = strchr(*line, '\n');
1993 if (cr == NULL)
1995 char *line2;
1996 (*size) *= 2;
1997 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1998 if (line2)
1999 *line = line2;
2000 else
2002 HeapFree(GetProcessHeap(), 0, *line);
2003 *line = NULL;
2006 else
2008 *cr = 0;
2009 return TRUE;
2012 return FALSE;
2015 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
2017 char *globs_filename = NULL;
2018 BOOL ret = TRUE;
2019 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
2020 if (globs_filename)
2022 FILE *globs_file = fopen(globs_filename, "r");
2023 if (globs_file) /* doesn't have to exist */
2025 char *line = NULL;
2026 int size = 0;
2027 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
2029 char *pos;
2030 struct xdg_mime_type *mime_type_entry = NULL;
2031 if (line[0] != '#' && (pos = strchr(line, ':')))
2033 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
2034 if (mime_type_entry)
2036 *pos = 0;
2037 mime_type_entry->mimeType = strdupA(line);
2038 mime_type_entry->glob = strdupA(pos + 1);
2039 mime_type_entry->lower_glob = strdupA(pos + 1);
2040 if (mime_type_entry->lower_glob)
2042 char *l;
2043 for (l = mime_type_entry->lower_glob; *l; l++)
2044 *l = tolower(*l);
2046 if (mime_type_entry->mimeType && mime_type_entry->glob && mime_type_entry->lower_glob)
2047 list_add_tail(mime_types, &mime_type_entry->entry);
2048 else
2050 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2051 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2052 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2053 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2054 ret = FALSE;
2057 else
2058 ret = FALSE;
2061 HeapFree(GetProcessHeap(), 0, line);
2062 fclose(globs_file);
2064 HeapFree(GetProcessHeap(), 0, globs_filename);
2066 else
2067 ret = FALSE;
2068 return ret;
2071 static void free_native_mime_types(struct list *native_mime_types)
2073 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
2075 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
2077 list_remove(&mime_type_entry->entry);
2078 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2079 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2080 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2081 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2085 static BOOL build_native_mime_types(const char *xdg_data_home, struct list *mime_types)
2087 char *xdg_data_dirs;
2088 BOOL ret;
2090 xdg_data_dirs = getenv("XDG_DATA_DIRS");
2091 if (xdg_data_dirs == NULL)
2092 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
2093 else
2094 xdg_data_dirs = strdupA(xdg_data_dirs);
2096 if (xdg_data_dirs)
2098 const char *begin;
2099 char *end;
2101 ret = add_mimes(xdg_data_home, mime_types);
2102 if (ret)
2104 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
2106 *end = '\0';
2107 ret = add_mimes(begin, mime_types);
2108 *end = ':';
2109 if (!ret)
2110 break;
2112 if (ret)
2113 ret = add_mimes(begin, mime_types);
2115 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
2117 else
2118 ret = FALSE;
2119 if (!ret)
2120 free_native_mime_types(mime_types);
2121 return ret;
2124 static BOOL match_glob(struct list *native_mime_types, const char *extension,
2125 int ignoreGlobCase, char **match)
2127 #ifdef HAVE_FNMATCH
2128 struct xdg_mime_type *mime_type_entry;
2129 int matchLength = 0;
2131 *match = NULL;
2133 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
2135 const char *glob = ignoreGlobCase ? mime_type_entry->lower_glob : mime_type_entry->glob;
2136 if (fnmatch(glob, extension, 0) == 0)
2138 if (*match == NULL || matchLength < strlen(glob))
2140 *match = mime_type_entry->mimeType;
2141 matchLength = strlen(glob);
2146 if (*match != NULL)
2148 *match = strdupA(*match);
2149 if (*match == NULL)
2150 return FALSE;
2152 #else
2153 *match = NULL;
2154 #endif
2155 return TRUE;
2158 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
2159 const char *extensionA,
2160 LPCWSTR extensionW,
2161 char **mime_type)
2163 WCHAR *lower_extensionW;
2164 INT len;
2165 BOOL ret = match_glob(native_mime_types, extensionA, 0, mime_type);
2166 if (ret == FALSE || *mime_type != NULL)
2167 return ret;
2168 len = strlenW(extensionW);
2169 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
2170 if (lower_extensionW)
2172 char *lower_extensionA;
2173 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
2174 strlwrW(lower_extensionW);
2175 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
2176 if (lower_extensionA)
2178 ret = match_glob(native_mime_types, lower_extensionA, 1, mime_type);
2179 HeapFree(GetProcessHeap(), 0, lower_extensionA);
2181 else
2183 ret = FALSE;
2184 WINE_FIXME("out of memory\n");
2186 HeapFree(GetProcessHeap(), 0, lower_extensionW);
2188 else
2190 ret = FALSE;
2191 WINE_FIXME("out of memory\n");
2193 return ret;
2196 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
2198 DWORD size;
2199 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
2201 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
2202 if (ret)
2204 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
2205 return ret;
2207 HeapFree(GetProcessHeap(), 0, ret);
2209 return NULL;
2212 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
2214 WCHAR *valW = reg_get_valW(key, subkey, name);
2215 if (valW)
2217 char *val = wchars_to_utf8_chars(valW);
2218 HeapFree(GetProcessHeap(), 0, valW);
2219 return val;
2221 return NULL;
2224 static HKEY open_associations_reg_key(void)
2226 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
2227 '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};
2228 HKEY assocKey;
2229 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
2230 return assocKey;
2231 return NULL;
2234 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
2235 LPCSTR appName, LPCSTR openWithIcon)
2237 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2238 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2239 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2240 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2241 HKEY assocKey;
2242 BOOL ret;
2244 if ((assocKey = open_associations_reg_key()))
2246 CHAR *valueA;
2247 WCHAR *value;
2249 ret = FALSE;
2251 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
2252 if (!valueA || lstrcmpA(valueA, mimeType))
2253 ret = TRUE;
2254 HeapFree(GetProcessHeap(), 0, valueA);
2256 value = reg_get_valW(assocKey, extensionW, ProgIDW);
2257 if (!value || strcmpW(value, progId))
2258 ret = TRUE;
2259 HeapFree(GetProcessHeap(), 0, value);
2261 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2262 if (!valueA || lstrcmpA(valueA, appName))
2263 ret = TRUE;
2264 HeapFree(GetProcessHeap(), 0, valueA);
2266 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
2267 if ((openWithIcon && !valueA) ||
2268 (!openWithIcon && valueA) ||
2269 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
2270 ret = TRUE;
2271 HeapFree(GetProcessHeap(), 0, valueA);
2273 RegCloseKey(assocKey);
2275 else
2277 WINE_ERR("error opening associations registry key\n");
2278 ret = FALSE;
2280 return ret;
2283 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2284 LPCSTR appName, LPCSTR desktopFile, LPCSTR openWithIcon)
2286 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2287 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2288 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2289 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2290 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2291 HKEY assocKey = NULL;
2292 HKEY subkey = NULL;
2293 WCHAR *mimeTypeW = NULL;
2294 WCHAR *appNameW = NULL;
2295 WCHAR *desktopFileW = NULL;
2296 WCHAR *openWithIconW = NULL;
2298 assocKey = open_associations_reg_key();
2299 if (assocKey == NULL)
2301 WINE_ERR("could not open file associations key\n");
2302 goto done;
2305 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2307 WINE_ERR("could not create extension subkey\n");
2308 goto done;
2311 mimeTypeW = utf8_chars_to_wchars(mimeType);
2312 if (mimeTypeW == NULL)
2314 WINE_ERR("out of memory\n");
2315 goto done;
2318 appNameW = utf8_chars_to_wchars(appName);
2319 if (appNameW == NULL)
2321 WINE_ERR("out of memory\n");
2322 goto done;
2325 desktopFileW = utf8_chars_to_wchars(desktopFile);
2326 if (desktopFileW == NULL)
2328 WINE_ERR("out of memory\n");
2329 goto done;
2332 if (openWithIcon)
2334 openWithIconW = utf8_chars_to_wchars(openWithIcon);
2335 if (openWithIconW == NULL)
2337 WINE_ERR("out of memory\n");
2338 goto done;
2342 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2343 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2344 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2345 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2346 if (openWithIcon)
2347 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
2348 else
2349 RegDeleteValueW(subkey, OpenWithIconW);
2351 done:
2352 RegCloseKey(assocKey);
2353 RegCloseKey(subkey);
2354 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2355 HeapFree(GetProcessHeap(), 0, appNameW);
2356 HeapFree(GetProcessHeap(), 0, desktopFileW);
2357 HeapFree(GetProcessHeap(), 0, openWithIconW);
2360 static BOOL cleanup_associations(void)
2362 static const WCHAR openW[] = {'o','p','e','n',0};
2363 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2364 HKEY assocKey;
2365 BOOL hasChanged = FALSE;
2366 if ((assocKey = open_associations_reg_key()))
2368 int i;
2369 BOOL done = FALSE;
2370 for (i = 0; !done;)
2372 WCHAR *extensionW = NULL;
2373 DWORD size = 1024;
2374 LSTATUS ret;
2378 HeapFree(GetProcessHeap(), 0, extensionW);
2379 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2380 if (extensionW == NULL)
2382 WINE_ERR("out of memory\n");
2383 ret = ERROR_OUTOFMEMORY;
2384 break;
2386 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2387 size *= 2;
2388 } while (ret == ERROR_MORE_DATA);
2390 if (ret == ERROR_SUCCESS)
2392 WCHAR *command;
2393 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2394 if (command == NULL)
2396 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2397 if (desktopFile)
2399 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2400 remove(desktopFile);
2402 RegDeleteKeyW(assocKey, extensionW);
2403 hasChanged = TRUE;
2404 HeapFree(GetProcessHeap(), 0, desktopFile);
2406 else
2407 i++;
2408 HeapFree(GetProcessHeap(), 0, command);
2410 else
2412 if (ret != ERROR_NO_MORE_ITEMS)
2413 WINE_ERR("error %d while reading registry\n", ret);
2414 done = TRUE;
2416 HeapFree(GetProcessHeap(), 0, extensionW);
2418 RegCloseKey(assocKey);
2420 else
2421 WINE_ERR("could not open file associations key\n");
2422 return hasChanged;
2425 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2426 const char *mime_type, const char *comment)
2428 BOOL ret = FALSE;
2429 char *filename;
2431 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2432 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2434 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2435 if (filename)
2437 FILE *packageFile = fopen(filename, "w");
2438 if (packageFile)
2440 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2441 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2442 fprintf(packageFile, " <mime-type type=\"");
2443 write_xml_text(packageFile, mime_type);
2444 fprintf(packageFile, "\">\n");
2445 fprintf(packageFile, " <glob pattern=\"*");
2446 write_xml_text(packageFile, dot_extension);
2447 fprintf(packageFile, "\"/>\n");
2448 if (comment)
2450 fprintf(packageFile, " <comment>");
2451 write_xml_text(packageFile, comment);
2452 fprintf(packageFile, "</comment>\n");
2454 fprintf(packageFile, " </mime-type>\n");
2455 fprintf(packageFile, "</mime-info>\n");
2456 ret = TRUE;
2457 fclose(packageFile);
2459 else
2460 WINE_ERR("error writing file %s\n", filename);
2461 HeapFree(GetProcessHeap(), 0, filename);
2463 else
2464 WINE_ERR("out of memory\n");
2465 return ret;
2468 static BOOL is_extension_blacklisted(LPCWSTR extension)
2470 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2471 static const WCHAR comW[] = {'.','c','o','m',0};
2472 static const WCHAR exeW[] = {'.','e','x','e',0};
2473 static const WCHAR msiW[] = {'.','m','s','i',0};
2475 if (!strcmpiW(extension, comW) ||
2476 !strcmpiW(extension, exeW) ||
2477 !strcmpiW(extension, msiW))
2478 return TRUE;
2479 return FALSE;
2482 static const char* get_special_mime_type(LPCWSTR extension)
2484 static const WCHAR lnkW[] = {'.','l','n','k',0};
2485 if (!strcmpiW(extension, lnkW))
2486 return "application/x-ms-shortcut";
2487 return NULL;
2490 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2491 const char *friendlyAppName, const char *mimeType,
2492 const char *progId, const char *openWithIcon)
2494 BOOL ret = FALSE;
2495 FILE *desktop;
2497 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2498 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2499 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2501 desktop = fopen(desktopPath, "w");
2502 if (desktop)
2504 fprintf(desktop, "[Desktop Entry]\n");
2505 fprintf(desktop, "Type=Application\n");
2506 fprintf(desktop, "Name=%s\n", friendlyAppName);
2507 fprintf(desktop, "MimeType=%s;\n", mimeType);
2508 fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId);
2509 fprintf(desktop, "NoDisplay=true\n");
2510 fprintf(desktop, "StartupNotify=true\n");
2511 if (openWithIcon)
2512 fprintf(desktop, "Icon=%s\n", openWithIcon);
2513 ret = TRUE;
2514 fclose(desktop);
2516 else
2517 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2518 return ret;
2521 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2523 static const WCHAR openW[] = {'o','p','e','n',0};
2524 struct wine_rb_tree mimeProgidTree = { winemenubuilder_rb_string_compare };
2525 struct list nativeMimeTypes = LIST_INIT(nativeMimeTypes);
2526 LSTATUS ret = 0;
2527 int i;
2528 BOOL hasChanged = FALSE;
2530 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2532 WINE_ERR("could not build native MIME types\n");
2533 return FALSE;
2536 for (i = 0; ; i++)
2538 WCHAR *extensionW = NULL;
2539 DWORD size = 1024;
2543 HeapFree(GetProcessHeap(), 0, extensionW);
2544 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2545 if (extensionW == NULL)
2547 WINE_ERR("out of memory\n");
2548 ret = ERROR_OUTOFMEMORY;
2549 break;
2551 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2552 size *= 2;
2553 } while (ret == ERROR_MORE_DATA);
2555 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2557 char *extensionA = NULL;
2558 WCHAR *commandW = NULL;
2559 WCHAR *executableW = NULL;
2560 char *openWithIconA = NULL;
2561 WCHAR *friendlyDocNameW = NULL;
2562 char *friendlyDocNameA = NULL;
2563 WCHAR *iconW = NULL;
2564 char *iconA = NULL;
2565 WCHAR *contentTypeW = NULL;
2566 char *mimeTypeA = NULL;
2567 WCHAR *friendlyAppNameW = NULL;
2568 char *friendlyAppNameA = NULL;
2569 WCHAR *progIdW = NULL;
2570 char *progIdA = NULL;
2571 char *mimeProgId = NULL;
2573 extensionA = wchars_to_utf8_chars(strlwrW(extensionW));
2574 if (extensionA == NULL)
2576 WINE_ERR("out of memory\n");
2577 goto end;
2580 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2581 if (friendlyDocNameW)
2583 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2584 if (friendlyDocNameA == NULL)
2586 WINE_ERR("out of memory\n");
2587 goto end;
2591 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2593 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2594 if (contentTypeW)
2595 strlwrW(contentTypeW);
2597 if (!freedesktop_mime_type_for_extension(&nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2598 goto end;
2600 if (mimeTypeA == NULL)
2602 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2603 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2604 else if ((get_special_mime_type(extensionW)))
2605 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2606 else
2607 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2609 if (mimeTypeA != NULL)
2611 /* GNOME seems to ignore the <icon> tag in MIME packages,
2612 * and the default name is more intuitive anyway.
2614 if (iconW)
2616 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2617 if (flattened_mime)
2619 int index = 0;
2620 WCHAR *comma = strrchrW(iconW, ',');
2621 if (comma)
2623 *comma = 0;
2624 index = atoiW(comma + 1);
2626 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2627 HeapFree(GetProcessHeap(), 0, flattened_mime);
2631 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2632 hasChanged = TRUE;
2634 else
2636 WINE_FIXME("out of memory\n");
2637 goto end;
2641 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2642 if (commandW == NULL)
2643 /* no command => no application is associated */
2644 goto end;
2646 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2647 if (executableW)
2648 openWithIconA = extract_icon(executableW, 0, NULL, FALSE);
2650 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, openW);
2651 if (friendlyAppNameW)
2653 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2654 if (friendlyAppNameA == NULL)
2656 WINE_ERR("out of memory\n");
2657 goto end;
2660 else
2662 friendlyAppNameA = heap_printf("A Wine application");
2663 if (friendlyAppNameA == NULL)
2665 WINE_ERR("out of memory\n");
2666 goto end;
2670 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2671 if (progIdW)
2673 progIdA = escape(progIdW);
2674 if (progIdA == NULL)
2676 WINE_ERR("out of memory\n");
2677 goto end;
2680 else
2681 goto end; /* no progID => not a file type association */
2683 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2684 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2685 if (mimeProgId)
2687 struct rb_string_entry *entry;
2688 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2690 HeapFree(GetProcessHeap(), 0, mimeProgId);
2691 goto end;
2693 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2694 if (!entry)
2696 WINE_ERR("out of memory allocating rb_string_entry\n");
2697 goto end;
2699 entry->string = mimeProgId;
2700 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2702 WINE_ERR("error updating rb tree\n");
2703 goto end;
2707 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, openWithIconA))
2709 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2710 if (desktopPath)
2712 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2714 hasChanged = TRUE;
2715 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, desktopPath, openWithIconA);
2717 HeapFree(GetProcessHeap(), 0, desktopPath);
2721 end:
2722 HeapFree(GetProcessHeap(), 0, extensionA);
2723 HeapFree(GetProcessHeap(), 0, commandW);
2724 HeapFree(GetProcessHeap(), 0, executableW);
2725 HeapFree(GetProcessHeap(), 0, openWithIconA);
2726 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2727 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2728 HeapFree(GetProcessHeap(), 0, iconW);
2729 HeapFree(GetProcessHeap(), 0, iconA);
2730 HeapFree(GetProcessHeap(), 0, contentTypeW);
2731 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2732 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2733 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2734 HeapFree(GetProcessHeap(), 0, progIdW);
2735 HeapFree(GetProcessHeap(), 0, progIdA);
2737 HeapFree(GetProcessHeap(), 0, extensionW);
2738 if (ret != ERROR_SUCCESS)
2739 break;
2742 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2743 free_native_mime_types(&nativeMimeTypes);
2744 return hasChanged;
2747 static char *get_start_exe_path(void)
2749 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2750 '\\','s','t','a','r','t','.','e','x','e',0};
2751 WCHAR start_path[MAX_PATH];
2752 GetWindowsDirectoryW(start_path, MAX_PATH);
2753 lstrcatW(start_path, startW);
2754 return escape(start_path);
2757 static char* escape_unix_link_arg(LPCSTR unix_link)
2759 char *ret = NULL;
2760 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2761 if (unix_linkW)
2763 char *escaped_lnk = escape(unix_linkW);
2764 if (escaped_lnk)
2766 ret = heap_printf("/Unix %s", escaped_lnk);
2767 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2769 HeapFree(GetProcessHeap(), 0, unix_linkW);
2771 return ret;
2774 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2776 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2777 '\\','s','t','a','r','t','.','e','x','e',0};
2778 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2779 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2780 char *wmclass = NULL;
2781 WCHAR szTmp[INFOTIPSIZE];
2782 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2783 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH], szWMClass[MAX_PATH];
2784 int iIconId = 0, r = -1;
2785 DWORD csidl = -1;
2786 HANDLE hsem = NULL;
2787 char *unix_link = NULL;
2788 char *start_path = NULL;
2790 if ( !link )
2792 WINE_ERR("Link name is null\n");
2793 return FALSE;
2796 if( !GetLinkLocation( link, &csidl, &link_name ) )
2798 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2799 return TRUE;
2801 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2803 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2804 return TRUE;
2806 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2808 szTmp[0] = 0;
2809 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2810 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2811 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2813 szTmp[0] = 0;
2814 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2815 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2816 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2818 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2819 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2820 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2821 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2823 szTmp[0] = 0;
2824 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2825 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2826 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2828 szWMClass[0] = 0;
2830 if( !szPath[0] )
2832 LPITEMIDLIST pidl = NULL;
2833 IShellLinkW_GetIDList( sl, &pidl );
2834 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2835 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2838 /* extract the icon */
2839 if( szIconPath[0] )
2840 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2841 else
2842 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2844 /* fail - try once again after parent process exit */
2845 if( !icon_name )
2847 if (bWait)
2849 WINE_WARN("Unable to extract icon, deferring.\n");
2850 goto cleanup;
2852 WINE_ERR("failed to extract icon from %s\n",
2853 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2856 unix_link = wine_get_unix_file_name(link);
2857 if (unix_link == NULL)
2859 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2860 goto cleanup;
2863 /* check the path */
2864 if( szPath[0] )
2866 static const WCHAR exeW[] = {'.','e','x','e',0};
2867 WCHAR *p;
2869 /* check for .exe extension */
2870 if (!(p = strrchrW( szPath, '.' )) ||
2871 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2872 lstrcmpiW( p, exeW ))
2874 /* Not .exe - use 'start.exe' to launch this file */
2875 p = szArgs + lstrlenW(szPath) + 2;
2876 if (szArgs[0])
2878 p[0] = ' ';
2879 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2880 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2882 else
2883 p[0] = 0;
2885 szArgs[0] = '"';
2886 lstrcpyW(szArgs + 1, szPath);
2887 p[-1] = '"';
2889 GetWindowsDirectoryW(szPath, MAX_PATH);
2890 lstrcatW(szPath, startW);
2892 else
2894 /* FIXME: Use AppUserModelID if present. */
2895 WCHAR *p = PathFindFileNameW(szPath);
2897 lstrcpyW(szWMClass, p);
2898 CharLowerW(szWMClass);
2901 /* convert app working dir */
2902 if (szWorkDir[0])
2903 work_dir = wine_get_unix_file_name( szWorkDir );
2905 else
2907 /* if there's no path... try run the link itself */
2908 lstrcpynW(szArgs, link, MAX_PATH);
2909 GetWindowsDirectoryW(szPath, MAX_PATH);
2910 lstrcatW(szPath, startW);
2913 /* escape the path and parameters */
2914 escaped_path = escape(szPath);
2915 escaped_args = escape(szArgs);
2916 description = wchars_to_utf8_chars(szDescription);
2917 wmclass = wchars_to_utf8_chars(szWMClass);
2918 if (escaped_path == NULL || escaped_args == NULL || description == NULL || wmclass == NULL)
2920 WINE_ERR("out of memory allocating/escaping parameters\n");
2921 goto cleanup;
2924 start_path = get_start_exe_path();
2925 if (start_path == NULL)
2927 WINE_ERR("out of memory\n");
2928 goto cleanup;
2931 /* building multiple menus concurrently has race conditions */
2932 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2933 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2935 WINE_ERR("failed wait for semaphore\n");
2936 goto cleanup;
2939 if (in_desktop_dir(csidl))
2941 char *location;
2942 const char *lastEntry;
2943 lastEntry = strrchr(link_name, '/');
2944 if (lastEntry == NULL)
2945 lastEntry = link_name;
2946 else
2947 ++lastEntry;
2948 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2949 if (location)
2951 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2953 char *link_arg = escape_unix_link_arg(unix_link);
2954 if (link_arg)
2956 r = !write_desktop_entry(unix_link, location, lastEntry,
2957 start_path, link_arg, description, work_dir, icon_name, wmclass);
2958 HeapFree(GetProcessHeap(), 0, link_arg);
2961 else
2962 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name, wmclass);
2963 if (r == 0)
2964 chmod(location, 0755);
2965 HeapFree(GetProcessHeap(), 0, location);
2968 else
2970 char *link_arg = escape_unix_link_arg(unix_link);
2971 if (link_arg)
2973 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name, wmclass);
2974 HeapFree(GetProcessHeap(), 0, link_arg);
2978 ReleaseSemaphore( hsem, 1, NULL );
2980 cleanup:
2981 if (hsem) CloseHandle( hsem );
2982 HeapFree( GetProcessHeap(), 0, icon_name );
2983 HeapFree( GetProcessHeap(), 0, work_dir );
2984 HeapFree( GetProcessHeap(), 0, link_name );
2985 HeapFree( GetProcessHeap(), 0, escaped_args );
2986 HeapFree( GetProcessHeap(), 0, escaped_path );
2987 HeapFree( GetProcessHeap(), 0, description );
2988 HeapFree( GetProcessHeap(), 0, wmclass );
2989 HeapFree( GetProcessHeap(), 0, unix_link );
2990 HeapFree( GetProcessHeap(), 0, start_path );
2992 if (r && !bWait)
2993 WINE_ERR("failed to build the menu\n" );
2995 return ( r == 0 );
2998 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
3000 char *link_name = NULL, *icon_name = NULL;
3001 DWORD csidl = -1;
3002 LPWSTR urlPath = NULL;
3003 char *escaped_urlPath = NULL;
3004 HRESULT hr;
3005 HANDLE hSem = NULL;
3006 BOOL ret = TRUE;
3007 int r = -1;
3008 char *unix_link = NULL;
3009 IPropertySetStorage *pPropSetStg;
3010 IPropertyStorage *pPropStg;
3011 PROPSPEC ps[2];
3012 PROPVARIANT pv[2];
3013 char *start_path = NULL;
3014 BOOL has_icon = FALSE;
3016 if ( !link )
3018 WINE_ERR("Link name is null\n");
3019 return TRUE;
3022 if( !GetLinkLocation( link, &csidl, &link_name ) )
3024 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
3025 return TRUE;
3027 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
3029 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3030 ret = TRUE;
3031 goto cleanup;
3033 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
3035 hr = url->lpVtbl->GetURL(url, &urlPath);
3036 if (FAILED(hr))
3038 ret = TRUE;
3039 goto cleanup;
3041 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
3043 unix_link = wine_get_unix_file_name(link);
3044 if (unix_link == NULL)
3046 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
3047 goto cleanup;
3050 escaped_urlPath = escape(urlPath);
3051 if (escaped_urlPath == NULL)
3053 WINE_ERR("couldn't escape url, out of memory\n");
3054 goto cleanup;
3057 start_path = get_start_exe_path();
3058 if (start_path == NULL)
3060 WINE_ERR("out of memory\n");
3061 goto cleanup;
3064 ps[0].ulKind = PRSPEC_PROPID;
3065 ps[0].u.propid = PID_IS_ICONFILE;
3066 ps[1].ulKind = PRSPEC_PROPID;
3067 ps[1].u.propid = PID_IS_ICONINDEX;
3069 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
3070 if (SUCCEEDED(hr))
3072 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
3073 if (SUCCEEDED(hr))
3075 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
3076 if (SUCCEEDED(hr))
3078 if (pv[0].vt == VT_LPWSTR && pv[0].u.pwszVal && pv[0].u.pwszVal[0])
3080 has_icon = TRUE;
3081 icon_name = extract_icon( pv[0].u.pwszVal, pv[1].u.iVal, NULL, bWait );
3083 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);
3085 PropVariantClear(&pv[0]);
3086 PropVariantClear(&pv[1]);
3088 IPropertyStorage_Release(pPropStg);
3090 IPropertySetStorage_Release(pPropSetStg);
3093 /* fail - try once again after parent process exit */
3094 if( has_icon && !icon_name )
3096 if (bWait)
3098 WINE_WARN("Unable to extract icon, deferring.\n");
3099 ret = FALSE;
3100 goto cleanup;
3102 WINE_ERR("failed to extract icon from %s\n",
3103 wine_dbgstr_w( pv[0].u.pwszVal ));
3106 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3107 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3109 WINE_ERR("failed wait for semaphore\n");
3110 goto cleanup;
3112 if (in_desktop_dir(csidl))
3114 char *location;
3115 const char *lastEntry;
3116 lastEntry = strrchr(link_name, '/');
3117 if (lastEntry == NULL)
3118 lastEntry = link_name;
3119 else
3120 ++lastEntry;
3121 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
3122 if (location)
3124 r = !write_desktop_entry(NULL, location, lastEntry, start_path, escaped_urlPath, NULL, NULL, icon_name, NULL);
3125 if (r == 0)
3126 chmod(location, 0755);
3127 HeapFree(GetProcessHeap(), 0, location);
3130 else
3131 r = !write_menu_entry(unix_link, link_name, start_path, escaped_urlPath, NULL, NULL, icon_name, NULL);
3132 ret = (r == 0);
3133 ReleaseSemaphore(hSem, 1, NULL);
3135 cleanup:
3136 if (hSem)
3137 CloseHandle(hSem);
3138 HeapFree( GetProcessHeap(), 0, icon_name );
3139 HeapFree(GetProcessHeap(), 0, link_name);
3140 CoTaskMemFree( urlPath );
3141 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
3142 HeapFree(GetProcessHeap(), 0, unix_link);
3143 return ret;
3146 static BOOL WaitForParentProcess( void )
3148 PROCESSENTRY32 procentry;
3149 HANDLE hsnapshot = NULL, hprocess = NULL;
3150 DWORD ourpid = GetCurrentProcessId();
3151 BOOL ret = FALSE, rc;
3153 WINE_TRACE("Waiting for parent process\n");
3154 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
3155 INVALID_HANDLE_VALUE)
3157 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3158 goto done;
3161 procentry.dwSize = sizeof(PROCESSENTRY32);
3162 rc = Process32First( hsnapshot, &procentry );
3163 while (rc)
3165 if (procentry.th32ProcessID == ourpid) break;
3166 rc = Process32Next( hsnapshot, &procentry );
3168 if (!rc)
3170 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
3171 goto done;
3174 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
3175 NULL)
3177 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
3178 GetLastError());
3179 goto done;
3182 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
3183 ret = TRUE;
3184 else
3185 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3187 done:
3188 if (hprocess) CloseHandle( hprocess );
3189 if (hsnapshot) CloseHandle( hsnapshot );
3190 return ret;
3193 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
3195 IShellLinkW *sl;
3196 IPersistFile *pf;
3197 HRESULT r;
3198 WCHAR fullname[MAX_PATH];
3199 DWORD len;
3201 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
3203 if( !linkname[0] )
3205 WINE_ERR("link name missing\n");
3206 return FALSE;
3209 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
3210 if (len==0 || len>MAX_PATH)
3212 WINE_ERR("couldn't get full path of link file\n");
3213 return FALSE;
3216 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3217 &IID_IShellLinkW, (LPVOID *) &sl );
3218 if( FAILED( r ) )
3220 WINE_ERR("No IID_IShellLink\n");
3221 return FALSE;
3224 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
3225 if( FAILED( r ) )
3227 WINE_ERR("No IID_IPersistFile\n");
3228 return FALSE;
3231 r = IPersistFile_Load( pf, fullname, STGM_READ );
3232 if( SUCCEEDED( r ) )
3234 /* If something fails (eg. Couldn't extract icon)
3235 * wait for parent process and try again
3237 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
3239 WaitForParentProcess();
3240 InvokeShellLinker( sl, fullname, FALSE );
3243 else
3245 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
3248 IPersistFile_Release( pf );
3249 IShellLinkW_Release( sl );
3251 return !r;
3254 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
3256 IUniformResourceLocatorW *url;
3257 IPersistFile *pf;
3258 HRESULT r;
3259 WCHAR fullname[MAX_PATH];
3260 DWORD len;
3262 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
3264 if( !urlname[0] )
3266 WINE_ERR("URL name missing\n");
3267 return FALSE;
3270 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
3271 if (len==0 || len>MAX_PATH)
3273 WINE_ERR("couldn't get full path of URL file\n");
3274 return FALSE;
3277 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
3278 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
3279 if( FAILED( r ) )
3281 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3282 return FALSE;
3285 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
3286 if( FAILED( r ) )
3288 WINE_ERR("No IID_IPersistFile\n");
3289 return FALSE;
3291 r = IPersistFile_Load( pf, fullname, STGM_READ );
3292 if( SUCCEEDED( r ) )
3294 /* If something fails (eg. Couldn't extract icon)
3295 * wait for parent process and try again
3297 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
3299 WaitForParentProcess();
3300 InvokeShellLinkerForURL( url, fullname, FALSE );
3304 IPersistFile_Release( pf );
3305 url->lpVtbl->Release( url );
3307 return !r;
3310 static void RefreshFileTypeAssociations(void)
3312 HANDLE hSem = NULL;
3313 char *mime_dir = NULL;
3314 char *packages_dir = NULL;
3315 char *applications_dir = NULL;
3316 BOOL hasChanged;
3318 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3319 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3321 WINE_ERR("failed wait for semaphore\n");
3322 CloseHandle(hSem);
3323 hSem = NULL;
3324 goto end;
3327 mime_dir = heap_printf("%s/mime", xdg_data_dir);
3328 if (mime_dir == NULL)
3330 WINE_ERR("out of memory\n");
3331 goto end;
3333 create_directories(mime_dir);
3335 packages_dir = heap_printf("%s/packages", mime_dir);
3336 if (packages_dir == NULL)
3338 WINE_ERR("out of memory\n");
3339 goto end;
3341 create_directories(packages_dir);
3343 applications_dir = heap_printf("%s/applications", xdg_data_dir);
3344 if (applications_dir == NULL)
3346 WINE_ERR("out of memory\n");
3347 goto end;
3349 create_directories(applications_dir);
3351 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3352 hasChanged |= cleanup_associations();
3353 if (hasChanged)
3355 const char *argv[3];
3357 argv[0] = "update-mime-database";
3358 argv[1] = mime_dir;
3359 argv[2] = NULL;
3360 _spawnvp( _P_DETACH, argv[0], argv );
3362 argv[0] = "update-desktop-database";
3363 argv[1] = applications_dir;
3364 _spawnvp( _P_DETACH, argv[0], argv );
3367 end:
3368 if (hSem)
3370 ReleaseSemaphore(hSem, 1, NULL);
3371 CloseHandle(hSem);
3373 HeapFree(GetProcessHeap(), 0, mime_dir);
3374 HeapFree(GetProcessHeap(), 0, packages_dir);
3375 HeapFree(GetProcessHeap(), 0, applications_dir);
3378 static void cleanup_menus(void)
3380 HKEY hkey;
3382 hkey = open_menus_reg_key();
3383 if (hkey)
3385 int i;
3386 LSTATUS lret = ERROR_SUCCESS;
3387 for (i = 0; lret == ERROR_SUCCESS; )
3389 WCHAR *value = NULL;
3390 WCHAR *data = NULL;
3391 DWORD valueSize = 4096;
3392 DWORD dataSize = 4096;
3393 while (1)
3395 lret = ERROR_OUTOFMEMORY;
3396 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3397 if (value == NULL)
3398 break;
3399 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3400 if (data == NULL)
3401 break;
3402 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3403 if (lret != ERROR_MORE_DATA)
3404 break;
3405 valueSize *= 2;
3406 dataSize *= 2;
3407 HeapFree(GetProcessHeap(), 0, value);
3408 HeapFree(GetProcessHeap(), 0, data);
3409 value = data = NULL;
3411 if (lret == ERROR_SUCCESS)
3413 char *unix_file;
3414 char *windows_file;
3415 unix_file = wchars_to_unix_chars(value);
3416 windows_file = wchars_to_unix_chars(data);
3417 if (unix_file != NULL && windows_file != NULL)
3419 struct stat filestats;
3420 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3422 WINE_TRACE("removing menu related file %s\n", unix_file);
3423 remove(unix_file);
3424 RegDeleteValueW(hkey, value);
3426 else
3427 i++;
3429 else
3431 WINE_ERR("out of memory enumerating menus\n");
3432 lret = ERROR_OUTOFMEMORY;
3434 HeapFree(GetProcessHeap(), 0, unix_file);
3435 HeapFree(GetProcessHeap(), 0, windows_file);
3437 else if (lret != ERROR_NO_MORE_ITEMS)
3438 WINE_ERR("error %d reading registry\n", lret);
3439 HeapFree(GetProcessHeap(), 0, value);
3440 HeapFree(GetProcessHeap(), 0, data);
3442 RegCloseKey(hkey);
3444 else
3445 WINE_ERR("error opening registry key, menu cleanup failed\n");
3448 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3450 char *utf8lnkPath = NULL;
3451 char *utf8OutputPath = NULL;
3452 WCHAR *winLnkPath = NULL;
3453 IShellLinkW *shellLink = NULL;
3454 IPersistFile *persistFile = NULL;
3455 WCHAR szTmp[MAX_PATH];
3456 WCHAR szPath[MAX_PATH];
3457 WCHAR szArgs[INFOTIPSIZE];
3458 WCHAR szIconPath[MAX_PATH];
3459 int iconId;
3460 IStream *stream = NULL;
3461 ICONDIRENTRY *pIconDirEntries = NULL;
3462 int numEntries;
3463 HRESULT hr;
3465 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3466 if (utf8lnkPath == NULL)
3468 WINE_ERR("out of memory converting paths\n");
3469 goto end;
3472 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3473 if (utf8OutputPath == NULL)
3475 WINE_ERR("out of memory converting paths\n");
3476 goto end;
3479 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3480 if (winLnkPath == NULL)
3482 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3483 goto end;
3486 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3487 &IID_IShellLinkW, (LPVOID*)&shellLink);
3488 if (FAILED(hr))
3490 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3491 goto end;
3494 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3495 if (FAILED(hr))
3497 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3498 goto end;
3501 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3502 if (FAILED(hr))
3504 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3505 goto end;
3508 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3509 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3510 szTmp[0] = 0;
3511 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3512 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3514 if(!szPath[0])
3516 LPITEMIDLIST pidl = NULL;
3517 IShellLinkW_GetIDList(shellLink, &pidl);
3518 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3519 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3522 if (szIconPath[0])
3524 hr = open_icon(szIconPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3525 if (SUCCEEDED(hr))
3526 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3528 else
3530 hr = open_icon(szPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3531 if (SUCCEEDED(hr))
3532 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3535 end:
3536 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3537 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3538 HeapFree(GetProcessHeap(), 0, winLnkPath);
3539 if (shellLink != NULL)
3540 IShellLinkW_Release(shellLink);
3541 if (persistFile != NULL)
3542 IPersistFile_Release(persistFile);
3543 if (stream != NULL)
3544 IStream_Release(stream);
3545 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
3548 static WCHAR *next_token( LPWSTR *p )
3550 LPWSTR token = NULL, t = *p;
3552 if( !t )
3553 return NULL;
3555 while( t && !token )
3557 switch( *t )
3559 case ' ':
3560 t++;
3561 continue;
3562 case '"':
3563 /* unquote the token */
3564 token = ++t;
3565 t = strchrW( token, '"' );
3566 if( t )
3567 *t++ = 0;
3568 break;
3569 case 0:
3570 t = NULL;
3571 break;
3572 default:
3573 token = t;
3574 t = strchrW( token, ' ' );
3575 if( t )
3576 *t++ = 0;
3577 break;
3580 *p = t;
3581 return token;
3584 static BOOL init_xdg(void)
3586 WCHAR shellDesktopPath[MAX_PATH];
3587 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3588 if (SUCCEEDED(hr))
3589 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3590 if (xdg_desktop_dir == NULL)
3592 WINE_ERR("error looking up the desktop directory\n");
3593 return FALSE;
3596 if (getenv("XDG_CONFIG_HOME"))
3597 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3598 else
3599 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3600 if (xdg_config_dir)
3602 create_directories(xdg_config_dir);
3603 if (getenv("XDG_DATA_HOME"))
3604 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3605 else
3606 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3607 if (xdg_data_dir)
3609 char *buffer;
3610 create_directories(xdg_data_dir);
3611 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3612 if (buffer)
3614 mkdir(buffer, 0777);
3615 HeapFree(GetProcessHeap(), 0, buffer);
3617 return TRUE;
3619 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3621 WINE_ERR("out of memory\n");
3622 return FALSE;
3625 static BOOL associations_enabled(void)
3627 BOOL ret = TRUE;
3628 HKEY hkey;
3629 BYTE buf[32];
3630 DWORD len;
3632 if ((hkey = open_associations_reg_key()))
3634 len = sizeof(buf);
3635 if (!RegQueryValueExA(hkey, "Enable", NULL, NULL, buf, &len))
3636 ret = IS_OPTION_TRUE(buf[0]);
3637 RegCloseKey( hkey );
3640 return ret;
3643 /***********************************************************************
3645 * wWinMain
3647 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3649 static const WCHAR dash_aW[] = {'-','a',0};
3650 static const WCHAR dash_rW[] = {'-','r',0};
3651 static const WCHAR dash_tW[] = {'-','t',0};
3652 static const WCHAR dash_uW[] = {'-','u',0};
3653 static const WCHAR dash_wW[] = {'-','w',0};
3655 LPWSTR token = NULL, p;
3656 BOOL bWait = FALSE;
3657 BOOL bURL = FALSE;
3658 HRESULT hr;
3659 int ret = 0;
3661 if (!init_xdg())
3662 return 1;
3664 hr = CoInitialize(NULL);
3665 if (FAILED(hr))
3667 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3668 return 1;
3671 for( p = cmdline; p && *p; )
3673 token = next_token( &p );
3674 if( !token )
3675 break;
3676 if( !strcmpW( token, dash_aW ) )
3678 if (associations_enabled())
3679 RefreshFileTypeAssociations();
3680 continue;
3682 if( !strcmpW( token, dash_rW ) )
3684 cleanup_menus();
3685 continue;
3687 if( !strcmpW( token, dash_wW ) )
3688 bWait = TRUE;
3689 else if ( !strcmpW( token, dash_uW ) )
3690 bURL = TRUE;
3691 else if ( !strcmpW( token, dash_tW ) )
3693 WCHAR *lnkFile = next_token( &p );
3694 if (lnkFile)
3696 WCHAR *outputFile = next_token( &p );
3697 if (outputFile)
3698 thumbnail_lnk(lnkFile, outputFile);
3701 else if( token[0] == '-' )
3703 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3705 else
3707 BOOL bRet;
3709 if (bURL)
3710 bRet = Process_URL( token, bWait );
3711 else
3712 bRet = Process_Link( token, bWait );
3713 if (!bRet)
3715 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3716 ret = 1;
3721 CoUninitialize();
3722 return ret;