qcap/tests: Add media tests for the SmartTee filter.
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blobbc1540bc34d910953ae7ffc8a6f41d511d0d9491
1 /*
2 * Helper program to build unix menu entries
4 * Copyright 1997 Marcus Meissner
5 * Copyright 1998 Juergen Schmied
6 * Copyright 2003 Mike McCormack for CodeWeavers
7 * Copyright 2004 Dmitry Timoshkov
8 * Copyright 2005 Bill Medland
9 * Copyright 2008 Damjan Jovanovic
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 * This program is used to replicate the Windows desktop and start menu
27 * into the native desktop's copies. Desktop entries are merged directly
28 * into the native desktop. The Windows Start Menu corresponds to a Wine
29 * entry within the native "start" menu and replicates the whole tree
30 * structure of the Windows Start Menu. Currently it does not differentiate
31 * between the user's desktop/start menu and the "All Users" copies.
33 * This program will read a Windows shortcut file using the IShellLink
34 * interface, then create a KDE/GNOME menu entry for the shortcut.
36 * winemenubuilder [ -w ] <shortcut.lnk>
38 * If the -w parameter is passed, and the shortcut cannot be created,
39 * this program will wait for the parent process to finish and then try
40 * again. This covers the case when a ShortCut is created before the
41 * executable containing its icon.
43 * TODO
44 * Handle data lnk files. There is no icon in the file; the icon is in
45 * the handler for the file type (or pointed to by the lnk file). Also it
46 * might be better to use a native handler (e.g. a native acroread for pdf
47 * files).
48 * Differentiate between the user's entries and the "All Users" entries.
49 * If it is possible to add the desktop files to the native system's
50 * shared location for an "All Users" entry then do so. As a suggestion the
51 * shared menu Wine base could be writable to the wine group, or a wineadm
52 * group.
53 * Clean up fd.o menu icons and .directory files when the menu is deleted
54 * in Windows.
55 * Associate applications under HKCR\Applications to open any MIME type
56 * (by associating with application/octet-stream, or how?).
57 * Clean up fd.o MIME types when they are deleted in Windows, their icons
58 * too. Very hard - once we associate them with fd.o, we can't tell whether
59 * they are ours or not, and the extension <-> MIME type mapping isn't
60 * one-to-one either.
61 * Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
62 * that write associations there won't associate (#17019).
65 #include "config.h"
66 #include "wine/port.h"
68 #include <ctype.h>
69 #include <stdio.h>
70 #include <string.h>
71 #ifdef HAVE_UNISTD_H
72 #include <unistd.h>
73 #endif
74 #include <errno.h>
75 #include <stdarg.h>
76 #ifdef HAVE_FNMATCH_H
77 #include <fnmatch.h>
78 #endif
80 #define COBJMACROS
81 #define NONAMELESSUNION
83 #include <windows.h>
84 #include <shlobj.h>
85 #include <objidl.h>
86 #include <shlguid.h>
87 #include <appmgmt.h>
88 #include <tlhelp32.h>
89 #include <intshcut.h>
90 #include <shlwapi.h>
91 #include <initguid.h>
92 #include <wincodec.h>
94 #include "wine/unicode.h"
95 #include "wine/debug.h"
96 #include "wine/library.h"
97 #include "wine/list.h"
98 #include "wine/rbtree.h"
100 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
102 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
103 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
104 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
105 (csidl)==CSIDL_COMMON_STARTMENU)
107 /* link file formats */
109 #include "pshpack1.h"
111 typedef struct
113 BYTE bWidth;
114 BYTE bHeight;
115 BYTE bColorCount;
116 BYTE bReserved;
117 WORD wPlanes;
118 WORD wBitCount;
119 DWORD dwBytesInRes;
120 WORD nID;
121 } GRPICONDIRENTRY;
123 typedef struct
125 WORD idReserved;
126 WORD idType;
127 WORD idCount;
128 GRPICONDIRENTRY idEntries[1];
129 } GRPICONDIR;
131 typedef struct
133 BYTE bWidth;
134 BYTE bHeight;
135 BYTE bColorCount;
136 BYTE bReserved;
137 WORD wPlanes;
138 WORD wBitCount;
139 DWORD dwBytesInRes;
140 DWORD dwImageOffset;
141 } ICONDIRENTRY;
143 typedef struct
145 WORD idReserved;
146 WORD idType;
147 WORD idCount;
148 } ICONDIR;
150 typedef struct
152 WORD offset;
153 WORD length;
154 WORD flags;
155 WORD id;
156 WORD handle;
157 WORD usage;
158 } NE_NAMEINFO;
160 typedef struct
162 WORD type_id;
163 WORD count;
164 DWORD resloader;
165 } NE_TYPEINFO;
167 #define NE_RSCTYPE_ICON 0x8003
168 #define NE_RSCTYPE_GROUP_ICON 0x800e
170 #include "poppack.h"
172 typedef struct
174 HRSRC *pResInfo;
175 int nIndex;
176 } ENUMRESSTRUCT;
178 struct xdg_mime_type
180 char *mimeType;
181 char *glob;
182 char *lower_glob;
183 struct list entry;
186 struct rb_string_entry
188 char *string;
189 struct wine_rb_entry entry;
192 DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
194 static char *xdg_config_dir;
195 static char *xdg_data_dir;
196 static char *xdg_desktop_dir;
199 /* Utility routines */
200 static unsigned short crc16(const char* string)
202 unsigned short crc = 0;
203 int i, j, xor_poly;
205 for (i = 0; string[i] != 0; i++)
207 char c = string[i];
208 for (j = 0; j < 8; c >>= 1, j++)
210 xor_poly = (c ^ crc) & 1;
211 crc >>= 1;
212 if (xor_poly)
213 crc ^= 0xa001;
216 return crc;
219 static char *strdupA( const char *str )
221 char *ret;
223 if (!str) return NULL;
224 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
225 return ret;
228 static char* heap_printf(const char *format, ...)
230 va_list args;
231 int size = 4096;
232 char *buffer, *ret;
233 int n;
235 while (1)
237 buffer = HeapAlloc(GetProcessHeap(), 0, size);
238 if (buffer == NULL)
239 break;
240 va_start(args, format);
241 n = vsnprintf(buffer, size, format, args);
242 va_end(args);
243 if (n == -1)
244 size *= 2;
245 else if (n >= size)
246 size = n + 1;
247 else
248 break;
249 HeapFree(GetProcessHeap(), 0, buffer);
252 if (!buffer) return NULL;
253 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
254 if (!ret) ret = buffer;
255 return ret;
258 static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
260 const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);
262 return strcmp((char*)key, t->string);
265 static void *winemenubuilder_rb_alloc(size_t size)
267 return HeapAlloc(GetProcessHeap(), 0, size);
270 static void *winemenubuilder_rb_realloc(void *ptr, size_t size)
272 return HeapReAlloc(GetProcessHeap(), 0, ptr, size);
275 static void winemenubuilder_rb_free(void *ptr)
277 HeapFree(GetProcessHeap(), 0, ptr);
280 static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
282 struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
283 HeapFree(GetProcessHeap(), 0, t->string);
284 HeapFree(GetProcessHeap(), 0, t);
287 static const struct wine_rb_functions winemenubuilder_rb_functions =
289 winemenubuilder_rb_alloc,
290 winemenubuilder_rb_realloc,
291 winemenubuilder_rb_free,
292 winemenubuilder_rb_string_compare,
295 static void write_xml_text(FILE *file, const char *text)
297 int i;
298 for (i = 0; text[i]; i++)
300 if (text[i] == '&')
301 fputs("&amp;", file);
302 else if (text[i] == '<')
303 fputs("&lt;", file);
304 else if (text[i] == '>')
305 fputs("&gt;", file);
306 else if (text[i] == '\'')
307 fputs("&apos;", file);
308 else if (text[i] == '"')
309 fputs("&quot;", file);
310 else
311 fputc(text[i], file);
315 static BOOL create_directories(char *directory)
317 BOOL ret = TRUE;
318 int i;
320 for (i = 0; directory[i]; i++)
322 if (i > 0 && directory[i] == '/')
324 directory[i] = 0;
325 mkdir(directory, 0777);
326 directory[i] = '/';
329 if (mkdir(directory, 0777) && errno != EEXIST)
330 ret = FALSE;
332 return ret;
335 static char* wchars_to_utf8_chars(LPCWSTR string)
337 char *ret;
338 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
339 ret = HeapAlloc(GetProcessHeap(), 0, size);
340 if (ret)
341 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
342 return ret;
345 static char* wchars_to_unix_chars(LPCWSTR string)
347 char *ret;
348 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
349 ret = HeapAlloc(GetProcessHeap(), 0, size);
350 if (ret)
351 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
352 return ret;
355 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
357 WCHAR *ret;
358 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
359 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
360 if (ret)
361 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
362 return ret;
365 /* Icon extraction routines
367 * FIXME: should use PrivateExtractIcons and friends
368 * FIXME: should not use stdio
371 static HRESULT convert_to_native_icon(IStream *icoFile, int *indices, int numIndices,
372 const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
374 WCHAR *dosOutputFileName = NULL;
375 IWICImagingFactory *factory = NULL;
376 IWICBitmapDecoder *decoder = NULL;
377 IWICBitmapEncoder *encoder = NULL;
378 IWICBitmapScaler *scaler = NULL;
379 IStream *outputFile = NULL;
380 int i;
381 HRESULT hr = E_FAIL;
383 dosOutputFileName = wine_get_dos_file_name(outputFileName);
384 if (dosOutputFileName == NULL)
386 WINE_ERR("error converting %s to DOS file name\n", outputFileName);
387 goto end;
389 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
390 &IID_IWICImagingFactory, (void**)&factory);
391 if (FAILED(hr))
393 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
394 goto end;
396 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
397 WICDecodeMetadataCacheOnDemand, &decoder);
398 if (FAILED(hr))
400 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
401 goto end;
403 if (IsEqualCLSID(outputFormat,&CLSID_WICIcnsEncoder))
405 hr = IWICImagingFactory_CreateBitmapScaler(factory, &scaler);
406 if (FAILED(hr))
408 WINE_WARN("error 0x%08X creating IWICBitmapScaler\n", hr);
411 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
412 &IID_IWICBitmapEncoder, (void**)&encoder);
413 if (FAILED(hr))
415 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
416 goto end;
418 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
419 if (FAILED(hr))
421 WINE_ERR("error 0x%08X creating output file %s\n", hr, wine_dbgstr_w(dosOutputFileName));
422 goto end;
424 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, GENERIC_WRITE);
425 if (FAILED(hr))
427 WINE_ERR("error 0x%08X initializing encoder\n", hr);
428 goto end;
431 for (i = 0; i < numIndices; i++)
433 IWICBitmapFrameDecode *sourceFrame = NULL;
434 IWICBitmapSource *sourceBitmap = NULL;
435 IWICBitmapFrameEncode *dstFrame = NULL;
436 IPropertyBag2 *options = NULL;
437 UINT width, height;
439 hr = IWICBitmapDecoder_GetFrame(decoder, indices[i], &sourceFrame);
440 if (FAILED(hr))
442 WINE_ERR("error 0x%08X getting frame %d\n", hr, indices[i]);
443 goto endloop;
445 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
446 if (FAILED(hr))
448 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
449 goto endloop;
451 if ( scaler)
453 IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
454 if (width == 64) /* Classic Mode */
456 hr = IWICBitmapScaler_Initialize( scaler, sourceBitmap, 128, 128,
457 WICBitmapInterpolationModeNearestNeighbor);
458 if (FAILED(hr))
459 WINE_ERR("error 0x%08X scaling bitmap\n", hr);
460 else
462 IWICBitmapSource_Release(sourceBitmap);
463 IWICBitmapScaler_QueryInterface(scaler, &IID_IWICBitmapSource, (LPVOID)&sourceBitmap);
467 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
468 if (FAILED(hr))
470 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
471 goto endloop;
473 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
474 if (FAILED(hr))
476 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
477 goto endloop;
479 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
480 if (FAILED(hr))
482 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
483 goto endloop;
485 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
486 if (FAILED(hr))
488 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
489 goto endloop;
491 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
492 if (FAILED(hr))
494 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
495 goto endloop;
497 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
498 if (FAILED(hr))
500 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
501 goto endloop;
503 hr = IWICBitmapFrameEncode_Commit(dstFrame);
504 if (FAILED(hr))
506 WINE_ERR("error 0x%08X committing frame\n", hr);
507 goto endloop;
509 endloop:
510 if (sourceFrame)
511 IWICBitmapFrameDecode_Release(sourceFrame);
512 if (sourceBitmap)
513 IWICBitmapSource_Release(sourceBitmap);
514 if (dstFrame)
515 IWICBitmapFrameEncode_Release(dstFrame);
516 if (options)
517 IPropertyBag2_Release(options);
520 hr = IWICBitmapEncoder_Commit(encoder);
521 if (FAILED(hr))
523 WINE_ERR("error 0x%08X committing encoder\n", hr);
524 goto end;
527 end:
528 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
529 if (factory)
530 IWICImagingFactory_Release(factory);
531 if (decoder)
532 IWICBitmapDecoder_Release(decoder);
533 if (scaler)
534 IWICBitmapScaler_Release(scaler);
535 if (encoder)
536 IWICBitmapEncoder_Release(encoder);
537 if (outputFile)
538 IStream_Release(outputFile);
539 return hr;
542 struct IconData16 {
543 BYTE *fileBytes;
544 DWORD fileSize;
545 NE_TYPEINFO *iconResources;
546 WORD alignmentShiftCount;
549 static int populate_module16_icons(struct IconData16 *iconData16, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
551 int i, j;
552 int validEntries = 0;
554 for (i = 0; i < grpIconDir->idCount; i++)
556 BYTE *iconPtr = (BYTE*)iconData16->iconResources;
557 NE_NAMEINFO *matchingIcon = NULL;
558 iconPtr += sizeof(NE_TYPEINFO);
559 for (j = 0; j < iconData16->iconResources->count; j++)
561 NE_NAMEINFO *iconInfo = (NE_NAMEINFO*)iconPtr;
562 if ((((BYTE*)iconPtr) + sizeof(NE_NAMEINFO)) > (iconData16->fileBytes + iconData16->fileSize))
564 WINE_WARN("file too small for icon NE_NAMEINFO\n");
565 break;
567 if (iconInfo->id == (0x8000 | grpIconDir->idEntries[i].nID))
569 matchingIcon = iconInfo;
570 break;
572 iconPtr += sizeof(NE_NAMEINFO);
575 if (matchingIcon == NULL)
576 continue;
577 if (((matchingIcon->offset << iconData16->alignmentShiftCount) + grpIconDir->idEntries[i].dwBytesInRes) > iconData16->fileSize)
579 WINE_WARN("file too small for icon contents\n");
580 break;
583 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
584 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
585 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
586 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
587 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
588 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
589 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
590 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
591 validEntries++;
592 memcpy(&icons[*iconOffset], &iconData16->fileBytes[matchingIcon->offset << iconData16->alignmentShiftCount], grpIconDir->idEntries[i].dwBytesInRes);
593 *iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
595 return validEntries;
598 static int populate_module_icons(HMODULE hModule, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
600 int i;
601 int validEntries = 0;
603 for (i = 0; i < grpIconDir->idCount; i++)
605 HRSRC hResInfo;
606 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
607 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
609 HGLOBAL hResData;
610 if ((hResData = LoadResource(hModule, hResInfo)))
612 BITMAPINFO *pIcon;
613 DWORD size = min( grpIconDir->idEntries[i].dwBytesInRes, ((IMAGE_RESOURCE_DATA_ENTRY *)hResInfo)->Size );
614 if ((pIcon = LockResource(hResData)))
616 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
617 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
618 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
619 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
620 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
621 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
622 iconDirEntries[validEntries].dwBytesInRes = size;
623 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
624 validEntries++;
625 memcpy(&icons[*iconOffset], pIcon, size);
626 *iconOffset += size;
628 FreeResource(hResData);
632 return validEntries;
635 static IStream *add_module_icons_to_stream(struct IconData16 *iconData16, HMODULE hModule, GRPICONDIR *grpIconDir)
637 int i;
638 SIZE_T iconsSize = 0;
639 BYTE *icons = NULL;
640 ICONDIRENTRY *iconDirEntries = NULL;
641 IStream *stream = NULL;
642 HRESULT hr = E_FAIL;
643 ULONG bytesWritten;
644 ICONDIR iconDir;
645 SIZE_T iconOffset;
646 int validEntries = 0;
647 LARGE_INTEGER zero;
649 for (i = 0; i < grpIconDir->idCount; i++)
650 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
651 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
652 if (icons == NULL)
654 WINE_ERR("out of memory allocating icon\n");
655 goto end;
658 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
659 if (iconDirEntries == NULL)
661 WINE_ERR("out of memory allocating icon dir entries\n");
662 goto end;
665 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
666 if (FAILED(hr))
668 WINE_ERR("error creating icon stream\n");
669 goto end;
672 iconOffset = 0;
673 if (iconData16)
674 validEntries = populate_module16_icons(iconData16, grpIconDir, iconDirEntries, icons, &iconOffset);
675 else if (hModule)
676 validEntries = populate_module_icons(hModule, grpIconDir, iconDirEntries, icons, &iconOffset);
678 if (validEntries == 0)
680 WINE_ERR("no valid icon entries\n");
681 goto end;
684 iconDir.idReserved = 0;
685 iconDir.idType = 1;
686 iconDir.idCount = validEntries;
687 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
688 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
690 WINE_ERR("error 0x%08X writing icon stream\n", hr);
691 goto end;
693 for (i = 0; i < validEntries; i++)
694 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
695 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
696 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
698 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
699 goto end;
701 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
702 if (FAILED(hr) || bytesWritten != iconOffset)
704 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
705 goto end;
707 zero.QuadPart = 0;
708 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
710 end:
711 HeapFree(GetProcessHeap(), 0, icons);
712 HeapFree(GetProcessHeap(), 0, iconDirEntries);
713 if (FAILED(hr) && stream != NULL)
715 IStream_Release(stream);
716 stream = NULL;
718 return stream;
721 static HRESULT open_module16_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
723 HANDLE hFile = INVALID_HANDLE_VALUE;
724 HANDLE hFileMapping = NULL;
725 DWORD fileSize;
726 BYTE *fileBytes = NULL;
727 IMAGE_DOS_HEADER *dosHeader;
728 IMAGE_OS2_HEADER *neHeader;
729 BYTE *rsrcTab;
730 NE_TYPEINFO *iconGroupResources;
731 NE_TYPEINFO *iconResources;
732 NE_NAMEINFO *iconDirPtr;
733 GRPICONDIR *iconDir;
734 WORD alignmentShiftCount;
735 struct IconData16 iconData16;
736 HRESULT hr = E_FAIL;
738 hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
739 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
740 if (hFile == INVALID_HANDLE_VALUE)
742 WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName), GetLastError());
743 goto end;
746 hFileMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
747 if (hFileMapping == NULL)
749 WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
750 goto end;
753 fileSize = GetFileSize(hFile, NULL);
755 fileBytes = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
756 if (fileBytes == NULL)
758 WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
759 goto end;
762 dosHeader = (IMAGE_DOS_HEADER*)fileBytes;
763 if (sizeof(IMAGE_DOS_HEADER) >= fileSize || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
765 WINE_WARN("file too small for MZ header\n");
766 goto end;
769 neHeader = (IMAGE_OS2_HEADER*)(fileBytes + dosHeader->e_lfanew);
770 if ((((BYTE*)neHeader) + sizeof(IMAGE_OS2_HEADER)) > (fileBytes + fileSize) ||
771 neHeader->ne_magic != IMAGE_OS2_SIGNATURE)
773 WINE_WARN("file too small for NE header\n");
774 goto end;
777 rsrcTab = ((BYTE*)neHeader) + neHeader->ne_rsrctab;
778 if ((rsrcTab + 2) > (fileBytes + fileSize))
780 WINE_WARN("file too small for resource table\n");
781 goto end;
784 alignmentShiftCount = *(WORD*)rsrcTab;
785 rsrcTab += 2;
786 iconGroupResources = NULL;
787 iconResources = NULL;
788 for (;;)
790 NE_TYPEINFO *neTypeInfo = (NE_TYPEINFO*)rsrcTab;
791 if ((rsrcTab + sizeof(NE_TYPEINFO)) > (fileBytes + fileSize))
793 WINE_WARN("file too small for resource table\n");
794 goto end;
796 if (neTypeInfo->type_id == 0)
797 break;
798 else if (neTypeInfo->type_id == NE_RSCTYPE_GROUP_ICON)
799 iconGroupResources = neTypeInfo;
800 else if (neTypeInfo->type_id == NE_RSCTYPE_ICON)
801 iconResources = neTypeInfo;
802 rsrcTab += sizeof(NE_TYPEINFO) + neTypeInfo->count*sizeof(NE_NAMEINFO);
804 if (iconGroupResources == NULL)
806 WINE_WARN("no group icon resource type found\n");
807 goto end;
809 if (iconResources == NULL)
811 WINE_WARN("no icon resource type found\n");
812 goto end;
815 if (nIndex >= iconGroupResources->count)
817 WINE_WARN("icon index out of range\n");
818 goto end;
821 iconDirPtr = (NE_NAMEINFO*)(((BYTE*)iconGroupResources) + sizeof(NE_TYPEINFO) + nIndex*sizeof(NE_NAMEINFO));
822 if ((((BYTE*)iconDirPtr) + sizeof(NE_NAMEINFO)) > (fileBytes + fileSize))
824 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
825 goto end;
827 iconDir = (GRPICONDIR*)(fileBytes + (iconDirPtr->offset << alignmentShiftCount));
828 if ((((BYTE*)iconDir) + sizeof(GRPICONDIR) + iconDir->idCount*sizeof(GRPICONDIRENTRY)) > (fileBytes + fileSize))
830 WINE_WARN("file too small for GRPICONDIR\n");
831 goto end;
834 iconData16.fileBytes = fileBytes;
835 iconData16.fileSize = fileSize;
836 iconData16.iconResources = iconResources;
837 iconData16.alignmentShiftCount = alignmentShiftCount;
838 *ppStream = add_module_icons_to_stream(&iconData16, NULL, iconDir);
839 if (*ppStream)
840 hr = S_OK;
842 end:
843 if (hFile != INVALID_HANDLE_VALUE)
844 CloseHandle(hFile);
845 if (hFileMapping != NULL)
846 CloseHandle(hFileMapping);
847 if (fileBytes != NULL)
848 UnmapViewOfFile(fileBytes);
849 return hr;
852 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
854 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
856 if (!sEnumRes->nIndex--)
858 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
859 return FALSE;
861 else
862 return TRUE;
865 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
867 HMODULE hModule;
868 HRSRC hResInfo;
869 HGLOBAL hResData;
870 GRPICONDIR *pIconDir;
871 ENUMRESSTRUCT sEnumRes;
872 HRESULT hr = E_FAIL;
874 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
875 if (!hModule)
877 if (GetLastError() == ERROR_BAD_EXE_FORMAT)
878 return open_module16_icon(szFileName, nIndex, ppStream);
879 else
881 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
882 wine_dbgstr_w(szFileName), GetLastError());
883 return HRESULT_FROM_WIN32(GetLastError());
887 if (nIndex < 0)
889 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
890 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
891 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
893 else
895 hResInfo=NULL;
896 sEnumRes.pResInfo = &hResInfo;
897 sEnumRes.nIndex = nIndex;
898 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
899 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
900 sEnumRes.nIndex != -1)
902 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
906 if (hResInfo)
908 if ((hResData = LoadResource(hModule, hResInfo)))
910 if ((pIconDir = LockResource(hResData)))
912 *ppStream = add_module_icons_to_stream(0, hModule, pIconDir);
913 if (*ppStream)
914 hr = S_OK;
917 FreeResource(hResData);
920 else
922 WINE_WARN("found no icon\n");
923 FreeLibrary(hModule);
924 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
927 FreeLibrary(hModule);
928 return hr;
931 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
933 ICONDIR iconDir;
934 ULONG bytesRead;
935 HRESULT hr;
937 *ppIconDirEntries = NULL;
939 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
940 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
941 (iconDir.idReserved != 0) || (iconDir.idType != 1))
943 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
944 hr = E_FAIL;
945 goto end;
947 *numEntries = iconDir.idCount;
949 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
951 hr = E_OUTOFMEMORY;
952 goto end;
954 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
955 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
957 if (SUCCEEDED(hr)) hr = E_FAIL;
958 goto end;
961 end:
962 if (FAILED(hr))
963 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
964 return hr;
967 static HRESULT validate_ico(IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
969 HRESULT hr;
971 hr = read_ico_direntries(*ppStream, ppIconDirEntries, numEntries);
972 if (SUCCEEDED(hr))
974 if (*numEntries)
975 return hr;
976 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
977 *ppIconDirEntries = NULL;
979 IStream_Release(*ppStream);
980 *ppStream = NULL;
981 return E_FAIL;
984 static HRESULT write_native_icon(IStream *iconStream, ICONDIRENTRY *pIconDirEntry,
985 int numEntries, const char *icon_name, LPCWSTR szFileName)
987 int nMax = 0, nMaxBits = 0;
988 int nIndex = 0;
989 int i;
990 LARGE_INTEGER position;
991 HRESULT hr;
993 for (i = 0; i < numEntries; i++)
995 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
996 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
997 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
999 nIndex = i;
1000 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
1001 nMaxBits = pIconDirEntry[i].wBitCount;
1004 WINE_TRACE("Selected: %d\n", nIndex);
1006 position.QuadPart = 0;
1007 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
1008 if (FAILED(hr))
1009 goto end;
1010 hr = convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
1012 end:
1013 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
1014 return hr;
1017 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1019 HRESULT hr;
1020 WCHAR *value = NULL;
1021 DWORD size = 0;
1022 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1023 if (SUCCEEDED(hr))
1025 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1026 if (value)
1028 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1029 if (FAILED(hr))
1031 HeapFree(GetProcessHeap(), 0, value);
1032 value = NULL;
1036 return value;
1039 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
1041 static const WCHAR openW[] = {'o','p','e','n',0};
1042 WCHAR *extension;
1043 WCHAR *icon = NULL;
1044 WCHAR *comma;
1045 WCHAR *executable = NULL;
1046 int index = 0;
1047 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
1049 extension = strrchrW(szFileName, '.');
1050 if (extension == NULL)
1051 goto end;
1053 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
1054 if (icon)
1056 comma = strrchrW(icon, ',');
1057 if (comma)
1059 *comma = 0;
1060 index = atoiW(comma + 1);
1062 hr = open_module_icon(icon, index, ppStream);
1064 else
1066 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, openW);
1067 if (executable)
1068 hr = open_module_icon(executable, 0, ppStream);
1071 end:
1072 HeapFree(GetProcessHeap(), 0, icon);
1073 HeapFree(GetProcessHeap(), 0, executable);
1074 return hr;
1077 static HRESULT open_default_icon(IStream **ppStream)
1079 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
1081 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
1084 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
1086 HRESULT hr;
1088 hr = open_module_icon(filename, index, ppStream);
1089 if (FAILED(hr))
1091 if(bWait && hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
1093 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1094 wine_dbgstr_w(filename));
1095 return hr;
1097 else
1099 /* This might be a raw .ico file */
1100 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
1103 if (SUCCEEDED(hr))
1104 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1106 if (FAILED(hr))
1108 hr = open_file_type_icon(filename, ppStream);
1109 if (SUCCEEDED(hr))
1110 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1112 if (FAILED(hr) && !bWait)
1114 hr = open_default_icon(ppStream);
1115 if (SUCCEEDED(hr))
1116 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1118 return hr;
1121 static char* compute_native_identifier(int exeIndex, LPCWSTR icoPathW)
1123 char* nativeIdentifier;
1124 char *icoPathA;
1125 unsigned short crc;
1126 char *basename, *ext;
1128 icoPathA = wchars_to_utf8_chars(icoPathW);
1129 if (icoPathA == NULL)
1130 return NULL;
1132 crc = crc16(icoPathA);
1133 basename = strrchr(icoPathA, '\\');
1134 if (basename == NULL)
1135 basename = icoPathA;
1136 else
1138 *basename = 0;
1139 basename++;
1141 ext = strrchr(basename, '.');
1142 if (ext)
1143 *ext = 0;
1145 nativeIdentifier = heap_printf("%04X_%s.%d", crc, basename, exeIndex);
1146 HeapFree(GetProcessHeap(), 0, icoPathA);
1147 return nativeIdentifier;
1150 #ifdef __APPLE__
1151 #define ICNS_SLOTS 6
1153 static inline int size_to_slot(int size)
1155 switch (size)
1157 case 16: return 0;
1158 case 32: return 1;
1159 case 48: return 2;
1160 case 64: return -2; /* Classic Mode */
1161 case 128: return 3;
1162 case 256: return 4;
1163 case 512: return 5;
1166 return -1;
1169 #define CLASSIC_SLOT 3
1171 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1172 int numEntries, int exeIndex, LPCWSTR icoPathW,
1173 const char *destFilename, char **nativeIdentifier)
1175 struct {
1176 int index;
1177 int maxBits;
1178 BOOL scaled;
1179 } best[ICNS_SLOTS];
1180 int indexes[ICNS_SLOTS];
1181 int i;
1182 const char* tmpdir;
1183 char *icnsPath = NULL;
1184 LARGE_INTEGER zero;
1185 HRESULT hr;
1187 for (i = 0; i < ICNS_SLOTS; i++)
1189 best[i].index = -1;
1190 best[i].maxBits = 0;
1192 for (i = 0; i < numEntries; i++)
1194 int slot;
1195 int width = iconDirEntries[i].bWidth ? iconDirEntries[i].bWidth : 256;
1196 int height = iconDirEntries[i].bHeight ? iconDirEntries[i].bHeight : 256;
1197 BOOL scaled = FALSE;
1199 WINE_TRACE("[%d]: %d x %d @ %d\n", i, width, height, iconDirEntries[i].wBitCount);
1200 if (height != width)
1201 continue;
1202 slot = size_to_slot(width);
1203 if (slot == -2)
1205 scaled = TRUE;
1206 slot = CLASSIC_SLOT;
1208 else if (slot < 0)
1209 continue;
1210 if (scaled && best[slot].maxBits && !best[slot].scaled)
1211 continue; /* don't replace unscaled with scaled */
1212 if (iconDirEntries[i].wBitCount >= best[slot].maxBits || (!scaled && best[slot].scaled))
1214 best[slot].index = i;
1215 best[slot].maxBits = iconDirEntries[i].wBitCount;
1216 best[slot].scaled = scaled;
1219 /* remove the scaled icon if a larger unscaled icon exists */
1220 if (best[CLASSIC_SLOT].scaled)
1222 for (i = CLASSIC_SLOT+1; i < ICNS_SLOTS; i++)
1223 if (best[i].index >= 0 && !best[i].scaled)
1225 best[CLASSIC_SLOT].index = -1;
1226 break;
1230 numEntries = 0;
1231 for (i = 0; i < ICNS_SLOTS; i++)
1233 if (best[i].index >= 0)
1235 indexes[numEntries] = best[i].index;
1236 numEntries++;
1240 if (destFilename)
1241 *nativeIdentifier = heap_printf("%s", destFilename);
1242 else
1243 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1244 if (*nativeIdentifier == NULL)
1246 hr = E_OUTOFMEMORY;
1247 goto end;
1249 if (!(tmpdir = getenv("TMPDIR"))) tmpdir = "/tmp";
1250 icnsPath = heap_printf("%s/%s.icns", tmpdir, *nativeIdentifier);
1251 if (icnsPath == NULL)
1253 hr = E_OUTOFMEMORY;
1254 WINE_WARN("out of memory creating ICNS path\n");
1255 goto end;
1257 zero.QuadPart = 0;
1258 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1259 if (FAILED(hr))
1261 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
1262 goto end;
1264 hr = convert_to_native_icon(icoStream, indexes, numEntries, &CLSID_WICIcnsEncoder,
1265 icnsPath, icoPathW);
1266 if (FAILED(hr))
1268 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
1269 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
1270 goto end;
1273 end:
1274 HeapFree(GetProcessHeap(), 0, icnsPath);
1275 return hr;
1277 #else
1278 static void refresh_icon_cache(const char *iconsDir)
1280 /* The icon theme spec only requires the mtime on the "toplevel"
1281 * directory (whatever that is) to be changed for a refresh,
1282 * but on GNOME you have to create a file in that directory
1283 * instead. Creating a file also works on KDE, Xfce and LXDE.
1285 char *filename = heap_printf("%s/.wine-refresh-XXXXXX", iconsDir);
1286 if (filename != NULL)
1288 int fd = mkstemps(filename, 0);
1289 if (fd >= 0)
1291 close(fd);
1292 unlink(filename);
1294 HeapFree(GetProcessHeap(), 0, filename);
1298 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1299 int numEntries, int exeIndex, LPCWSTR icoPathW,
1300 const char *destFilename, char **nativeIdentifier)
1302 int i;
1303 char *iconsDir = NULL;
1304 HRESULT hr = S_OK;
1305 LARGE_INTEGER zero;
1307 if (destFilename)
1308 *nativeIdentifier = heap_printf("%s", destFilename);
1309 else
1310 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1311 if (*nativeIdentifier == NULL)
1313 hr = E_OUTOFMEMORY;
1314 goto end;
1316 iconsDir = heap_printf("%s/icons/hicolor", xdg_data_dir);
1317 if (iconsDir == NULL)
1319 hr = E_OUTOFMEMORY;
1320 goto end;
1323 for (i = 0; i < numEntries; i++)
1325 int bestIndex = i;
1326 int j;
1327 BOOLEAN duplicate = FALSE;
1328 int w, h;
1329 char *iconDir = NULL;
1330 char *pngPath = NULL;
1332 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
1333 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
1335 for (j = 0; j < i; j++)
1337 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1338 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
1340 duplicate = TRUE;
1341 break;
1344 if (duplicate)
1345 continue;
1346 for (j = i + 1; j < numEntries; j++)
1348 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1349 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1350 iconDirEntries[j].wBitCount >= iconDirEntries[bestIndex].wBitCount)
1352 bestIndex = j;
1355 WINE_TRACE("Selected: %d\n", bestIndex);
1357 w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
1358 h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
1359 iconDir = heap_printf("%s/%dx%d/apps", iconsDir, w, h);
1360 if (iconDir == NULL)
1362 hr = E_OUTOFMEMORY;
1363 goto endloop;
1365 create_directories(iconDir);
1366 pngPath = heap_printf("%s/%s.png", iconDir, *nativeIdentifier);
1367 if (pngPath == NULL)
1369 hr = E_OUTOFMEMORY;
1370 goto endloop;
1372 zero.QuadPart = 0;
1373 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1374 if (FAILED(hr))
1375 goto endloop;
1376 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
1377 pngPath, icoPathW);
1379 endloop:
1380 HeapFree(GetProcessHeap(), 0, iconDir);
1381 HeapFree(GetProcessHeap(), 0, pngPath);
1383 refresh_icon_cache(iconsDir);
1385 end:
1386 HeapFree(GetProcessHeap(), 0, iconsDir);
1387 return hr;
1389 #endif /* defined(__APPLE__) */
1391 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1392 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
1394 IStream *stream = NULL;
1395 ICONDIRENTRY *pIconDirEntries = NULL;
1396 int numEntries;
1397 HRESULT hr;
1398 char *nativeIdentifier = NULL;
1400 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
1402 hr = open_icon(icoPathW, index, bWait, &stream, &pIconDirEntries, &numEntries);
1403 if (FAILED(hr))
1405 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
1406 goto end;
1408 hr = platform_write_icon(stream, pIconDirEntries, numEntries, index, icoPathW, destFilename, &nativeIdentifier);
1409 if (FAILED(hr))
1410 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
1412 end:
1413 if (stream)
1414 IStream_Release(stream);
1415 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
1416 if (FAILED(hr))
1418 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
1419 nativeIdentifier = NULL;
1421 return nativeIdentifier;
1424 static HKEY open_menus_reg_key(void)
1426 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1427 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1428 HKEY assocKey;
1429 DWORD ret;
1430 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1431 if (ret == ERROR_SUCCESS)
1432 return assocKey;
1433 SetLastError(ret);
1434 return NULL;
1437 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1439 WCHAR *unix_fileW;
1440 WCHAR *windows_fileW;
1441 INT size;
1442 DWORD ret;
1444 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1445 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1446 if (unix_fileW)
1448 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1449 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1450 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1451 if (windows_fileW)
1453 HKEY hkey;
1454 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1455 hkey = open_menus_reg_key();
1456 if (hkey)
1458 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1459 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1460 RegCloseKey(hkey);
1462 else
1463 ret = GetLastError();
1464 HeapFree(GetProcessHeap(), 0, windows_fileW);
1466 else
1467 ret = ERROR_NOT_ENOUGH_MEMORY;
1468 HeapFree(GetProcessHeap(), 0, unix_fileW);
1470 else
1471 ret = ERROR_NOT_ENOUGH_MEMORY;
1472 return ret;
1475 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1476 const char *path, const char *args, const char *descr,
1477 const char *workdir, const char *icon)
1479 FILE *file;
1481 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1482 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1483 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1485 file = fopen(location, "w");
1486 if (file == NULL)
1487 return FALSE;
1489 fprintf(file, "[Desktop Entry]\n");
1490 fprintf(file, "Name=%s\n", linkname);
1491 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1492 wine_get_config_dir(), path, args);
1493 fprintf(file, "Type=Application\n");
1494 fprintf(file, "StartupNotify=true\n");
1495 if (descr && lstrlenA(descr))
1496 fprintf(file, "Comment=%s\n", descr);
1497 if (workdir && lstrlenA(workdir))
1498 fprintf(file, "Path=%s\n", workdir);
1499 if (icon && lstrlenA(icon))
1500 fprintf(file, "Icon=%s\n", icon);
1502 fclose(file);
1504 if (unix_link)
1506 DWORD ret = register_menus_entry(location, unix_link);
1507 if (ret != ERROR_SUCCESS)
1508 return FALSE;
1511 return TRUE;
1514 static BOOL write_directory_entry(const char *directory, const char *location)
1516 FILE *file;
1518 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1520 file = fopen(location, "w");
1521 if (file == NULL)
1522 return FALSE;
1524 fprintf(file, "[Desktop Entry]\n");
1525 fprintf(file, "Type=Directory\n");
1526 if (strcmp(directory, "wine") == 0)
1528 fprintf(file, "Name=Wine\n");
1529 fprintf(file, "Icon=wine\n");
1531 else
1533 fprintf(file, "Name=%s\n", directory);
1534 fprintf(file, "Icon=folder\n");
1537 fclose(file);
1538 return TRUE;
1541 static BOOL write_menu_file(const char *unix_link, const char *filename)
1543 char *tempfilename;
1544 FILE *tempfile = NULL;
1545 char *lastEntry;
1546 char *name = NULL;
1547 char *menuPath = NULL;
1548 int i;
1549 int count = 0;
1550 BOOL ret = FALSE;
1552 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1554 while (1)
1556 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1557 if (tempfilename)
1559 int tempfd = mkstemps(tempfilename, 0);
1560 if (tempfd >= 0)
1562 tempfile = fdopen(tempfd, "w");
1563 if (tempfile)
1564 break;
1565 close(tempfd);
1566 goto end;
1568 else if (errno == EEXIST)
1570 HeapFree(GetProcessHeap(), 0, tempfilename);
1571 continue;
1573 HeapFree(GetProcessHeap(), 0, tempfilename);
1575 return FALSE;
1578 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1579 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1580 fprintf(tempfile, "<Menu>\n");
1581 fprintf(tempfile, " <Name>Applications</Name>\n");
1583 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1584 if (name == NULL) goto end;
1585 lastEntry = name;
1586 for (i = 0; filename[i]; i++)
1588 name[i] = filename[i];
1589 if (filename[i] == '/')
1591 char *dir_file_name;
1592 struct stat st;
1593 name[i] = 0;
1594 fprintf(tempfile, " <Menu>\n");
1595 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1596 write_xml_text(tempfile, name);
1597 fprintf(tempfile, "</Name>\n");
1598 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1599 write_xml_text(tempfile, name);
1600 fprintf(tempfile, ".directory</Directory>\n");
1601 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1602 xdg_data_dir, count ? "" : "wine-", name);
1603 if (dir_file_name)
1605 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1606 write_directory_entry(lastEntry, dir_file_name);
1607 HeapFree(GetProcessHeap(), 0, dir_file_name);
1609 name[i] = '-';
1610 lastEntry = &name[i+1];
1611 ++count;
1614 name[i] = 0;
1616 fprintf(tempfile, " <Include>\n");
1617 fprintf(tempfile, " <Filename>");
1618 write_xml_text(tempfile, name);
1619 fprintf(tempfile, "</Filename>\n");
1620 fprintf(tempfile, " </Include>\n");
1621 for (i = 0; i < count; i++)
1622 fprintf(tempfile, " </Menu>\n");
1623 fprintf(tempfile, "</Menu>\n");
1625 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1626 if (menuPath == NULL) goto end;
1627 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1628 ret = TRUE;
1630 end:
1631 if (tempfile)
1632 fclose(tempfile);
1633 if (ret)
1634 ret = (rename(tempfilename, menuPath) == 0);
1635 if (!ret && tempfilename)
1636 remove(tempfilename);
1637 HeapFree(GetProcessHeap(), 0, tempfilename);
1638 if (ret)
1639 register_menus_entry(menuPath, unix_link);
1640 HeapFree(GetProcessHeap(), 0, name);
1641 HeapFree(GetProcessHeap(), 0, menuPath);
1642 return ret;
1645 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1646 const char *descr, const char *workdir, const char *icon)
1648 const char *linkname;
1649 char *desktopPath = NULL;
1650 char *desktopDir;
1651 char *filename = NULL;
1652 BOOL ret = TRUE;
1654 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1655 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1656 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1658 linkname = strrchr(link, '/');
1659 if (linkname == NULL)
1660 linkname = link;
1661 else
1662 ++linkname;
1664 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1665 if (!desktopPath)
1667 WINE_WARN("out of memory creating menu entry\n");
1668 ret = FALSE;
1669 goto end;
1671 desktopDir = strrchr(desktopPath, '/');
1672 *desktopDir = 0;
1673 if (!create_directories(desktopPath))
1675 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1676 ret = FALSE;
1677 goto end;
1679 *desktopDir = '/';
1680 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1682 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1683 ret = FALSE;
1684 goto end;
1687 filename = heap_printf("wine/%s.desktop", link);
1688 if (!filename || !write_menu_file(unix_link, filename))
1690 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1691 ret = FALSE;
1694 end:
1695 HeapFree(GetProcessHeap(), 0, desktopPath);
1696 HeapFree(GetProcessHeap(), 0, filename);
1697 return ret;
1700 /* This escapes reserved characters in .desktop files' Exec keys. */
1701 static LPSTR escape(LPCWSTR arg)
1703 int i, j;
1704 WCHAR *escaped_string;
1705 char *utf8_string;
1707 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1708 if (escaped_string == NULL) return NULL;
1709 for (i = j = 0; arg[i]; i++)
1711 switch (arg[i])
1713 case '\\':
1714 escaped_string[j++] = '\\';
1715 escaped_string[j++] = '\\';
1716 escaped_string[j++] = '\\';
1717 escaped_string[j++] = '\\';
1718 break;
1719 case ' ':
1720 case '\t':
1721 case '\n':
1722 case '"':
1723 case '\'':
1724 case '>':
1725 case '<':
1726 case '~':
1727 case '|':
1728 case '&':
1729 case ';':
1730 case '$':
1731 case '*':
1732 case '?':
1733 case '#':
1734 case '(':
1735 case ')':
1736 case '`':
1737 escaped_string[j++] = '\\';
1738 escaped_string[j++] = '\\';
1739 /* fall through */
1740 default:
1741 escaped_string[j++] = arg[i];
1742 break;
1745 escaped_string[j] = 0;
1747 utf8_string = wchars_to_utf8_chars(escaped_string);
1748 if (utf8_string == NULL)
1750 WINE_ERR("out of memory\n");
1751 goto end;
1754 end:
1755 HeapFree(GetProcessHeap(), 0, escaped_string);
1756 return utf8_string;
1759 /* Return a heap-allocated copy of the unix format difference between the two
1760 * Windows-format paths.
1761 * locn is the owning location
1762 * link is within locn
1764 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1766 char *unix_locn, *unix_link;
1767 char *relative = NULL;
1769 unix_locn = wine_get_unix_file_name(locn);
1770 unix_link = wine_get_unix_file_name(link);
1771 if (unix_locn && unix_link)
1773 size_t len_unix_locn, len_unix_link;
1774 len_unix_locn = strlen (unix_locn);
1775 len_unix_link = strlen (unix_link);
1776 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1778 size_t len_rel;
1779 char *p = strrchr (unix_link + len_unix_locn, '/');
1780 p = strrchr (p, '.');
1781 if (p)
1783 *p = '\0';
1784 len_unix_link = p - unix_link;
1786 len_rel = len_unix_link - len_unix_locn;
1787 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1788 if (relative)
1790 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1794 if (!relative)
1795 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1796 HeapFree(GetProcessHeap(), 0, unix_locn);
1797 HeapFree(GetProcessHeap(), 0, unix_link);
1798 return relative;
1801 /***********************************************************************
1803 * GetLinkLocation
1805 * returns TRUE if successful
1806 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1807 * *relative will contain the address of a heap-allocated copy of the portion
1808 * of the filename that is within the specified location, in unix form
1810 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1812 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1813 DWORD len, i, r, filelen;
1814 const DWORD locations[] = {
1815 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1816 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1817 CSIDL_COMMON_STARTMENU };
1819 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1820 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1821 if (filelen==0 || filelen>MAX_PATH)
1822 return FALSE;
1824 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1826 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1827 * expand or our hardcoded list won't match.
1829 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1830 if (filelen==0 || filelen>MAX_PATH)
1831 return FALSE;
1833 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1835 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1837 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1838 continue;
1840 len = lstrlenW(buffer);
1841 if (len >= MAX_PATH)
1842 continue; /* We've just trashed memory! Hopefully we are OK */
1844 if (len > filelen || filename[len]!='\\')
1845 continue;
1846 /* do a lstrcmpinW */
1847 filename[len] = 0;
1848 r = lstrcmpiW( filename, buffer );
1849 filename[len] = '\\';
1850 if ( r )
1851 continue;
1853 /* return the remainder of the string and link type */
1854 *loc = locations[i];
1855 *relative = relative_path (filename, buffer);
1856 return (*relative != NULL);
1859 return FALSE;
1862 /* gets the target path directly or through MSI */
1863 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1864 LPWSTR szArgs, DWORD argsSize)
1866 IShellLinkDataList *dl = NULL;
1867 EXP_DARWIN_LINK *dar = NULL;
1868 HRESULT hr;
1870 szPath[0] = 0;
1871 szArgs[0] = 0;
1873 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1874 if (hr == S_OK && szPath[0])
1876 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1877 return hr;
1880 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1881 if (FAILED(hr))
1882 return hr;
1884 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1885 if (SUCCEEDED(hr))
1887 WCHAR* szCmdline;
1888 DWORD cmdSize;
1890 cmdSize=0;
1891 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1892 if (hr == ERROR_SUCCESS)
1894 cmdSize++;
1895 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1896 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1897 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1898 if (hr == ERROR_SUCCESS)
1900 WCHAR *s, *d;
1901 int bcount = 0;
1902 BOOL in_quotes = FALSE;
1904 /* Extract the application path */
1905 s=szCmdline;
1906 d=szPath;
1907 while (*s)
1909 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1911 /* skip the remaining spaces */
1912 do {
1913 s++;
1914 } while (*s==0x0009 || *s==0x0020);
1915 break;
1917 else if (*s==0x005c)
1919 /* '\\' */
1920 *d++=*s++;
1921 bcount++;
1923 else if (*s==0x0022)
1925 /* '"' */
1926 if ((bcount & 1)==0)
1928 /* Preceded by an even number of '\', this is
1929 * half that number of '\', plus a quote which
1930 * we erase.
1932 d-=bcount/2;
1933 in_quotes=!in_quotes;
1934 s++;
1936 else
1938 /* Preceded by an odd number of '\', this is
1939 * half that number of '\' followed by a '"'
1941 d=d-bcount/2-1;
1942 *d++='"';
1943 s++;
1945 bcount=0;
1947 else
1949 /* a regular character */
1950 *d++=*s++;
1951 bcount=0;
1953 if ((d-szPath) == pathSize)
1955 /* Keep processing the path till we get to the
1956 * arguments, but 'stand still'
1958 d--;
1961 /* Close the application path */
1962 *d=0;
1964 lstrcpynW(szArgs, s, argsSize);
1966 HeapFree( GetProcessHeap(), 0, szCmdline );
1968 LocalFree( dar );
1971 IShellLinkDataList_Release( dl );
1972 return hr;
1975 static char *slashes_to_minuses(const char *string)
1977 int i;
1978 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1979 if (ret)
1981 for (i = 0; string[i]; i++)
1983 if (string[i] == '/')
1984 ret[i] = '-';
1985 else
1986 ret[i] = string[i];
1988 ret[i] = 0;
1989 return ret;
1991 return NULL;
1994 static BOOL next_line(FILE *file, char **line, int *size)
1996 int pos = 0;
1997 char *cr;
1998 if (*line == NULL)
2000 *size = 4096;
2001 *line = HeapAlloc(GetProcessHeap(), 0, *size);
2003 while (*line != NULL)
2005 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
2007 HeapFree(GetProcessHeap(), 0, *line);
2008 *line = NULL;
2009 if (feof(file))
2010 return TRUE;
2011 return FALSE;
2013 pos = strlen(*line);
2014 cr = strchr(*line, '\n');
2015 if (cr == NULL)
2017 char *line2;
2018 (*size) *= 2;
2019 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
2020 if (line2)
2021 *line = line2;
2022 else
2024 HeapFree(GetProcessHeap(), 0, *line);
2025 *line = NULL;
2028 else
2030 *cr = 0;
2031 return TRUE;
2034 return FALSE;
2037 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
2039 char *globs_filename = NULL;
2040 BOOL ret = TRUE;
2041 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
2042 if (globs_filename)
2044 FILE *globs_file = fopen(globs_filename, "r");
2045 if (globs_file) /* doesn't have to exist */
2047 char *line = NULL;
2048 int size = 0;
2049 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
2051 char *pos;
2052 struct xdg_mime_type *mime_type_entry = NULL;
2053 if (line[0] != '#' && (pos = strchr(line, ':')))
2055 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
2056 if (mime_type_entry)
2058 *pos = 0;
2059 mime_type_entry->mimeType = strdupA(line);
2060 mime_type_entry->glob = strdupA(pos + 1);
2061 mime_type_entry->lower_glob = strdupA(pos + 1);
2062 if (mime_type_entry->lower_glob)
2064 char *l;
2065 for (l = mime_type_entry->lower_glob; *l; l++)
2066 *l = tolower(*l);
2068 if (mime_type_entry->mimeType && mime_type_entry->glob && mime_type_entry->lower_glob)
2069 list_add_tail(mime_types, &mime_type_entry->entry);
2070 else
2072 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2073 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2074 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2075 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2076 ret = FALSE;
2079 else
2080 ret = FALSE;
2083 HeapFree(GetProcessHeap(), 0, line);
2084 fclose(globs_file);
2086 HeapFree(GetProcessHeap(), 0, globs_filename);
2088 else
2089 ret = FALSE;
2090 return ret;
2093 static void free_native_mime_types(struct list *native_mime_types)
2095 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
2097 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
2099 list_remove(&mime_type_entry->entry);
2100 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2101 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2102 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2103 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2105 HeapFree(GetProcessHeap(), 0, native_mime_types);
2108 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
2110 char *xdg_data_dirs;
2111 BOOL ret;
2113 *mime_types = NULL;
2115 xdg_data_dirs = getenv("XDG_DATA_DIRS");
2116 if (xdg_data_dirs == NULL)
2117 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
2118 else
2119 xdg_data_dirs = strdupA(xdg_data_dirs);
2121 if (xdg_data_dirs)
2123 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
2124 if (*mime_types)
2126 const char *begin;
2127 char *end;
2129 list_init(*mime_types);
2130 ret = add_mimes(xdg_data_home, *mime_types);
2131 if (ret)
2133 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
2135 *end = '\0';
2136 ret = add_mimes(begin, *mime_types);
2137 *end = ':';
2138 if (!ret)
2139 break;
2141 if (ret)
2142 ret = add_mimes(begin, *mime_types);
2145 else
2146 ret = FALSE;
2147 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
2149 else
2150 ret = FALSE;
2151 if (!ret && *mime_types)
2153 free_native_mime_types(*mime_types);
2154 *mime_types = NULL;
2156 return ret;
2159 static BOOL match_glob(struct list *native_mime_types, const char *extension,
2160 int ignoreGlobCase, char **match)
2162 #ifdef HAVE_FNMATCH
2163 struct xdg_mime_type *mime_type_entry;
2164 int matchLength = 0;
2166 *match = NULL;
2168 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
2170 const char *glob = ignoreGlobCase ? mime_type_entry->lower_glob : mime_type_entry->glob;
2171 if (fnmatch(glob, extension, 0) == 0)
2173 if (*match == NULL || matchLength < strlen(glob))
2175 *match = mime_type_entry->mimeType;
2176 matchLength = strlen(glob);
2181 if (*match != NULL)
2183 *match = strdupA(*match);
2184 if (*match == NULL)
2185 return FALSE;
2187 #else
2188 *match = NULL;
2189 #endif
2190 return TRUE;
2193 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
2194 const char *extensionA,
2195 LPCWSTR extensionW,
2196 char **mime_type)
2198 WCHAR *lower_extensionW;
2199 INT len;
2200 BOOL ret = match_glob(native_mime_types, extensionA, 0, mime_type);
2201 if (ret == FALSE || *mime_type != NULL)
2202 return ret;
2203 len = strlenW(extensionW);
2204 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
2205 if (lower_extensionW)
2207 char *lower_extensionA;
2208 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
2209 strlwrW(lower_extensionW);
2210 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
2211 if (lower_extensionA)
2213 ret = match_glob(native_mime_types, lower_extensionA, 1, mime_type);
2214 HeapFree(GetProcessHeap(), 0, lower_extensionA);
2216 else
2218 ret = FALSE;
2219 WINE_FIXME("out of memory\n");
2221 HeapFree(GetProcessHeap(), 0, lower_extensionW);
2223 else
2225 ret = FALSE;
2226 WINE_FIXME("out of memory\n");
2228 return ret;
2231 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
2233 DWORD size;
2234 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
2236 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
2237 if (ret)
2239 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
2240 return ret;
2242 HeapFree(GetProcessHeap(), 0, ret);
2244 return NULL;
2247 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
2249 WCHAR *valW = reg_get_valW(key, subkey, name);
2250 if (valW)
2252 char *val = wchars_to_utf8_chars(valW);
2253 HeapFree(GetProcessHeap(), 0, valW);
2254 return val;
2256 return NULL;
2259 static HKEY open_associations_reg_key(void)
2261 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
2262 '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};
2263 HKEY assocKey;
2264 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
2265 return assocKey;
2266 return NULL;
2269 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
2270 LPCSTR appName, LPCSTR openWithIcon)
2272 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2273 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2274 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2275 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2276 HKEY assocKey;
2277 BOOL ret;
2279 if ((assocKey = open_associations_reg_key()))
2281 CHAR *valueA;
2282 WCHAR *value;
2284 ret = FALSE;
2286 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
2287 if (!valueA || lstrcmpA(valueA, mimeType))
2288 ret = TRUE;
2289 HeapFree(GetProcessHeap(), 0, valueA);
2291 value = reg_get_valW(assocKey, extensionW, ProgIDW);
2292 if (!value || strcmpW(value, progId))
2293 ret = TRUE;
2294 HeapFree(GetProcessHeap(), 0, value);
2296 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2297 if (!valueA || lstrcmpA(valueA, appName))
2298 ret = TRUE;
2299 HeapFree(GetProcessHeap(), 0, valueA);
2301 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
2302 if ((openWithIcon && !valueA) ||
2303 (!openWithIcon && valueA) ||
2304 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
2305 ret = TRUE;
2306 HeapFree(GetProcessHeap(), 0, valueA);
2308 RegCloseKey(assocKey);
2310 else
2312 WINE_ERR("error opening associations registry key\n");
2313 ret = FALSE;
2315 return ret;
2318 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2319 LPCSTR appName, LPCSTR desktopFile, LPCSTR openWithIcon)
2321 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2322 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2323 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2324 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2325 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2326 HKEY assocKey = NULL;
2327 HKEY subkey = NULL;
2328 WCHAR *mimeTypeW = NULL;
2329 WCHAR *appNameW = NULL;
2330 WCHAR *desktopFileW = NULL;
2331 WCHAR *openWithIconW = NULL;
2333 assocKey = open_associations_reg_key();
2334 if (assocKey == NULL)
2336 WINE_ERR("could not open file associations key\n");
2337 goto done;
2340 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2342 WINE_ERR("could not create extension subkey\n");
2343 goto done;
2346 mimeTypeW = utf8_chars_to_wchars(mimeType);
2347 if (mimeTypeW == NULL)
2349 WINE_ERR("out of memory\n");
2350 goto done;
2353 appNameW = utf8_chars_to_wchars(appName);
2354 if (appNameW == NULL)
2356 WINE_ERR("out of memory\n");
2357 goto done;
2360 desktopFileW = utf8_chars_to_wchars(desktopFile);
2361 if (desktopFileW == NULL)
2363 WINE_ERR("out of memory\n");
2364 goto done;
2367 if (openWithIcon)
2369 openWithIconW = utf8_chars_to_wchars(openWithIcon);
2370 if (openWithIconW == NULL)
2372 WINE_ERR("out of memory\n");
2373 goto done;
2377 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2378 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2379 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2380 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2381 if (openWithIcon)
2382 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
2383 else
2384 RegDeleteValueW(subkey, OpenWithIconW);
2386 done:
2387 RegCloseKey(assocKey);
2388 RegCloseKey(subkey);
2389 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2390 HeapFree(GetProcessHeap(), 0, appNameW);
2391 HeapFree(GetProcessHeap(), 0, desktopFileW);
2392 HeapFree(GetProcessHeap(), 0, openWithIconW);
2395 static BOOL cleanup_associations(void)
2397 static const WCHAR openW[] = {'o','p','e','n',0};
2398 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2399 HKEY assocKey;
2400 BOOL hasChanged = FALSE;
2401 if ((assocKey = open_associations_reg_key()))
2403 int i;
2404 BOOL done = FALSE;
2405 for (i = 0; !done;)
2407 WCHAR *extensionW = NULL;
2408 DWORD size = 1024;
2409 LSTATUS ret;
2413 HeapFree(GetProcessHeap(), 0, extensionW);
2414 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2415 if (extensionW == NULL)
2417 WINE_ERR("out of memory\n");
2418 ret = ERROR_OUTOFMEMORY;
2419 break;
2421 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2422 size *= 2;
2423 } while (ret == ERROR_MORE_DATA);
2425 if (ret == ERROR_SUCCESS)
2427 WCHAR *command;
2428 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2429 if (command == NULL)
2431 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2432 if (desktopFile)
2434 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2435 remove(desktopFile);
2437 RegDeleteKeyW(assocKey, extensionW);
2438 hasChanged = TRUE;
2439 HeapFree(GetProcessHeap(), 0, desktopFile);
2441 else
2442 i++;
2443 HeapFree(GetProcessHeap(), 0, command);
2445 else
2447 if (ret != ERROR_NO_MORE_ITEMS)
2448 WINE_ERR("error %d while reading registry\n", ret);
2449 done = TRUE;
2451 HeapFree(GetProcessHeap(), 0, extensionW);
2453 RegCloseKey(assocKey);
2455 else
2456 WINE_ERR("could not open file associations key\n");
2457 return hasChanged;
2460 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2461 const char *mime_type, const char *comment)
2463 BOOL ret = FALSE;
2464 char *filename;
2466 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2467 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2469 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2470 if (filename)
2472 FILE *packageFile = fopen(filename, "w");
2473 if (packageFile)
2475 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2476 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2477 fprintf(packageFile, " <mime-type type=\"");
2478 write_xml_text(packageFile, mime_type);
2479 fprintf(packageFile, "\">\n");
2480 fprintf(packageFile, " <glob pattern=\"*");
2481 write_xml_text(packageFile, dot_extension);
2482 fprintf(packageFile, "\"/>\n");
2483 if (comment)
2485 fprintf(packageFile, " <comment>");
2486 write_xml_text(packageFile, comment);
2487 fprintf(packageFile, "</comment>\n");
2489 fprintf(packageFile, " </mime-type>\n");
2490 fprintf(packageFile, "</mime-info>\n");
2491 ret = TRUE;
2492 fclose(packageFile);
2494 else
2495 WINE_ERR("error writing file %s\n", filename);
2496 HeapFree(GetProcessHeap(), 0, filename);
2498 else
2499 WINE_ERR("out of memory\n");
2500 return ret;
2503 static BOOL is_extension_blacklisted(LPCWSTR extension)
2505 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2506 static const WCHAR comW[] = {'.','c','o','m',0};
2507 static const WCHAR exeW[] = {'.','e','x','e',0};
2508 static const WCHAR msiW[] = {'.','m','s','i',0};
2510 if (!strcmpiW(extension, comW) ||
2511 !strcmpiW(extension, exeW) ||
2512 !strcmpiW(extension, msiW))
2513 return TRUE;
2514 return FALSE;
2517 static const char* get_special_mime_type(LPCWSTR extension)
2519 static const WCHAR lnkW[] = {'.','l','n','k',0};
2520 if (!strcmpiW(extension, lnkW))
2521 return "application/x-ms-shortcut";
2522 return NULL;
2525 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2526 const char *friendlyAppName, const char *mimeType,
2527 const char *progId, const char *openWithIcon)
2529 BOOL ret = FALSE;
2530 FILE *desktop;
2532 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2533 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2534 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2536 desktop = fopen(desktopPath, "w");
2537 if (desktop)
2539 fprintf(desktop, "[Desktop Entry]\n");
2540 fprintf(desktop, "Type=Application\n");
2541 fprintf(desktop, "Name=%s\n", friendlyAppName);
2542 fprintf(desktop, "MimeType=%s;\n", mimeType);
2543 fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId);
2544 fprintf(desktop, "NoDisplay=true\n");
2545 fprintf(desktop, "StartupNotify=true\n");
2546 if (openWithIcon)
2547 fprintf(desktop, "Icon=%s\n", openWithIcon);
2548 ret = TRUE;
2549 fclose(desktop);
2551 else
2552 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2553 return ret;
2556 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2558 static const WCHAR openW[] = {'o','p','e','n',0};
2559 struct wine_rb_tree mimeProgidTree;
2560 struct list *nativeMimeTypes = NULL;
2561 LSTATUS ret = 0;
2562 int i;
2563 BOOL hasChanged = FALSE;
2565 if (wine_rb_init(&mimeProgidTree, &winemenubuilder_rb_functions))
2567 WINE_ERR("wine_rb_init failed\n");
2568 return FALSE;
2570 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2572 WINE_ERR("could not build native MIME types\n");
2573 return FALSE;
2576 for (i = 0; ; i++)
2578 WCHAR *extensionW = NULL;
2579 DWORD size = 1024;
2583 HeapFree(GetProcessHeap(), 0, extensionW);
2584 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2585 if (extensionW == NULL)
2587 WINE_ERR("out of memory\n");
2588 ret = ERROR_OUTOFMEMORY;
2589 break;
2591 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2592 size *= 2;
2593 } while (ret == ERROR_MORE_DATA);
2595 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2597 char *extensionA = NULL;
2598 WCHAR *commandW = NULL;
2599 WCHAR *executableW = NULL;
2600 char *openWithIconA = NULL;
2601 WCHAR *friendlyDocNameW = NULL;
2602 char *friendlyDocNameA = NULL;
2603 WCHAR *iconW = NULL;
2604 char *iconA = NULL;
2605 WCHAR *contentTypeW = NULL;
2606 char *mimeTypeA = NULL;
2607 WCHAR *friendlyAppNameW = NULL;
2608 char *friendlyAppNameA = NULL;
2609 WCHAR *progIdW = NULL;
2610 char *progIdA = NULL;
2611 char *mimeProgId = NULL;
2613 extensionA = wchars_to_utf8_chars(strlwrW(extensionW));
2614 if (extensionA == NULL)
2616 WINE_ERR("out of memory\n");
2617 goto end;
2620 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2621 if (friendlyDocNameW)
2623 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2624 if (friendlyDocNameA == NULL)
2626 WINE_ERR("out of memory\n");
2627 goto end;
2631 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2633 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2634 if (contentTypeW)
2635 strlwrW(contentTypeW);
2637 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2638 goto end;
2640 if (mimeTypeA == NULL)
2642 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2643 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2644 else if ((get_special_mime_type(extensionW)))
2645 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2646 else
2647 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2649 if (mimeTypeA != NULL)
2651 /* GNOME seems to ignore the <icon> tag in MIME packages,
2652 * and the default name is more intuitive anyway.
2654 if (iconW)
2656 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2657 if (flattened_mime)
2659 int index = 0;
2660 WCHAR *comma = strrchrW(iconW, ',');
2661 if (comma)
2663 *comma = 0;
2664 index = atoiW(comma + 1);
2666 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2667 HeapFree(GetProcessHeap(), 0, flattened_mime);
2671 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2672 hasChanged = TRUE;
2674 else
2676 WINE_FIXME("out of memory\n");
2677 goto end;
2681 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2682 if (commandW == NULL)
2683 /* no command => no application is associated */
2684 goto end;
2686 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2687 if (executableW)
2688 openWithIconA = extract_icon(executableW, 0, NULL, FALSE);
2690 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, openW);
2691 if (friendlyAppNameW)
2693 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2694 if (friendlyAppNameA == NULL)
2696 WINE_ERR("out of memory\n");
2697 goto end;
2700 else
2702 friendlyAppNameA = heap_printf("A Wine application");
2703 if (friendlyAppNameA == NULL)
2705 WINE_ERR("out of memory\n");
2706 goto end;
2710 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2711 if (progIdW)
2713 progIdA = escape(progIdW);
2714 if (progIdA == NULL)
2716 WINE_ERR("out of memory\n");
2717 goto end;
2720 else
2721 goto end; /* no progID => not a file type association */
2723 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2724 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2725 if (mimeProgId)
2727 struct rb_string_entry *entry;
2728 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2730 HeapFree(GetProcessHeap(), 0, mimeProgId);
2731 goto end;
2733 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2734 if (!entry)
2736 WINE_ERR("out of memory allocating rb_string_entry\n");
2737 goto end;
2739 entry->string = mimeProgId;
2740 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2742 WINE_ERR("error updating rb tree\n");
2743 goto end;
2747 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, openWithIconA))
2749 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2750 if (desktopPath)
2752 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2754 hasChanged = TRUE;
2755 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, desktopPath, openWithIconA);
2757 HeapFree(GetProcessHeap(), 0, desktopPath);
2761 end:
2762 HeapFree(GetProcessHeap(), 0, extensionA);
2763 HeapFree(GetProcessHeap(), 0, commandW);
2764 HeapFree(GetProcessHeap(), 0, executableW);
2765 HeapFree(GetProcessHeap(), 0, openWithIconA);
2766 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2767 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2768 HeapFree(GetProcessHeap(), 0, iconW);
2769 HeapFree(GetProcessHeap(), 0, iconA);
2770 HeapFree(GetProcessHeap(), 0, contentTypeW);
2771 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2772 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2773 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2774 HeapFree(GetProcessHeap(), 0, progIdW);
2775 HeapFree(GetProcessHeap(), 0, progIdA);
2777 HeapFree(GetProcessHeap(), 0, extensionW);
2778 if (ret != ERROR_SUCCESS)
2779 break;
2782 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2783 free_native_mime_types(nativeMimeTypes);
2784 return hasChanged;
2787 static char *get_start_exe_path(void)
2789 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2790 '\\','s','t','a','r','t','.','e','x','e',0};
2791 WCHAR start_path[MAX_PATH];
2792 GetWindowsDirectoryW(start_path, MAX_PATH);
2793 lstrcatW(start_path, startW);
2794 return escape(start_path);
2797 static char* escape_unix_link_arg(LPCSTR unix_link)
2799 char *ret = NULL;
2800 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2801 if (unix_linkW)
2803 char *escaped_lnk = escape(unix_linkW);
2804 if (escaped_lnk)
2806 ret = heap_printf("/Unix %s", escaped_lnk);
2807 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2809 HeapFree(GetProcessHeap(), 0, unix_linkW);
2811 return ret;
2814 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2816 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2817 '\\','s','t','a','r','t','.','e','x','e',0};
2818 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2819 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2820 WCHAR szTmp[INFOTIPSIZE];
2821 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2822 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2823 int iIconId = 0, r = -1;
2824 DWORD csidl = -1;
2825 HANDLE hsem = NULL;
2826 char *unix_link = NULL;
2827 char *start_path = NULL;
2829 if ( !link )
2831 WINE_ERR("Link name is null\n");
2832 return FALSE;
2835 if( !GetLinkLocation( link, &csidl, &link_name ) )
2837 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2838 return TRUE;
2840 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2842 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2843 return TRUE;
2845 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2847 szTmp[0] = 0;
2848 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2849 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2850 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2852 szTmp[0] = 0;
2853 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2854 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2855 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2857 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2858 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2859 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2860 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2862 szTmp[0] = 0;
2863 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2864 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2865 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2867 if( !szPath[0] )
2869 LPITEMIDLIST pidl = NULL;
2870 IShellLinkW_GetIDList( sl, &pidl );
2871 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2872 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2875 /* extract the icon */
2876 if( szIconPath[0] )
2877 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2878 else
2879 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2881 /* fail - try once again after parent process exit */
2882 if( !icon_name )
2884 if (bWait)
2886 WINE_WARN("Unable to extract icon, deferring.\n");
2887 goto cleanup;
2889 WINE_ERR("failed to extract icon from %s\n",
2890 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2893 unix_link = wine_get_unix_file_name(link);
2894 if (unix_link == NULL)
2896 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2897 goto cleanup;
2900 /* check the path */
2901 if( szPath[0] )
2903 static const WCHAR exeW[] = {'.','e','x','e',0};
2904 WCHAR *p;
2906 /* check for .exe extension */
2907 if (!(p = strrchrW( szPath, '.' )) ||
2908 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2909 lstrcmpiW( p, exeW ))
2911 /* Not .exe - use 'start.exe' to launch this file */
2912 p = szArgs + lstrlenW(szPath) + 2;
2913 if (szArgs[0])
2915 p[0] = ' ';
2916 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2917 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2919 else
2920 p[0] = 0;
2922 szArgs[0] = '"';
2923 lstrcpyW(szArgs + 1, szPath);
2924 p[-1] = '"';
2926 GetWindowsDirectoryW(szPath, MAX_PATH);
2927 lstrcatW(szPath, startW);
2930 /* convert app working dir */
2931 if (szWorkDir[0])
2932 work_dir = wine_get_unix_file_name( szWorkDir );
2934 else
2936 /* if there's no path... try run the link itself */
2937 lstrcpynW(szArgs, link, MAX_PATH);
2938 GetWindowsDirectoryW(szPath, MAX_PATH);
2939 lstrcatW(szPath, startW);
2942 /* escape the path and parameters */
2943 escaped_path = escape(szPath);
2944 escaped_args = escape(szArgs);
2945 description = wchars_to_utf8_chars(szDescription);
2946 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2948 WINE_ERR("out of memory allocating/escaping parameters\n");
2949 goto cleanup;
2952 start_path = get_start_exe_path();
2953 if (start_path == NULL)
2955 WINE_ERR("out of memory\n");
2956 goto cleanup;
2959 /* building multiple menus concurrently has race conditions */
2960 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2961 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2963 WINE_ERR("failed wait for semaphore\n");
2964 goto cleanup;
2967 if (in_desktop_dir(csidl))
2969 char *location;
2970 const char *lastEntry;
2971 lastEntry = strrchr(link_name, '/');
2972 if (lastEntry == NULL)
2973 lastEntry = link_name;
2974 else
2975 ++lastEntry;
2976 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2977 if (location)
2979 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2981 char *link_arg = escape_unix_link_arg(unix_link);
2982 if (link_arg)
2984 r = !write_desktop_entry(unix_link, location, lastEntry,
2985 start_path, link_arg, description, work_dir, icon_name);
2986 HeapFree(GetProcessHeap(), 0, link_arg);
2989 else
2990 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2991 if (r == 0)
2992 chmod(location, 0755);
2993 HeapFree(GetProcessHeap(), 0, location);
2996 else
2998 char *link_arg = escape_unix_link_arg(unix_link);
2999 if (link_arg)
3001 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name);
3002 HeapFree(GetProcessHeap(), 0, link_arg);
3006 ReleaseSemaphore( hsem, 1, NULL );
3008 cleanup:
3009 if (hsem) CloseHandle( hsem );
3010 HeapFree( GetProcessHeap(), 0, icon_name );
3011 HeapFree( GetProcessHeap(), 0, work_dir );
3012 HeapFree( GetProcessHeap(), 0, link_name );
3013 HeapFree( GetProcessHeap(), 0, escaped_args );
3014 HeapFree( GetProcessHeap(), 0, escaped_path );
3015 HeapFree( GetProcessHeap(), 0, description );
3016 HeapFree( GetProcessHeap(), 0, unix_link );
3017 HeapFree( GetProcessHeap(), 0, start_path );
3019 if (r && !bWait)
3020 WINE_ERR("failed to build the menu\n" );
3022 return ( r == 0 );
3025 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
3027 char *link_name = NULL, *icon_name = NULL;
3028 DWORD csidl = -1;
3029 LPWSTR urlPath = NULL;
3030 char *escaped_urlPath = NULL;
3031 HRESULT hr;
3032 HANDLE hSem = NULL;
3033 BOOL ret = TRUE;
3034 int r = -1;
3035 char *unix_link = NULL;
3036 IPropertySetStorage *pPropSetStg;
3037 IPropertyStorage *pPropStg;
3038 PROPSPEC ps[2];
3039 PROPVARIANT pv[2];
3040 char *start_path = NULL;
3041 BOOL has_icon = FALSE;
3043 if ( !link )
3045 WINE_ERR("Link name is null\n");
3046 return TRUE;
3049 if( !GetLinkLocation( link, &csidl, &link_name ) )
3051 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
3052 return TRUE;
3054 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
3056 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3057 ret = TRUE;
3058 goto cleanup;
3060 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
3062 hr = url->lpVtbl->GetURL(url, &urlPath);
3063 if (FAILED(hr))
3065 ret = TRUE;
3066 goto cleanup;
3068 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
3070 unix_link = wine_get_unix_file_name(link);
3071 if (unix_link == NULL)
3073 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
3074 goto cleanup;
3077 escaped_urlPath = escape(urlPath);
3078 if (escaped_urlPath == NULL)
3080 WINE_ERR("couldn't escape url, out of memory\n");
3081 goto cleanup;
3084 start_path = get_start_exe_path();
3085 if (start_path == NULL)
3087 WINE_ERR("out of memory\n");
3088 goto cleanup;
3091 ps[0].ulKind = PRSPEC_PROPID;
3092 ps[0].u.propid = PID_IS_ICONFILE;
3093 ps[1].ulKind = PRSPEC_PROPID;
3094 ps[1].u.propid = PID_IS_ICONINDEX;
3096 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
3097 if (SUCCEEDED(hr))
3099 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
3100 if (SUCCEEDED(hr))
3102 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
3103 if (SUCCEEDED(hr))
3105 if (pv[0].vt == VT_LPWSTR && pv[0].u.pwszVal && pv[0].u.pwszVal[0])
3107 has_icon = TRUE;
3108 icon_name = extract_icon( pv[0].u.pwszVal, pv[1].u.iVal, NULL, bWait );
3110 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);
3112 PropVariantClear(&pv[0]);
3113 PropVariantClear(&pv[1]);
3115 IPropertyStorage_Release(pPropStg);
3117 IPropertySetStorage_Release(pPropSetStg);
3120 /* fail - try once again after parent process exit */
3121 if( has_icon && !icon_name )
3123 if (bWait)
3125 WINE_WARN("Unable to extract icon, deferring.\n");
3126 ret = FALSE;
3127 goto cleanup;
3129 WINE_ERR("failed to extract icon from %s\n",
3130 wine_dbgstr_w( pv[0].u.pwszVal ));
3133 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3134 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3136 WINE_ERR("failed wait for semaphore\n");
3137 goto cleanup;
3139 if (in_desktop_dir(csidl))
3141 char *location;
3142 const char *lastEntry;
3143 lastEntry = strrchr(link_name, '/');
3144 if (lastEntry == NULL)
3145 lastEntry = link_name;
3146 else
3147 ++lastEntry;
3148 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
3149 if (location)
3151 r = !write_desktop_entry(NULL, location, lastEntry, start_path, escaped_urlPath, NULL, NULL, icon_name);
3152 if (r == 0)
3153 chmod(location, 0755);
3154 HeapFree(GetProcessHeap(), 0, location);
3157 else
3158 r = !write_menu_entry(unix_link, link_name, start_path, escaped_urlPath, NULL, NULL, icon_name);
3159 ret = (r == 0);
3160 ReleaseSemaphore(hSem, 1, NULL);
3162 cleanup:
3163 if (hSem)
3164 CloseHandle(hSem);
3165 HeapFree( GetProcessHeap(), 0, icon_name );
3166 HeapFree(GetProcessHeap(), 0, link_name);
3167 CoTaskMemFree( urlPath );
3168 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
3169 HeapFree(GetProcessHeap(), 0, unix_link);
3170 return ret;
3173 static BOOL WaitForParentProcess( void )
3175 PROCESSENTRY32 procentry;
3176 HANDLE hsnapshot = NULL, hprocess = NULL;
3177 DWORD ourpid = GetCurrentProcessId();
3178 BOOL ret = FALSE, rc;
3180 WINE_TRACE("Waiting for parent process\n");
3181 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
3182 INVALID_HANDLE_VALUE)
3184 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3185 goto done;
3188 procentry.dwSize = sizeof(PROCESSENTRY32);
3189 rc = Process32First( hsnapshot, &procentry );
3190 while (rc)
3192 if (procentry.th32ProcessID == ourpid) break;
3193 rc = Process32Next( hsnapshot, &procentry );
3195 if (!rc)
3197 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
3198 goto done;
3201 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
3202 NULL)
3204 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
3205 GetLastError());
3206 goto done;
3209 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
3210 ret = TRUE;
3211 else
3212 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3214 done:
3215 if (hprocess) CloseHandle( hprocess );
3216 if (hsnapshot) CloseHandle( hsnapshot );
3217 return ret;
3220 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
3222 IShellLinkW *sl;
3223 IPersistFile *pf;
3224 HRESULT r;
3225 WCHAR fullname[MAX_PATH];
3226 DWORD len;
3228 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
3230 if( !linkname[0] )
3232 WINE_ERR("link name missing\n");
3233 return FALSE;
3236 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
3237 if (len==0 || len>MAX_PATH)
3239 WINE_ERR("couldn't get full path of link file\n");
3240 return FALSE;
3243 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3244 &IID_IShellLinkW, (LPVOID *) &sl );
3245 if( FAILED( r ) )
3247 WINE_ERR("No IID_IShellLink\n");
3248 return FALSE;
3251 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
3252 if( FAILED( r ) )
3254 WINE_ERR("No IID_IPersistFile\n");
3255 return FALSE;
3258 r = IPersistFile_Load( pf, fullname, STGM_READ );
3259 if( SUCCEEDED( r ) )
3261 /* If something fails (eg. Couldn't extract icon)
3262 * wait for parent process and try again
3264 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
3266 WaitForParentProcess();
3267 InvokeShellLinker( sl, fullname, FALSE );
3270 else
3272 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
3275 IPersistFile_Release( pf );
3276 IShellLinkW_Release( sl );
3278 return !r;
3281 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
3283 IUniformResourceLocatorW *url;
3284 IPersistFile *pf;
3285 HRESULT r;
3286 WCHAR fullname[MAX_PATH];
3287 DWORD len;
3289 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
3291 if( !urlname[0] )
3293 WINE_ERR("URL name missing\n");
3294 return FALSE;
3297 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
3298 if (len==0 || len>MAX_PATH)
3300 WINE_ERR("couldn't get full path of URL file\n");
3301 return FALSE;
3304 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
3305 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
3306 if( FAILED( r ) )
3308 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3309 return FALSE;
3312 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
3313 if( FAILED( r ) )
3315 WINE_ERR("No IID_IPersistFile\n");
3316 return FALSE;
3318 r = IPersistFile_Load( pf, fullname, STGM_READ );
3319 if( SUCCEEDED( r ) )
3321 /* If something fails (eg. Couldn't extract icon)
3322 * wait for parent process and try again
3324 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
3326 WaitForParentProcess();
3327 InvokeShellLinkerForURL( url, fullname, FALSE );
3331 IPersistFile_Release( pf );
3332 url->lpVtbl->Release( url );
3334 return !r;
3337 static void RefreshFileTypeAssociations(void)
3339 HANDLE hSem = NULL;
3340 char *mime_dir = NULL;
3341 char *packages_dir = NULL;
3342 char *applications_dir = NULL;
3343 BOOL hasChanged;
3345 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3346 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3348 WINE_ERR("failed wait for semaphore\n");
3349 CloseHandle(hSem);
3350 hSem = NULL;
3351 goto end;
3354 mime_dir = heap_printf("%s/mime", xdg_data_dir);
3355 if (mime_dir == NULL)
3357 WINE_ERR("out of memory\n");
3358 goto end;
3360 create_directories(mime_dir);
3362 packages_dir = heap_printf("%s/packages", mime_dir);
3363 if (packages_dir == NULL)
3365 WINE_ERR("out of memory\n");
3366 goto end;
3368 create_directories(packages_dir);
3370 applications_dir = heap_printf("%s/applications", xdg_data_dir);
3371 if (applications_dir == NULL)
3373 WINE_ERR("out of memory\n");
3374 goto end;
3376 create_directories(applications_dir);
3378 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3379 hasChanged |= cleanup_associations();
3380 if (hasChanged)
3382 const char *argv[3];
3384 argv[0] = "update-mime-database";
3385 argv[1] = mime_dir;
3386 argv[2] = NULL;
3387 _spawnvp( _P_DETACH, argv[0], argv );
3389 argv[0] = "update-desktop-database";
3390 argv[1] = applications_dir;
3391 _spawnvp( _P_DETACH, argv[0], argv );
3394 end:
3395 if (hSem)
3397 ReleaseSemaphore(hSem, 1, NULL);
3398 CloseHandle(hSem);
3400 HeapFree(GetProcessHeap(), 0, mime_dir);
3401 HeapFree(GetProcessHeap(), 0, packages_dir);
3402 HeapFree(GetProcessHeap(), 0, applications_dir);
3405 static void cleanup_menus(void)
3407 HKEY hkey;
3409 hkey = open_menus_reg_key();
3410 if (hkey)
3412 int i;
3413 LSTATUS lret = ERROR_SUCCESS;
3414 for (i = 0; lret == ERROR_SUCCESS; )
3416 WCHAR *value = NULL;
3417 WCHAR *data = NULL;
3418 DWORD valueSize = 4096;
3419 DWORD dataSize = 4096;
3420 while (1)
3422 lret = ERROR_OUTOFMEMORY;
3423 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3424 if (value == NULL)
3425 break;
3426 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3427 if (data == NULL)
3428 break;
3429 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3430 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
3431 break;
3432 valueSize *= 2;
3433 dataSize *= 2;
3434 HeapFree(GetProcessHeap(), 0, value);
3435 HeapFree(GetProcessHeap(), 0, data);
3436 value = data = NULL;
3438 if (lret == ERROR_SUCCESS)
3440 char *unix_file;
3441 char *windows_file;
3442 unix_file = wchars_to_unix_chars(value);
3443 windows_file = wchars_to_unix_chars(data);
3444 if (unix_file != NULL && windows_file != NULL)
3446 struct stat filestats;
3447 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3449 WINE_TRACE("removing menu related file %s\n", unix_file);
3450 remove(unix_file);
3451 RegDeleteValueW(hkey, value);
3453 else
3454 i++;
3456 else
3458 WINE_ERR("out of memory enumerating menus\n");
3459 lret = ERROR_OUTOFMEMORY;
3461 HeapFree(GetProcessHeap(), 0, unix_file);
3462 HeapFree(GetProcessHeap(), 0, windows_file);
3464 else if (lret != ERROR_NO_MORE_ITEMS)
3465 WINE_ERR("error %d reading registry\n", lret);
3466 HeapFree(GetProcessHeap(), 0, value);
3467 HeapFree(GetProcessHeap(), 0, data);
3469 RegCloseKey(hkey);
3471 else
3472 WINE_ERR("error opening registry key, menu cleanup failed\n");
3475 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3477 char *utf8lnkPath = NULL;
3478 char *utf8OutputPath = NULL;
3479 WCHAR *winLnkPath = NULL;
3480 IShellLinkW *shellLink = NULL;
3481 IPersistFile *persistFile = NULL;
3482 WCHAR szTmp[MAX_PATH];
3483 WCHAR szPath[MAX_PATH];
3484 WCHAR szArgs[INFOTIPSIZE];
3485 WCHAR szIconPath[MAX_PATH];
3486 int iconId;
3487 IStream *stream = NULL;
3488 ICONDIRENTRY *pIconDirEntries = NULL;
3489 int numEntries;
3490 HRESULT hr;
3492 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3493 if (utf8lnkPath == NULL)
3495 WINE_ERR("out of memory converting paths\n");
3496 goto end;
3499 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3500 if (utf8OutputPath == NULL)
3502 WINE_ERR("out of memory converting paths\n");
3503 goto end;
3506 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3507 if (winLnkPath == NULL)
3509 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3510 goto end;
3513 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3514 &IID_IShellLinkW, (LPVOID*)&shellLink);
3515 if (FAILED(hr))
3517 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3518 goto end;
3521 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3522 if (FAILED(hr))
3524 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3525 goto end;
3528 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3529 if (FAILED(hr))
3531 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3532 goto end;
3535 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3536 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3537 szTmp[0] = 0;
3538 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3539 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3541 if(!szPath[0])
3543 LPITEMIDLIST pidl = NULL;
3544 IShellLinkW_GetIDList(shellLink, &pidl);
3545 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3546 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3549 if (szIconPath[0])
3551 hr = open_icon(szIconPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3552 if (SUCCEEDED(hr))
3553 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3555 else
3557 hr = open_icon(szPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3558 if (SUCCEEDED(hr))
3559 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3562 end:
3563 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3564 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3565 HeapFree(GetProcessHeap(), 0, winLnkPath);
3566 if (shellLink != NULL)
3567 IShellLinkW_Release(shellLink);
3568 if (persistFile != NULL)
3569 IPersistFile_Release(persistFile);
3570 if (stream != NULL)
3571 IStream_Release(stream);
3572 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
3575 static WCHAR *next_token( LPWSTR *p )
3577 LPWSTR token = NULL, t = *p;
3579 if( !t )
3580 return NULL;
3582 while( t && !token )
3584 switch( *t )
3586 case ' ':
3587 t++;
3588 continue;
3589 case '"':
3590 /* unquote the token */
3591 token = ++t;
3592 t = strchrW( token, '"' );
3593 if( t )
3594 *t++ = 0;
3595 break;
3596 case 0:
3597 t = NULL;
3598 break;
3599 default:
3600 token = t;
3601 t = strchrW( token, ' ' );
3602 if( t )
3603 *t++ = 0;
3604 break;
3607 *p = t;
3608 return token;
3611 static BOOL init_xdg(void)
3613 WCHAR shellDesktopPath[MAX_PATH];
3614 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3615 if (SUCCEEDED(hr))
3616 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3617 if (xdg_desktop_dir == NULL)
3619 WINE_ERR("error looking up the desktop directory\n");
3620 return FALSE;
3623 if (getenv("XDG_CONFIG_HOME"))
3624 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3625 else
3626 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3627 if (xdg_config_dir)
3629 create_directories(xdg_config_dir);
3630 if (getenv("XDG_DATA_HOME"))
3631 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3632 else
3633 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3634 if (xdg_data_dir)
3636 char *buffer;
3637 create_directories(xdg_data_dir);
3638 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3639 if (buffer)
3641 mkdir(buffer, 0777);
3642 HeapFree(GetProcessHeap(), 0, buffer);
3644 return TRUE;
3646 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3648 WINE_ERR("out of memory\n");
3649 return FALSE;
3652 /***********************************************************************
3654 * wWinMain
3656 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3658 static const WCHAR dash_aW[] = {'-','a',0};
3659 static const WCHAR dash_rW[] = {'-','r',0};
3660 static const WCHAR dash_tW[] = {'-','t',0};
3661 static const WCHAR dash_uW[] = {'-','u',0};
3662 static const WCHAR dash_wW[] = {'-','w',0};
3664 LPWSTR token = NULL, p;
3665 BOOL bWait = FALSE;
3666 BOOL bURL = FALSE;
3667 HRESULT hr;
3668 int ret = 0;
3670 if (!init_xdg())
3671 return 1;
3673 hr = CoInitialize(NULL);
3674 if (FAILED(hr))
3676 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3677 return 1;
3680 for( p = cmdline; p && *p; )
3682 token = next_token( &p );
3683 if( !token )
3684 break;
3685 if( !strcmpW( token, dash_aW ) )
3687 RefreshFileTypeAssociations();
3688 continue;
3690 if( !strcmpW( token, dash_rW ) )
3692 cleanup_menus();
3693 continue;
3695 if( !strcmpW( token, dash_wW ) )
3696 bWait = TRUE;
3697 else if ( !strcmpW( token, dash_uW ) )
3698 bURL = TRUE;
3699 else if ( !strcmpW( token, dash_tW ) )
3701 WCHAR *lnkFile = next_token( &p );
3702 if (lnkFile)
3704 WCHAR *outputFile = next_token( &p );
3705 if (outputFile)
3706 thumbnail_lnk(lnkFile, outputFile);
3709 else if( token[0] == '-' )
3711 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3713 else
3715 BOOL bRet;
3717 if (bURL)
3718 bRet = Process_URL( token, bWait );
3719 else
3720 bRet = Process_Link( token, bWait );
3721 if (!bRet)
3723 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3724 ret = 1;
3729 CoUninitialize();
3730 return ret;