user32/tests: Test pending redraw state with owner-drawn list box.
[wine.git] / programs / winemenubuilder / winemenubuilder.c
blob87ff3f3763722565495019961bcb9e9d87cfa9d2
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/list.h"
97 #include "wine/rbtree.h"
99 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
101 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
102 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
103 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
104 (csidl)==CSIDL_COMMON_STARTMENU)
106 #define IS_OPTION_TRUE(ch) \
107 ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
109 /* link file formats */
111 #include "pshpack1.h"
113 typedef struct
115 BYTE bWidth;
116 BYTE bHeight;
117 BYTE bColorCount;
118 BYTE bReserved;
119 WORD wPlanes;
120 WORD wBitCount;
121 DWORD dwBytesInRes;
122 WORD nID;
123 } GRPICONDIRENTRY;
125 typedef struct
127 WORD idReserved;
128 WORD idType;
129 WORD idCount;
130 GRPICONDIRENTRY idEntries[1];
131 } GRPICONDIR;
133 typedef struct
135 BYTE bWidth;
136 BYTE bHeight;
137 BYTE bColorCount;
138 BYTE bReserved;
139 WORD wPlanes;
140 WORD wBitCount;
141 DWORD dwBytesInRes;
142 DWORD dwImageOffset;
143 } ICONDIRENTRY;
145 typedef struct
147 WORD idReserved;
148 WORD idType;
149 WORD idCount;
150 } ICONDIR;
152 typedef struct
154 WORD offset;
155 WORD length;
156 WORD flags;
157 WORD id;
158 WORD handle;
159 WORD usage;
160 } NE_NAMEINFO;
162 typedef struct
164 WORD type_id;
165 WORD count;
166 DWORD resloader;
167 } NE_TYPEINFO;
169 #define NE_RSCTYPE_ICON 0x8003
170 #define NE_RSCTYPE_GROUP_ICON 0x800e
172 #include "poppack.h"
174 typedef struct
176 HRSRC *pResInfo;
177 int nIndex;
178 } ENUMRESSTRUCT;
180 struct xdg_mime_type
182 char *mimeType;
183 char *glob;
184 char *lower_glob;
185 struct list entry;
188 struct rb_string_entry
190 char *string;
191 struct wine_rb_entry entry;
194 DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
196 static char *xdg_config_dir;
197 static char *xdg_data_dir;
198 static char *xdg_desktop_dir;
201 /* Utility routines */
202 static unsigned short crc16(const char* string)
204 unsigned short crc = 0;
205 int i, j, xor_poly;
207 for (i = 0; string[i] != 0; i++)
209 char c = string[i];
210 for (j = 0; j < 8; c >>= 1, j++)
212 xor_poly = (c ^ crc) & 1;
213 crc >>= 1;
214 if (xor_poly)
215 crc ^= 0xa001;
218 return crc;
221 static char *strdupA( const char *str )
223 char *ret;
225 if (!str) return NULL;
226 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
227 return ret;
230 static char* heap_printf(const char *format, ...)
232 va_list args;
233 int size = 4096;
234 char *buffer, *ret;
235 int n;
237 while (1)
239 buffer = HeapAlloc(GetProcessHeap(), 0, size);
240 if (buffer == NULL)
241 break;
242 va_start(args, format);
243 n = vsnprintf(buffer, size, format, args);
244 va_end(args);
245 if (n == -1)
246 size *= 2;
247 else if (n >= size)
248 size = n + 1;
249 else
250 break;
251 HeapFree(GetProcessHeap(), 0, buffer);
254 if (!buffer) return NULL;
255 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
256 if (!ret) ret = buffer;
257 return ret;
260 static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
262 const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);
264 return strcmp((char*)key, t->string);
267 static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
269 struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
270 HeapFree(GetProcessHeap(), 0, t->string);
271 HeapFree(GetProcessHeap(), 0, t);
274 static void write_xml_text(FILE *file, const char *text)
276 int i;
277 for (i = 0; text[i]; i++)
279 if (text[i] == '&')
280 fputs("&amp;", file);
281 else if (text[i] == '<')
282 fputs("&lt;", file);
283 else if (text[i] == '>')
284 fputs("&gt;", file);
285 else if (text[i] == '\'')
286 fputs("&apos;", file);
287 else if (text[i] == '"')
288 fputs("&quot;", file);
289 else
290 fputc(text[i], file);
294 static BOOL create_directories(char *directory)
296 BOOL ret = TRUE;
297 int i;
299 for (i = 0; directory[i]; i++)
301 if (i > 0 && directory[i] == '/')
303 directory[i] = 0;
304 mkdir(directory, 0777);
305 directory[i] = '/';
308 if (mkdir(directory, 0777) && errno != EEXIST)
309 ret = FALSE;
311 return ret;
314 static char* wchars_to_utf8_chars(LPCWSTR string)
316 char *ret;
317 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
318 ret = HeapAlloc(GetProcessHeap(), 0, size);
319 if (ret)
320 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
321 return ret;
324 static char* wchars_to_unix_chars(LPCWSTR string)
326 char *ret;
327 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
328 ret = HeapAlloc(GetProcessHeap(), 0, size);
329 if (ret)
330 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
331 return ret;
334 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
336 WCHAR *ret;
337 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
338 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
339 if (ret)
340 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
341 return ret;
344 /* Icon extraction routines
346 * FIXME: should use PrivateExtractIcons and friends
347 * FIXME: should not use stdio
350 static HRESULT convert_to_native_icon(IStream *icoFile, int *indices, int numIndices,
351 const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
353 WCHAR *dosOutputFileName = NULL;
354 IWICImagingFactory *factory = NULL;
355 IWICBitmapDecoder *decoder = NULL;
356 IWICBitmapEncoder *encoder = NULL;
357 IWICBitmapScaler *scaler = NULL;
358 IStream *outputFile = NULL;
359 int i;
360 HRESULT hr = E_FAIL;
362 dosOutputFileName = wine_get_dos_file_name(outputFileName);
363 if (dosOutputFileName == NULL)
365 WINE_ERR("error converting %s to DOS file name\n", outputFileName);
366 goto end;
368 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
369 &IID_IWICImagingFactory, (void**)&factory);
370 if (FAILED(hr))
372 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
373 goto end;
375 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
376 WICDecodeMetadataCacheOnDemand, &decoder);
377 if (FAILED(hr))
379 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
380 goto end;
382 if (IsEqualCLSID(outputFormat,&CLSID_WICIcnsEncoder))
384 hr = IWICImagingFactory_CreateBitmapScaler(factory, &scaler);
385 if (FAILED(hr))
387 WINE_WARN("error 0x%08X creating IWICBitmapScaler\n", hr);
390 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
391 &IID_IWICBitmapEncoder, (void**)&encoder);
392 if (FAILED(hr))
394 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
395 goto end;
397 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
398 if (FAILED(hr))
400 WINE_ERR("error 0x%08X creating output file %s\n", hr, wine_dbgstr_w(dosOutputFileName));
401 goto end;
403 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, WICBitmapEncoderNoCache);
404 if (FAILED(hr))
406 WINE_ERR("error 0x%08X initializing encoder\n", hr);
407 goto end;
410 for (i = 0; i < numIndices; i++)
412 IWICBitmapFrameDecode *sourceFrame = NULL;
413 IWICBitmapSource *sourceBitmap = NULL;
414 IWICBitmapFrameEncode *dstFrame = NULL;
415 IPropertyBag2 *options = NULL;
416 UINT width, height;
418 hr = IWICBitmapDecoder_GetFrame(decoder, indices[i], &sourceFrame);
419 if (FAILED(hr))
421 WINE_ERR("error 0x%08X getting frame %d\n", hr, indices[i]);
422 goto endloop;
424 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
425 if (FAILED(hr))
427 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
428 goto endloop;
430 if ( scaler)
432 IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
433 if (width == 64) /* Classic Mode */
435 hr = IWICBitmapScaler_Initialize( scaler, sourceBitmap, 128, 128,
436 WICBitmapInterpolationModeNearestNeighbor);
437 if (FAILED(hr))
438 WINE_ERR("error 0x%08X scaling bitmap\n", hr);
439 else
441 IWICBitmapSource_Release(sourceBitmap);
442 IWICBitmapScaler_QueryInterface(scaler, &IID_IWICBitmapSource, (LPVOID)&sourceBitmap);
446 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
447 if (FAILED(hr))
449 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
450 goto endloop;
452 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
453 if (FAILED(hr))
455 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
456 goto endloop;
458 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
459 if (FAILED(hr))
461 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
462 goto endloop;
464 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
465 if (FAILED(hr))
467 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
468 goto endloop;
470 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
471 if (FAILED(hr))
473 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
474 goto endloop;
476 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
477 if (FAILED(hr))
479 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
480 goto endloop;
482 hr = IWICBitmapFrameEncode_Commit(dstFrame);
483 if (FAILED(hr))
485 WINE_ERR("error 0x%08X committing frame\n", hr);
486 goto endloop;
488 endloop:
489 if (sourceFrame)
490 IWICBitmapFrameDecode_Release(sourceFrame);
491 if (sourceBitmap)
492 IWICBitmapSource_Release(sourceBitmap);
493 if (dstFrame)
494 IWICBitmapFrameEncode_Release(dstFrame);
495 if (options)
496 IPropertyBag2_Release(options);
499 hr = IWICBitmapEncoder_Commit(encoder);
500 if (FAILED(hr))
502 WINE_ERR("error 0x%08X committing encoder\n", hr);
503 goto end;
506 end:
507 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
508 if (factory)
509 IWICImagingFactory_Release(factory);
510 if (decoder)
511 IWICBitmapDecoder_Release(decoder);
512 if (scaler)
513 IWICBitmapScaler_Release(scaler);
514 if (encoder)
515 IWICBitmapEncoder_Release(encoder);
516 if (outputFile)
517 IStream_Release(outputFile);
518 return hr;
521 struct IconData16 {
522 BYTE *fileBytes;
523 DWORD fileSize;
524 NE_TYPEINFO *iconResources;
525 WORD alignmentShiftCount;
528 static int populate_module16_icons(struct IconData16 *iconData16, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
530 int i, j;
531 int validEntries = 0;
533 for (i = 0; i < grpIconDir->idCount; i++)
535 BYTE *iconPtr = (BYTE*)iconData16->iconResources;
536 NE_NAMEINFO *matchingIcon = NULL;
537 iconPtr += sizeof(NE_TYPEINFO);
538 for (j = 0; j < iconData16->iconResources->count; j++)
540 NE_NAMEINFO *iconInfo = (NE_NAMEINFO*)iconPtr;
541 if ((iconPtr + sizeof(NE_NAMEINFO)) > (iconData16->fileBytes + iconData16->fileSize))
543 WINE_WARN("file too small for icon NE_NAMEINFO\n");
544 break;
546 if (iconInfo->id == (0x8000 | grpIconDir->idEntries[i].nID))
548 matchingIcon = iconInfo;
549 break;
551 iconPtr += sizeof(NE_NAMEINFO);
554 if (matchingIcon == NULL)
555 continue;
556 if (((matchingIcon->offset << iconData16->alignmentShiftCount) + grpIconDir->idEntries[i].dwBytesInRes) > iconData16->fileSize)
558 WINE_WARN("file too small for icon contents\n");
559 break;
562 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
563 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
564 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
565 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
566 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
567 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
568 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
569 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
570 validEntries++;
571 memcpy(&icons[*iconOffset], &iconData16->fileBytes[matchingIcon->offset << iconData16->alignmentShiftCount], grpIconDir->idEntries[i].dwBytesInRes);
572 *iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
574 return validEntries;
577 static int populate_module_icons(HMODULE hModule, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
579 int i;
580 int validEntries = 0;
582 for (i = 0; i < grpIconDir->idCount; i++)
584 HRSRC hResInfo;
585 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
586 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
588 HGLOBAL hResData;
589 if ((hResData = LoadResource(hModule, hResInfo)))
591 BITMAPINFO *pIcon;
592 DWORD size = min( grpIconDir->idEntries[i].dwBytesInRes, ((IMAGE_RESOURCE_DATA_ENTRY *)hResInfo)->Size );
593 if ((pIcon = LockResource(hResData)))
595 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
596 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
597 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
598 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
599 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
600 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
601 iconDirEntries[validEntries].dwBytesInRes = size;
602 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
603 validEntries++;
604 memcpy(&icons[*iconOffset], pIcon, size);
605 *iconOffset += size;
607 FreeResource(hResData);
611 return validEntries;
614 static IStream *add_module_icons_to_stream(struct IconData16 *iconData16, HMODULE hModule, GRPICONDIR *grpIconDir)
616 int i;
617 SIZE_T iconsSize = 0;
618 BYTE *icons = NULL;
619 ICONDIRENTRY *iconDirEntries = NULL;
620 IStream *stream = NULL;
621 HRESULT hr = E_FAIL;
622 ULONG bytesWritten;
623 ICONDIR iconDir;
624 SIZE_T iconOffset;
625 int validEntries = 0;
626 LARGE_INTEGER zero;
628 for (i = 0; i < grpIconDir->idCount; i++)
629 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
630 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
631 if (icons == NULL)
633 WINE_ERR("out of memory allocating icon\n");
634 goto end;
637 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
638 if (iconDirEntries == NULL)
640 WINE_ERR("out of memory allocating icon dir entries\n");
641 goto end;
644 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
645 if (FAILED(hr))
647 WINE_ERR("error creating icon stream\n");
648 goto end;
651 iconOffset = 0;
652 if (iconData16)
653 validEntries = populate_module16_icons(iconData16, grpIconDir, iconDirEntries, icons, &iconOffset);
654 else if (hModule)
655 validEntries = populate_module_icons(hModule, grpIconDir, iconDirEntries, icons, &iconOffset);
657 if (validEntries == 0)
659 WINE_ERR("no valid icon entries\n");
660 goto end;
663 iconDir.idReserved = 0;
664 iconDir.idType = 1;
665 iconDir.idCount = validEntries;
666 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
667 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
669 WINE_ERR("error 0x%08X writing icon stream\n", hr);
670 goto end;
672 for (i = 0; i < validEntries; i++)
673 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
674 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
675 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
677 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
678 goto end;
680 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
681 if (FAILED(hr) || bytesWritten != iconOffset)
683 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
684 goto end;
686 zero.QuadPart = 0;
687 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
689 end:
690 HeapFree(GetProcessHeap(), 0, icons);
691 HeapFree(GetProcessHeap(), 0, iconDirEntries);
692 if (FAILED(hr) && stream != NULL)
694 IStream_Release(stream);
695 stream = NULL;
697 return stream;
700 static HRESULT open_module16_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
702 HANDLE hFile = INVALID_HANDLE_VALUE;
703 HANDLE hFileMapping = NULL;
704 DWORD fileSize;
705 BYTE *fileBytes = NULL;
706 IMAGE_DOS_HEADER *dosHeader;
707 IMAGE_OS2_HEADER *neHeader;
708 BYTE *rsrcTab;
709 NE_TYPEINFO *iconGroupResources;
710 NE_TYPEINFO *iconResources;
711 NE_NAMEINFO *iconDirPtr;
712 GRPICONDIR *iconDir;
713 WORD alignmentShiftCount;
714 struct IconData16 iconData16;
715 HRESULT hr = E_FAIL;
717 hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
718 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
719 if (hFile == INVALID_HANDLE_VALUE)
721 WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName), GetLastError());
722 goto end;
725 hFileMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
726 if (hFileMapping == NULL)
728 WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
729 goto end;
732 fileSize = GetFileSize(hFile, NULL);
734 fileBytes = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
735 if (fileBytes == NULL)
737 WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
738 goto end;
741 dosHeader = (IMAGE_DOS_HEADER*)fileBytes;
742 if (sizeof(IMAGE_DOS_HEADER) >= fileSize || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
744 WINE_WARN("file too small for MZ header\n");
745 goto end;
748 neHeader = (IMAGE_OS2_HEADER*)(fileBytes + dosHeader->e_lfanew);
749 if ((((BYTE*)neHeader) + sizeof(IMAGE_OS2_HEADER)) > (fileBytes + fileSize) ||
750 neHeader->ne_magic != IMAGE_OS2_SIGNATURE)
752 WINE_WARN("file too small for NE header\n");
753 goto end;
756 rsrcTab = ((BYTE*)neHeader) + neHeader->ne_rsrctab;
757 if ((rsrcTab + 2) > (fileBytes + fileSize))
759 WINE_WARN("file too small for resource table\n");
760 goto end;
763 alignmentShiftCount = *(WORD*)rsrcTab;
764 rsrcTab += 2;
765 iconGroupResources = NULL;
766 iconResources = NULL;
767 for (;;)
769 NE_TYPEINFO *neTypeInfo = (NE_TYPEINFO*)rsrcTab;
770 if ((rsrcTab + sizeof(NE_TYPEINFO)) > (fileBytes + fileSize))
772 WINE_WARN("file too small for resource table\n");
773 goto end;
775 if (neTypeInfo->type_id == 0)
776 break;
777 else if (neTypeInfo->type_id == NE_RSCTYPE_GROUP_ICON)
778 iconGroupResources = neTypeInfo;
779 else if (neTypeInfo->type_id == NE_RSCTYPE_ICON)
780 iconResources = neTypeInfo;
781 rsrcTab += sizeof(NE_TYPEINFO) + neTypeInfo->count*sizeof(NE_NAMEINFO);
783 if (iconGroupResources == NULL)
785 WINE_WARN("no group icon resource type found\n");
786 goto end;
788 if (iconResources == NULL)
790 WINE_WARN("no icon resource type found\n");
791 goto end;
794 if (nIndex >= iconGroupResources->count)
796 WINE_WARN("icon index out of range\n");
797 goto end;
800 iconDirPtr = (NE_NAMEINFO*)(((BYTE*)iconGroupResources) + sizeof(NE_TYPEINFO) + nIndex*sizeof(NE_NAMEINFO));
801 if ((((BYTE*)iconDirPtr) + sizeof(NE_NAMEINFO)) > (fileBytes + fileSize))
803 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
804 goto end;
806 iconDir = (GRPICONDIR*)(fileBytes + (iconDirPtr->offset << alignmentShiftCount));
807 if ((((BYTE*)iconDir) + sizeof(GRPICONDIR) + iconDir->idCount*sizeof(GRPICONDIRENTRY)) > (fileBytes + fileSize))
809 WINE_WARN("file too small for GRPICONDIR\n");
810 goto end;
813 iconData16.fileBytes = fileBytes;
814 iconData16.fileSize = fileSize;
815 iconData16.iconResources = iconResources;
816 iconData16.alignmentShiftCount = alignmentShiftCount;
817 *ppStream = add_module_icons_to_stream(&iconData16, NULL, iconDir);
818 if (*ppStream)
819 hr = S_OK;
821 end:
822 if (hFile != INVALID_HANDLE_VALUE)
823 CloseHandle(hFile);
824 if (hFileMapping != NULL)
825 CloseHandle(hFileMapping);
826 if (fileBytes != NULL)
827 UnmapViewOfFile(fileBytes);
828 return hr;
831 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
833 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
835 if (!sEnumRes->nIndex--)
837 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
838 return FALSE;
840 else
841 return TRUE;
844 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
846 HMODULE hModule;
847 HRSRC hResInfo;
848 HGLOBAL hResData;
849 GRPICONDIR *pIconDir;
850 ENUMRESSTRUCT sEnumRes;
851 HRESULT hr = E_FAIL;
853 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
854 if (!hModule)
856 if (GetLastError() == ERROR_BAD_EXE_FORMAT)
857 return open_module16_icon(szFileName, nIndex, ppStream);
858 else
860 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
861 wine_dbgstr_w(szFileName), GetLastError());
862 return HRESULT_FROM_WIN32(GetLastError());
866 if (nIndex < 0)
868 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
869 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
870 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
872 else
874 hResInfo=NULL;
875 sEnumRes.pResInfo = &hResInfo;
876 sEnumRes.nIndex = nIndex;
877 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
878 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
879 sEnumRes.nIndex != -1)
881 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
885 if (hResInfo)
887 if ((hResData = LoadResource(hModule, hResInfo)))
889 if ((pIconDir = LockResource(hResData)))
891 *ppStream = add_module_icons_to_stream(0, hModule, pIconDir);
892 if (*ppStream)
893 hr = S_OK;
896 FreeResource(hResData);
899 else
901 WINE_WARN("found no icon\n");
902 FreeLibrary(hModule);
903 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
906 FreeLibrary(hModule);
907 return hr;
910 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
912 ICONDIR iconDir;
913 ULONG bytesRead;
914 HRESULT hr;
916 *ppIconDirEntries = NULL;
918 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
919 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
920 (iconDir.idReserved != 0) || (iconDir.idType != 1))
922 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
923 hr = E_FAIL;
924 goto end;
926 *numEntries = iconDir.idCount;
928 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
930 hr = E_OUTOFMEMORY;
931 goto end;
933 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
934 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
936 if (SUCCEEDED(hr)) hr = E_FAIL;
937 goto end;
940 end:
941 if (FAILED(hr))
942 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
943 return hr;
946 static HRESULT validate_ico(IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
948 HRESULT hr;
950 hr = read_ico_direntries(*ppStream, ppIconDirEntries, numEntries);
951 if (SUCCEEDED(hr))
953 if (*numEntries)
954 return hr;
955 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
956 *ppIconDirEntries = NULL;
958 IStream_Release(*ppStream);
959 *ppStream = NULL;
960 return E_FAIL;
963 static HRESULT write_native_icon(IStream *iconStream, ICONDIRENTRY *pIconDirEntry,
964 int numEntries, const char *icon_name, LPCWSTR szFileName)
966 int nMax = 0, nMaxBits = 0;
967 int nIndex = 0;
968 int i;
969 LARGE_INTEGER position;
970 HRESULT hr;
972 for (i = 0; i < numEntries; i++)
974 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
975 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
976 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
978 nIndex = i;
979 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
980 nMaxBits = pIconDirEntry[i].wBitCount;
983 WINE_TRACE("Selected: %d\n", nIndex);
985 position.QuadPart = 0;
986 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
987 if (FAILED(hr)) return hr;
988 return convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
991 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
993 HRESULT hr;
994 WCHAR *value = NULL;
995 DWORD size = 0;
996 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
997 if (SUCCEEDED(hr))
999 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1000 if (value)
1002 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1003 if (FAILED(hr))
1005 HeapFree(GetProcessHeap(), 0, value);
1006 value = NULL;
1010 return value;
1013 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
1015 static const WCHAR openW[] = {'o','p','e','n',0};
1016 WCHAR *extension;
1017 WCHAR *icon = NULL;
1018 WCHAR *comma;
1019 WCHAR *executable = NULL;
1020 int index = 0;
1021 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
1023 extension = strrchrW(szFileName, '.');
1024 if (extension == NULL)
1025 goto end;
1027 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
1028 if (icon)
1030 comma = strrchrW(icon, ',');
1031 if (comma)
1033 *comma = 0;
1034 index = atoiW(comma + 1);
1036 hr = open_module_icon(icon, index, ppStream);
1038 else
1040 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, openW);
1041 if (executable)
1042 hr = open_module_icon(executable, 0, ppStream);
1045 end:
1046 HeapFree(GetProcessHeap(), 0, icon);
1047 HeapFree(GetProcessHeap(), 0, executable);
1048 return hr;
1051 static HRESULT open_default_icon(IStream **ppStream)
1053 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
1055 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
1058 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
1060 HRESULT hr;
1062 hr = open_module_icon(filename, index, ppStream);
1063 if (FAILED(hr))
1065 if(bWait && hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
1067 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1068 wine_dbgstr_w(filename));
1069 return hr;
1071 else
1073 /* This might be a raw .ico file */
1074 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
1077 if (SUCCEEDED(hr))
1078 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1080 if (FAILED(hr))
1082 hr = open_file_type_icon(filename, ppStream);
1083 if (SUCCEEDED(hr))
1084 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1086 if (FAILED(hr) && !bWait)
1088 hr = open_default_icon(ppStream);
1089 if (SUCCEEDED(hr))
1090 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1092 return hr;
1095 static char* compute_native_identifier(int exeIndex, LPCWSTR icoPathW)
1097 char* nativeIdentifier;
1098 char *icoPathA;
1099 unsigned short crc;
1100 char *basename, *ext;
1102 icoPathA = wchars_to_utf8_chars(icoPathW);
1103 if (icoPathA == NULL)
1104 return NULL;
1106 crc = crc16(icoPathA);
1107 basename = strrchr(icoPathA, '\\');
1108 if (basename == NULL)
1109 basename = icoPathA;
1110 else
1112 *basename = 0;
1113 basename++;
1115 ext = strrchr(basename, '.');
1116 if (ext)
1117 *ext = 0;
1119 nativeIdentifier = heap_printf("%04X_%s.%d", crc, basename, exeIndex);
1120 HeapFree(GetProcessHeap(), 0, icoPathA);
1121 return nativeIdentifier;
1124 #ifdef __APPLE__
1125 #define ICNS_SLOTS 6
1127 static inline int size_to_slot(int size)
1129 switch (size)
1131 case 16: return 0;
1132 case 32: return 1;
1133 case 48: return 2;
1134 case 64: return -2; /* Classic Mode */
1135 case 128: return 3;
1136 case 256: return 4;
1137 case 512: return 5;
1140 return -1;
1143 #define CLASSIC_SLOT 3
1145 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1146 int numEntries, int exeIndex, LPCWSTR icoPathW,
1147 const char *destFilename, char **nativeIdentifier)
1149 struct {
1150 int index;
1151 int maxBits;
1152 BOOL scaled;
1153 } best[ICNS_SLOTS];
1154 int indexes[ICNS_SLOTS];
1155 int i;
1156 const char* tmpdir;
1157 char *icnsPath = NULL;
1158 LARGE_INTEGER zero;
1159 HRESULT hr;
1161 for (i = 0; i < ICNS_SLOTS; i++)
1163 best[i].index = -1;
1164 best[i].maxBits = 0;
1166 for (i = 0; i < numEntries; i++)
1168 int slot;
1169 int width = iconDirEntries[i].bWidth ? iconDirEntries[i].bWidth : 256;
1170 int height = iconDirEntries[i].bHeight ? iconDirEntries[i].bHeight : 256;
1171 BOOL scaled = FALSE;
1173 WINE_TRACE("[%d]: %d x %d @ %d\n", i, width, height, iconDirEntries[i].wBitCount);
1174 if (height != width)
1175 continue;
1176 slot = size_to_slot(width);
1177 if (slot == -2)
1179 scaled = TRUE;
1180 slot = CLASSIC_SLOT;
1182 else if (slot < 0)
1183 continue;
1184 if (scaled && best[slot].maxBits && !best[slot].scaled)
1185 continue; /* don't replace unscaled with scaled */
1186 if (iconDirEntries[i].wBitCount >= best[slot].maxBits || (!scaled && best[slot].scaled))
1188 best[slot].index = i;
1189 best[slot].maxBits = iconDirEntries[i].wBitCount;
1190 best[slot].scaled = scaled;
1193 /* remove the scaled icon if a larger unscaled icon exists */
1194 if (best[CLASSIC_SLOT].scaled)
1196 for (i = CLASSIC_SLOT+1; i < ICNS_SLOTS; i++)
1197 if (best[i].index >= 0 && !best[i].scaled)
1199 best[CLASSIC_SLOT].index = -1;
1200 break;
1204 numEntries = 0;
1205 for (i = 0; i < ICNS_SLOTS; i++)
1207 if (best[i].index >= 0)
1209 indexes[numEntries] = best[i].index;
1210 numEntries++;
1214 if (destFilename)
1215 *nativeIdentifier = heap_printf("%s", destFilename);
1216 else
1217 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1218 if (*nativeIdentifier == NULL)
1220 hr = E_OUTOFMEMORY;
1221 goto end;
1223 if (!(tmpdir = getenv("TMPDIR"))) tmpdir = "/tmp";
1224 icnsPath = heap_printf("%s/%s.icns", tmpdir, *nativeIdentifier);
1225 if (icnsPath == NULL)
1227 hr = E_OUTOFMEMORY;
1228 WINE_WARN("out of memory creating ICNS path\n");
1229 goto end;
1231 zero.QuadPart = 0;
1232 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1233 if (FAILED(hr))
1235 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
1236 goto end;
1238 hr = convert_to_native_icon(icoStream, indexes, numEntries, &CLSID_WICIcnsEncoder,
1239 icnsPath, icoPathW);
1240 if (FAILED(hr))
1242 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
1243 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
1244 goto end;
1247 end:
1248 HeapFree(GetProcessHeap(), 0, icnsPath);
1249 return hr;
1251 #else
1252 static void refresh_icon_cache(const char *iconsDir)
1254 /* The icon theme spec only requires the mtime on the "toplevel"
1255 * directory (whatever that is) to be changed for a refresh,
1256 * but on GNOME you have to create a file in that directory
1257 * instead. Creating a file also works on KDE, Xfce and LXDE.
1259 char *filename = heap_printf("%s/.wine-refresh-XXXXXX", iconsDir);
1260 if (filename != NULL)
1262 int fd = mkstemps(filename, 0);
1263 if (fd >= 0)
1265 close(fd);
1266 unlink(filename);
1268 HeapFree(GetProcessHeap(), 0, filename);
1272 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1273 int numEntries, int exeIndex, LPCWSTR icoPathW,
1274 const char *destFilename, char **nativeIdentifier)
1276 int i;
1277 char *iconsDir = NULL;
1278 HRESULT hr = S_OK;
1279 LARGE_INTEGER zero;
1281 if (destFilename)
1282 *nativeIdentifier = heap_printf("%s", destFilename);
1283 else
1284 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1285 if (*nativeIdentifier == NULL)
1287 hr = E_OUTOFMEMORY;
1288 goto end;
1290 iconsDir = heap_printf("%s/icons/hicolor", xdg_data_dir);
1291 if (iconsDir == NULL)
1293 hr = E_OUTOFMEMORY;
1294 goto end;
1297 for (i = 0; i < numEntries; i++)
1299 int bestIndex = i;
1300 int j;
1301 BOOLEAN duplicate = FALSE;
1302 int w, h;
1303 char *iconDir = NULL;
1304 char *pngPath = NULL;
1306 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
1307 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
1309 for (j = 0; j < i; j++)
1311 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1312 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
1314 duplicate = TRUE;
1315 break;
1318 if (duplicate)
1319 continue;
1320 for (j = i + 1; j < numEntries; j++)
1322 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1323 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1324 iconDirEntries[j].wBitCount >= iconDirEntries[bestIndex].wBitCount)
1326 bestIndex = j;
1329 WINE_TRACE("Selected: %d\n", bestIndex);
1331 w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
1332 h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
1333 iconDir = heap_printf("%s/%dx%d/apps", iconsDir, w, h);
1334 if (iconDir == NULL)
1336 hr = E_OUTOFMEMORY;
1337 goto endloop;
1339 create_directories(iconDir);
1340 pngPath = heap_printf("%s/%s.png", iconDir, *nativeIdentifier);
1341 if (pngPath == NULL)
1343 hr = E_OUTOFMEMORY;
1344 goto endloop;
1346 zero.QuadPart = 0;
1347 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1348 if (FAILED(hr))
1349 goto endloop;
1350 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
1351 pngPath, icoPathW);
1353 endloop:
1354 HeapFree(GetProcessHeap(), 0, iconDir);
1355 HeapFree(GetProcessHeap(), 0, pngPath);
1357 refresh_icon_cache(iconsDir);
1359 end:
1360 HeapFree(GetProcessHeap(), 0, iconsDir);
1361 return hr;
1363 #endif /* defined(__APPLE__) */
1365 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1366 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
1368 IStream *stream = NULL;
1369 ICONDIRENTRY *pIconDirEntries = NULL;
1370 int numEntries;
1371 HRESULT hr;
1372 char *nativeIdentifier = NULL;
1374 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
1376 hr = open_icon(icoPathW, index, bWait, &stream, &pIconDirEntries, &numEntries);
1377 if (FAILED(hr))
1379 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
1380 goto end;
1382 hr = platform_write_icon(stream, pIconDirEntries, numEntries, index, icoPathW, destFilename, &nativeIdentifier);
1383 if (FAILED(hr))
1384 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
1386 end:
1387 if (stream)
1388 IStream_Release(stream);
1389 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
1390 if (FAILED(hr))
1392 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
1393 nativeIdentifier = NULL;
1395 return nativeIdentifier;
1398 static HKEY open_menus_reg_key(void)
1400 static const WCHAR Software_Wine_FileOpenMenuFilesW[] = {
1401 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1402 HKEY assocKey;
1403 DWORD ret;
1404 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenMenuFilesW, &assocKey);
1405 if (ret == ERROR_SUCCESS)
1406 return assocKey;
1407 SetLastError(ret);
1408 return NULL;
1411 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1413 WCHAR *unix_fileW;
1414 WCHAR *windows_fileW;
1415 INT size;
1416 DWORD ret;
1418 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1419 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1420 if (unix_fileW)
1422 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1423 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1424 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1425 if (windows_fileW)
1427 HKEY hkey;
1428 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1429 hkey = open_menus_reg_key();
1430 if (hkey)
1432 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1433 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1434 RegCloseKey(hkey);
1436 else
1437 ret = GetLastError();
1438 HeapFree(GetProcessHeap(), 0, windows_fileW);
1440 else
1441 ret = ERROR_NOT_ENOUGH_MEMORY;
1442 HeapFree(GetProcessHeap(), 0, unix_fileW);
1444 else
1445 ret = ERROR_NOT_ENOUGH_MEMORY;
1446 return ret;
1449 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1450 const char *path, const char *args, const char *descr,
1451 const char *workdir, const char *icon, const char *wmclass)
1453 FILE *file;
1454 const char *prefix = getenv("WINEPREFIX");
1455 const char *home = getenv("HOME");
1457 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1458 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1459 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon),
1460 wine_dbgstr_a(wmclass));
1462 file = fopen(location, "w");
1463 if (file == NULL)
1464 return FALSE;
1466 fprintf(file, "[Desktop Entry]\n");
1467 fprintf(file, "Name=%s\n", linkname);
1468 if (prefix)
1469 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n", prefix, path, args);
1470 else if (home)
1471 fprintf(file, "Exec=env WINEPREFIX=\"%s/.wine\" wine %s %s\n", home, path, args);
1472 else
1473 fprintf(file, "Exec=wine %s %s\n", path, args);
1474 fprintf(file, "Type=Application\n");
1475 fprintf(file, "StartupNotify=true\n");
1476 if (descr && *descr)
1477 fprintf(file, "Comment=%s\n", descr);
1478 if (workdir && *workdir)
1479 fprintf(file, "Path=%s\n", workdir);
1480 if (icon && *icon)
1481 fprintf(file, "Icon=%s\n", icon);
1482 if (wmclass && *wmclass)
1483 fprintf(file, "StartupWMClass=%s\n", wmclass);
1485 fclose(file);
1487 if (unix_link)
1489 DWORD ret = register_menus_entry(location, unix_link);
1490 if (ret != ERROR_SUCCESS)
1491 return FALSE;
1494 return TRUE;
1497 static BOOL write_directory_entry(const char *directory, const char *location)
1499 FILE *file;
1501 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1503 file = fopen(location, "w");
1504 if (file == NULL)
1505 return FALSE;
1507 fprintf(file, "[Desktop Entry]\n");
1508 fprintf(file, "Type=Directory\n");
1509 if (strcmp(directory, "wine") == 0)
1511 fprintf(file, "Name=Wine\n");
1512 fprintf(file, "Icon=wine\n");
1514 else
1516 fprintf(file, "Name=%s\n", directory);
1517 fprintf(file, "Icon=folder\n");
1520 fclose(file);
1521 return TRUE;
1524 static BOOL write_menu_file(const char *unix_link, const char *filename)
1526 char *tempfilename;
1527 FILE *tempfile = NULL;
1528 char *lastEntry;
1529 char *name = NULL;
1530 char *menuPath = NULL;
1531 int i;
1532 int count = 0;
1533 BOOL ret = FALSE;
1535 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1537 while (1)
1539 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1540 if (tempfilename)
1542 int tempfd = mkstemps(tempfilename, 0);
1543 if (tempfd >= 0)
1545 tempfile = fdopen(tempfd, "w");
1546 if (tempfile)
1547 break;
1548 close(tempfd);
1549 goto end;
1551 else if (errno == EEXIST)
1553 HeapFree(GetProcessHeap(), 0, tempfilename);
1554 continue;
1556 HeapFree(GetProcessHeap(), 0, tempfilename);
1558 return FALSE;
1561 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1562 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1563 fprintf(tempfile, "<Menu>\n");
1564 fprintf(tempfile, " <Name>Applications</Name>\n");
1566 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1567 if (name == NULL) goto end;
1568 lastEntry = name;
1569 for (i = 0; filename[i]; i++)
1571 name[i] = filename[i];
1572 if (filename[i] == '/')
1574 char *dir_file_name;
1575 struct stat st;
1576 name[i] = 0;
1577 fprintf(tempfile, " <Menu>\n");
1578 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1579 write_xml_text(tempfile, name);
1580 fprintf(tempfile, "</Name>\n");
1581 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1582 write_xml_text(tempfile, name);
1583 fprintf(tempfile, ".directory</Directory>\n");
1584 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1585 xdg_data_dir, count ? "" : "wine-", name);
1586 if (dir_file_name)
1588 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1589 write_directory_entry(lastEntry, dir_file_name);
1590 HeapFree(GetProcessHeap(), 0, dir_file_name);
1592 name[i] = '-';
1593 lastEntry = &name[i+1];
1594 ++count;
1597 name[i] = 0;
1599 fprintf(tempfile, " <Include>\n");
1600 fprintf(tempfile, " <Filename>");
1601 write_xml_text(tempfile, name);
1602 fprintf(tempfile, "</Filename>\n");
1603 fprintf(tempfile, " </Include>\n");
1604 for (i = 0; i < count; i++)
1605 fprintf(tempfile, " </Menu>\n");
1606 fprintf(tempfile, "</Menu>\n");
1608 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1609 if (menuPath == NULL) goto end;
1610 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1611 ret = TRUE;
1613 end:
1614 if (tempfile)
1615 fclose(tempfile);
1616 if (ret)
1617 ret = (rename(tempfilename, menuPath) == 0);
1618 if (!ret && tempfilename)
1619 remove(tempfilename);
1620 HeapFree(GetProcessHeap(), 0, tempfilename);
1621 if (ret)
1622 register_menus_entry(menuPath, unix_link);
1623 HeapFree(GetProcessHeap(), 0, name);
1624 HeapFree(GetProcessHeap(), 0, menuPath);
1625 return ret;
1628 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1629 const char *descr, const char *workdir, const char *icon, const char *wmclass)
1631 const char *linkname;
1632 char *desktopPath = NULL;
1633 char *desktopDir;
1634 char *filename = NULL;
1635 BOOL ret = TRUE;
1637 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1638 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1639 wine_dbgstr_a(workdir), wine_dbgstr_a(icon), wine_dbgstr_a(wmclass));
1641 linkname = strrchr(link, '/');
1642 if (linkname == NULL)
1643 linkname = link;
1644 else
1645 ++linkname;
1647 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1648 if (!desktopPath)
1650 WINE_WARN("out of memory creating menu entry\n");
1651 ret = FALSE;
1652 goto end;
1654 desktopDir = strrchr(desktopPath, '/');
1655 *desktopDir = 0;
1656 if (!create_directories(desktopPath))
1658 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1659 ret = FALSE;
1660 goto end;
1662 *desktopDir = '/';
1663 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon, wmclass))
1665 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1666 ret = FALSE;
1667 goto end;
1670 filename = heap_printf("wine/%s.desktop", link);
1671 if (!filename || !write_menu_file(unix_link, filename))
1673 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1674 ret = FALSE;
1677 end:
1678 HeapFree(GetProcessHeap(), 0, desktopPath);
1679 HeapFree(GetProcessHeap(), 0, filename);
1680 return ret;
1683 /* This escapes reserved characters in .desktop files' Exec keys. */
1684 static LPSTR escape(LPCWSTR arg)
1686 int i, j;
1687 WCHAR *escaped_string;
1688 char *utf8_string;
1690 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1691 if (escaped_string == NULL) return NULL;
1692 for (i = j = 0; arg[i]; i++)
1694 switch (arg[i])
1696 case '\\':
1697 escaped_string[j++] = '\\';
1698 escaped_string[j++] = '\\';
1699 escaped_string[j++] = '\\';
1700 escaped_string[j++] = '\\';
1701 break;
1702 case ' ':
1703 case '\t':
1704 case '\n':
1705 case '"':
1706 case '\'':
1707 case '>':
1708 case '<':
1709 case '~':
1710 case '|':
1711 case '&':
1712 case ';':
1713 case '$':
1714 case '*':
1715 case '?':
1716 case '#':
1717 case '(':
1718 case ')':
1719 case '`':
1720 escaped_string[j++] = '\\';
1721 escaped_string[j++] = '\\';
1722 /* fall through */
1723 default:
1724 escaped_string[j++] = arg[i];
1725 break;
1728 escaped_string[j] = 0;
1730 utf8_string = wchars_to_utf8_chars(escaped_string);
1731 if (utf8_string == NULL)
1733 WINE_ERR("out of memory\n");
1734 goto end;
1737 end:
1738 HeapFree(GetProcessHeap(), 0, escaped_string);
1739 return utf8_string;
1742 /* Return a heap-allocated copy of the unix format difference between the two
1743 * Windows-format paths.
1744 * locn is the owning location
1745 * link is within locn
1747 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1749 char *unix_locn, *unix_link;
1750 char *relative = NULL;
1752 unix_locn = wine_get_unix_file_name(locn);
1753 unix_link = wine_get_unix_file_name(link);
1754 if (unix_locn && unix_link)
1756 size_t len_unix_locn, len_unix_link;
1757 len_unix_locn = strlen (unix_locn);
1758 len_unix_link = strlen (unix_link);
1759 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1761 size_t len_rel;
1762 char *p = strrchr (unix_link + len_unix_locn, '/');
1763 p = strrchr (p, '.');
1764 if (p)
1766 *p = '\0';
1767 len_unix_link = p - unix_link;
1769 len_rel = len_unix_link - len_unix_locn;
1770 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1771 if (relative)
1773 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1777 if (!relative)
1778 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1779 HeapFree(GetProcessHeap(), 0, unix_locn);
1780 HeapFree(GetProcessHeap(), 0, unix_link);
1781 return relative;
1784 /***********************************************************************
1786 * GetLinkLocation
1788 * returns TRUE if successful
1789 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1790 * *relative will contain the address of a heap-allocated copy of the portion
1791 * of the filename that is within the specified location, in unix form
1793 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1795 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1796 DWORD len, i, r, filelen;
1797 const DWORD locations[] = {
1798 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1799 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1800 CSIDL_COMMON_STARTMENU };
1802 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1803 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1804 if (filelen==0 || filelen>MAX_PATH)
1805 return FALSE;
1807 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1809 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1810 * expand or our hardcoded list won't match.
1812 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1813 if (filelen==0 || filelen>MAX_PATH)
1814 return FALSE;
1816 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1818 for( i=0; i<ARRAY_SIZE( locations ); i++ )
1820 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1821 continue;
1823 len = lstrlenW(buffer);
1824 if (len >= MAX_PATH)
1825 continue; /* We've just trashed memory! Hopefully we are OK */
1827 if (len > filelen || filename[len]!='\\')
1828 continue;
1829 /* do a lstrcmpinW */
1830 filename[len] = 0;
1831 r = lstrcmpiW( filename, buffer );
1832 filename[len] = '\\';
1833 if ( r )
1834 continue;
1836 /* return the remainder of the string and link type */
1837 *loc = locations[i];
1838 *relative = relative_path (filename, buffer);
1839 return (*relative != NULL);
1842 return FALSE;
1845 /* gets the target path directly or through MSI */
1846 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1847 LPWSTR szArgs, DWORD argsSize)
1849 IShellLinkDataList *dl = NULL;
1850 EXP_DARWIN_LINK *dar = NULL;
1851 HRESULT hr;
1853 szPath[0] = 0;
1854 szArgs[0] = 0;
1856 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1857 if (hr == S_OK && szPath[0])
1859 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1860 return hr;
1863 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1864 if (FAILED(hr))
1865 return hr;
1867 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1868 if (SUCCEEDED(hr))
1870 WCHAR* szCmdline;
1871 DWORD cmdSize;
1873 cmdSize=0;
1874 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1875 if (hr == ERROR_SUCCESS)
1877 cmdSize++;
1878 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1879 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1880 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1881 if (hr == ERROR_SUCCESS)
1883 WCHAR *s, *d;
1884 int bcount = 0;
1885 BOOL in_quotes = FALSE;
1887 /* Extract the application path */
1888 s=szCmdline;
1889 d=szPath;
1890 while (*s)
1892 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1894 /* skip the remaining spaces */
1895 do {
1896 s++;
1897 } while (*s==0x0009 || *s==0x0020);
1898 break;
1900 else if (*s==0x005c)
1902 /* '\\' */
1903 *d++=*s++;
1904 bcount++;
1906 else if (*s==0x0022)
1908 /* '"' */
1909 if ((bcount & 1)==0)
1911 /* Preceded by an even number of '\', this is
1912 * half that number of '\', plus a quote which
1913 * we erase.
1915 d-=bcount/2;
1916 in_quotes=!in_quotes;
1917 s++;
1919 else
1921 /* Preceded by an odd number of '\', this is
1922 * half that number of '\' followed by a '"'
1924 d=d-bcount/2-1;
1925 *d++='"';
1926 s++;
1928 bcount=0;
1930 else
1932 /* a regular character */
1933 *d++=*s++;
1934 bcount=0;
1936 if ((d-szPath) == pathSize)
1938 /* Keep processing the path till we get to the
1939 * arguments, but 'stand still'
1941 d--;
1944 /* Close the application path */
1945 *d=0;
1947 lstrcpynW(szArgs, s, argsSize);
1949 HeapFree( GetProcessHeap(), 0, szCmdline );
1951 LocalFree( dar );
1954 IShellLinkDataList_Release( dl );
1955 return hr;
1958 static char *slashes_to_minuses(const char *string)
1960 int i;
1961 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1962 if (ret)
1964 for (i = 0; string[i]; i++)
1966 if (string[i] == '/')
1967 ret[i] = '-';
1968 else
1969 ret[i] = string[i];
1971 ret[i] = 0;
1972 return ret;
1974 return NULL;
1977 static BOOL next_line(FILE *file, char **line, int *size)
1979 int pos = 0;
1980 char *cr;
1981 if (*line == NULL)
1983 *size = 4096;
1984 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1986 while (*line != NULL)
1988 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1990 HeapFree(GetProcessHeap(), 0, *line);
1991 *line = NULL;
1992 if (feof(file))
1993 return TRUE;
1994 return FALSE;
1996 pos = strlen(*line);
1997 cr = strchr(*line, '\n');
1998 if (cr == NULL)
2000 char *line2;
2001 (*size) *= 2;
2002 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
2003 if (line2)
2004 *line = line2;
2005 else
2007 HeapFree(GetProcessHeap(), 0, *line);
2008 *line = NULL;
2011 else
2013 *cr = 0;
2014 return TRUE;
2017 return FALSE;
2020 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
2022 char *globs_filename = NULL;
2023 BOOL ret = TRUE;
2024 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
2025 if (globs_filename)
2027 FILE *globs_file = fopen(globs_filename, "r");
2028 if (globs_file) /* doesn't have to exist */
2030 char *line = NULL;
2031 int size = 0;
2032 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
2034 char *pos;
2035 struct xdg_mime_type *mime_type_entry = NULL;
2036 if (line[0] != '#' && (pos = strchr(line, ':')))
2038 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
2039 if (mime_type_entry)
2041 *pos = 0;
2042 mime_type_entry->mimeType = strdupA(line);
2043 mime_type_entry->glob = strdupA(pos + 1);
2044 mime_type_entry->lower_glob = strdupA(pos + 1);
2045 if (mime_type_entry->lower_glob)
2047 char *l;
2048 for (l = mime_type_entry->lower_glob; *l; l++)
2049 *l = tolower(*l);
2051 if (mime_type_entry->mimeType && mime_type_entry->glob && mime_type_entry->lower_glob)
2052 list_add_tail(mime_types, &mime_type_entry->entry);
2053 else
2055 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2056 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2057 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2058 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2059 ret = FALSE;
2062 else
2063 ret = FALSE;
2066 HeapFree(GetProcessHeap(), 0, line);
2067 fclose(globs_file);
2069 HeapFree(GetProcessHeap(), 0, globs_filename);
2071 else
2072 ret = FALSE;
2073 return ret;
2076 static void free_native_mime_types(struct list *native_mime_types)
2078 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
2080 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
2082 list_remove(&mime_type_entry->entry);
2083 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2084 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2085 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2086 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2090 static BOOL build_native_mime_types(const char *xdg_data_home, struct list *mime_types)
2092 char *xdg_data_dirs;
2093 BOOL ret;
2095 xdg_data_dirs = getenv("XDG_DATA_DIRS");
2096 if (xdg_data_dirs == NULL)
2097 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
2098 else
2099 xdg_data_dirs = strdupA(xdg_data_dirs);
2101 if (xdg_data_dirs)
2103 const char *begin;
2104 char *end;
2106 ret = add_mimes(xdg_data_home, mime_types);
2107 if (ret)
2109 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
2111 *end = '\0';
2112 ret = add_mimes(begin, mime_types);
2113 *end = ':';
2114 if (!ret)
2115 break;
2117 if (ret)
2118 ret = add_mimes(begin, mime_types);
2120 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
2122 else
2123 ret = FALSE;
2124 if (!ret)
2125 free_native_mime_types(mime_types);
2126 return ret;
2129 static BOOL match_glob(struct list *native_mime_types, const char *extension,
2130 int ignoreGlobCase, char **match)
2132 #ifdef HAVE_FNMATCH
2133 struct xdg_mime_type *mime_type_entry;
2134 int matchLength = 0;
2136 *match = NULL;
2138 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
2140 const char *glob = ignoreGlobCase ? mime_type_entry->lower_glob : mime_type_entry->glob;
2141 if (fnmatch(glob, extension, 0) == 0)
2143 if (*match == NULL || matchLength < strlen(glob))
2145 *match = mime_type_entry->mimeType;
2146 matchLength = strlen(glob);
2151 if (*match != NULL)
2153 *match = strdupA(*match);
2154 if (*match == NULL)
2155 return FALSE;
2157 #else
2158 *match = NULL;
2159 #endif
2160 return TRUE;
2163 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
2164 const char *extensionA,
2165 LPCWSTR extensionW,
2166 char **mime_type)
2168 WCHAR *lower_extensionW;
2169 INT len;
2170 BOOL ret = match_glob(native_mime_types, extensionA, 0, mime_type);
2171 if (ret == FALSE || *mime_type != NULL)
2172 return ret;
2173 len = strlenW(extensionW);
2174 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
2175 if (lower_extensionW)
2177 char *lower_extensionA;
2178 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
2179 strlwrW(lower_extensionW);
2180 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
2181 if (lower_extensionA)
2183 ret = match_glob(native_mime_types, lower_extensionA, 1, mime_type);
2184 HeapFree(GetProcessHeap(), 0, lower_extensionA);
2186 else
2188 ret = FALSE;
2189 WINE_FIXME("out of memory\n");
2191 HeapFree(GetProcessHeap(), 0, lower_extensionW);
2193 else
2195 ret = FALSE;
2196 WINE_FIXME("out of memory\n");
2198 return ret;
2201 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
2203 DWORD size;
2204 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
2206 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
2207 if (ret)
2209 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
2210 return ret;
2212 HeapFree(GetProcessHeap(), 0, ret);
2214 return NULL;
2217 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
2219 WCHAR *valW = reg_get_valW(key, subkey, name);
2220 if (valW)
2222 char *val = wchars_to_utf8_chars(valW);
2223 HeapFree(GetProcessHeap(), 0, valW);
2224 return val;
2226 return NULL;
2229 static HKEY open_associations_reg_key(void)
2231 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
2232 '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};
2233 HKEY assocKey;
2234 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
2235 return assocKey;
2236 return NULL;
2239 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
2240 LPCSTR appName, LPCSTR openWithIcon)
2242 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2243 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2244 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2245 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2246 HKEY assocKey;
2247 BOOL ret;
2249 if ((assocKey = open_associations_reg_key()))
2251 CHAR *valueA;
2252 WCHAR *value;
2254 ret = FALSE;
2256 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
2257 if (!valueA || lstrcmpA(valueA, mimeType))
2258 ret = TRUE;
2259 HeapFree(GetProcessHeap(), 0, valueA);
2261 value = reg_get_valW(assocKey, extensionW, ProgIDW);
2262 if (!value || strcmpW(value, progId))
2263 ret = TRUE;
2264 HeapFree(GetProcessHeap(), 0, value);
2266 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2267 if (!valueA || lstrcmpA(valueA, appName))
2268 ret = TRUE;
2269 HeapFree(GetProcessHeap(), 0, valueA);
2271 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
2272 if ((openWithIcon && !valueA) ||
2273 (!openWithIcon && valueA) ||
2274 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
2275 ret = TRUE;
2276 HeapFree(GetProcessHeap(), 0, valueA);
2278 RegCloseKey(assocKey);
2280 else
2282 WINE_ERR("error opening associations registry key\n");
2283 ret = FALSE;
2285 return ret;
2288 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2289 LPCSTR appName, LPCSTR desktopFile, LPCSTR openWithIcon)
2291 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2292 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2293 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2294 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2295 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2296 HKEY assocKey = NULL;
2297 HKEY subkey = NULL;
2298 WCHAR *mimeTypeW = NULL;
2299 WCHAR *appNameW = NULL;
2300 WCHAR *desktopFileW = NULL;
2301 WCHAR *openWithIconW = NULL;
2303 assocKey = open_associations_reg_key();
2304 if (assocKey == NULL)
2306 WINE_ERR("could not open file associations key\n");
2307 goto done;
2310 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2312 WINE_ERR("could not create extension subkey\n");
2313 goto done;
2316 mimeTypeW = utf8_chars_to_wchars(mimeType);
2317 if (mimeTypeW == NULL)
2319 WINE_ERR("out of memory\n");
2320 goto done;
2323 appNameW = utf8_chars_to_wchars(appName);
2324 if (appNameW == NULL)
2326 WINE_ERR("out of memory\n");
2327 goto done;
2330 desktopFileW = utf8_chars_to_wchars(desktopFile);
2331 if (desktopFileW == NULL)
2333 WINE_ERR("out of memory\n");
2334 goto done;
2337 if (openWithIcon)
2339 openWithIconW = utf8_chars_to_wchars(openWithIcon);
2340 if (openWithIconW == NULL)
2342 WINE_ERR("out of memory\n");
2343 goto done;
2347 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2348 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2349 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2350 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2351 if (openWithIcon)
2352 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
2353 else
2354 RegDeleteValueW(subkey, OpenWithIconW);
2356 done:
2357 RegCloseKey(assocKey);
2358 RegCloseKey(subkey);
2359 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2360 HeapFree(GetProcessHeap(), 0, appNameW);
2361 HeapFree(GetProcessHeap(), 0, desktopFileW);
2362 HeapFree(GetProcessHeap(), 0, openWithIconW);
2365 static BOOL cleanup_associations(void)
2367 static const WCHAR openW[] = {'o','p','e','n',0};
2368 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2369 HKEY assocKey;
2370 BOOL hasChanged = FALSE;
2371 if ((assocKey = open_associations_reg_key()))
2373 int i;
2374 BOOL done = FALSE;
2375 for (i = 0; !done;)
2377 WCHAR *extensionW = NULL;
2378 DWORD size = 1024;
2379 LSTATUS ret;
2383 HeapFree(GetProcessHeap(), 0, extensionW);
2384 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2385 if (extensionW == NULL)
2387 WINE_ERR("out of memory\n");
2388 ret = ERROR_OUTOFMEMORY;
2389 break;
2391 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2392 size *= 2;
2393 } while (ret == ERROR_MORE_DATA);
2395 if (ret == ERROR_SUCCESS)
2397 WCHAR *command;
2398 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2399 if (command == NULL)
2401 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2402 if (desktopFile)
2404 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2405 remove(desktopFile);
2407 RegDeleteKeyW(assocKey, extensionW);
2408 hasChanged = TRUE;
2409 HeapFree(GetProcessHeap(), 0, desktopFile);
2411 else
2412 i++;
2413 HeapFree(GetProcessHeap(), 0, command);
2415 else
2417 if (ret != ERROR_NO_MORE_ITEMS)
2418 WINE_ERR("error %d while reading registry\n", ret);
2419 done = TRUE;
2421 HeapFree(GetProcessHeap(), 0, extensionW);
2423 RegCloseKey(assocKey);
2425 else
2426 WINE_ERR("could not open file associations key\n");
2427 return hasChanged;
2430 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2431 const char *mime_type, const char *comment)
2433 BOOL ret = FALSE;
2434 char *filename;
2436 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2437 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2439 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2440 if (filename)
2442 FILE *packageFile = fopen(filename, "w");
2443 if (packageFile)
2445 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2446 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2447 fprintf(packageFile, " <mime-type type=\"");
2448 write_xml_text(packageFile, mime_type);
2449 fprintf(packageFile, "\">\n");
2450 fprintf(packageFile, " <glob pattern=\"*");
2451 write_xml_text(packageFile, dot_extension);
2452 fprintf(packageFile, "\"/>\n");
2453 if (comment)
2455 fprintf(packageFile, " <comment>");
2456 write_xml_text(packageFile, comment);
2457 fprintf(packageFile, "</comment>\n");
2459 fprintf(packageFile, " </mime-type>\n");
2460 fprintf(packageFile, "</mime-info>\n");
2461 ret = TRUE;
2462 fclose(packageFile);
2464 else
2465 WINE_ERR("error writing file %s\n", filename);
2466 HeapFree(GetProcessHeap(), 0, filename);
2468 else
2469 WINE_ERR("out of memory\n");
2470 return ret;
2473 static BOOL is_extension_banned(LPCWSTR extension)
2475 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2476 static const WCHAR comW[] = {'.','c','o','m',0};
2477 static const WCHAR exeW[] = {'.','e','x','e',0};
2478 static const WCHAR msiW[] = {'.','m','s','i',0};
2480 if (!strcmpiW(extension, comW) ||
2481 !strcmpiW(extension, exeW) ||
2482 !strcmpiW(extension, msiW))
2483 return TRUE;
2484 return FALSE;
2487 static const char* get_special_mime_type(LPCWSTR extension)
2489 static const WCHAR lnkW[] = {'.','l','n','k',0};
2490 if (!strcmpiW(extension, lnkW))
2491 return "application/x-ms-shortcut";
2492 return NULL;
2495 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2496 const char *friendlyAppName, const char *mimeType,
2497 const char *progId, const char *openWithIcon)
2499 BOOL ret = FALSE;
2500 FILE *desktop;
2501 const char *prefix = getenv("WINEPREFIX");
2502 const char *home = getenv("HOME");
2504 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2505 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2506 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2508 desktop = fopen(desktopPath, "w");
2509 if (desktop)
2511 fprintf(desktop, "[Desktop Entry]\n");
2512 fprintf(desktop, "Type=Application\n");
2513 fprintf(desktop, "Name=%s\n", friendlyAppName);
2514 fprintf(desktop, "MimeType=%s;\n", mimeType);
2515 if (prefix)
2516 fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", prefix, progId);
2517 else if (home)
2518 fprintf(desktop, "Exec=env WINEPREFIX=\"%s/.wine\" wine start /ProgIDOpen %s %%f\n", home, progId);
2519 else
2520 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
2521 fprintf(desktop, "NoDisplay=true\n");
2522 fprintf(desktop, "StartupNotify=true\n");
2523 if (openWithIcon)
2524 fprintf(desktop, "Icon=%s\n", openWithIcon);
2525 ret = TRUE;
2526 fclose(desktop);
2528 else
2529 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2530 return ret;
2533 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2535 static const WCHAR openW[] = {'o','p','e','n',0};
2536 struct wine_rb_tree mimeProgidTree = { winemenubuilder_rb_string_compare };
2537 struct list nativeMimeTypes = LIST_INIT(nativeMimeTypes);
2538 LSTATUS ret = 0;
2539 int i;
2540 BOOL hasChanged = FALSE;
2542 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2544 WINE_ERR("could not build native MIME types\n");
2545 return FALSE;
2548 for (i = 0; ; i++)
2550 WCHAR *extensionW = NULL;
2551 DWORD size = 1024;
2555 HeapFree(GetProcessHeap(), 0, extensionW);
2556 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2557 if (extensionW == NULL)
2559 WINE_ERR("out of memory\n");
2560 ret = ERROR_OUTOFMEMORY;
2561 break;
2563 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2564 size *= 2;
2565 } while (ret == ERROR_MORE_DATA);
2567 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_banned(extensionW))
2569 char *extensionA = NULL;
2570 WCHAR *commandW = NULL;
2571 WCHAR *executableW = NULL;
2572 char *openWithIconA = NULL;
2573 WCHAR *friendlyDocNameW = NULL;
2574 char *friendlyDocNameA = NULL;
2575 WCHAR *iconW = NULL;
2576 char *iconA = NULL;
2577 WCHAR *contentTypeW = NULL;
2578 char *mimeTypeA = NULL;
2579 WCHAR *friendlyAppNameW = NULL;
2580 char *friendlyAppNameA = NULL;
2581 WCHAR *progIdW = NULL;
2582 char *progIdA = NULL;
2583 char *mimeProgId = NULL;
2585 extensionA = wchars_to_utf8_chars(strlwrW(extensionW));
2586 if (extensionA == NULL)
2588 WINE_ERR("out of memory\n");
2589 goto end;
2592 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2593 if (friendlyDocNameW)
2595 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2596 if (friendlyDocNameA == NULL)
2598 WINE_ERR("out of memory\n");
2599 goto end;
2603 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2605 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2606 if (contentTypeW)
2607 strlwrW(contentTypeW);
2609 if (!freedesktop_mime_type_for_extension(&nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2610 goto end;
2612 if (mimeTypeA == NULL)
2614 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2615 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2616 else if ((get_special_mime_type(extensionW)))
2617 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2618 else
2619 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2621 if (mimeTypeA != NULL)
2623 /* GNOME seems to ignore the <icon> tag in MIME packages,
2624 * and the default name is more intuitive anyway.
2626 if (iconW)
2628 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2629 if (flattened_mime)
2631 int index = 0;
2632 WCHAR *comma = strrchrW(iconW, ',');
2633 if (comma)
2635 *comma = 0;
2636 index = atoiW(comma + 1);
2638 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2639 HeapFree(GetProcessHeap(), 0, flattened_mime);
2643 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2644 hasChanged = TRUE;
2646 else
2648 WINE_FIXME("out of memory\n");
2649 goto end;
2653 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2654 if (commandW == NULL)
2655 /* no command => no application is associated */
2656 goto end;
2658 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2659 if (executableW)
2660 openWithIconA = compute_native_identifier(0, executableW);
2662 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, openW);
2663 if (friendlyAppNameW)
2665 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2666 if (friendlyAppNameA == NULL)
2668 WINE_ERR("out of memory\n");
2669 goto end;
2672 else
2674 friendlyAppNameA = heap_printf("A Wine application");
2675 if (friendlyAppNameA == NULL)
2677 WINE_ERR("out of memory\n");
2678 goto end;
2682 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2683 if (progIdW)
2685 progIdA = escape(progIdW);
2686 if (progIdA == NULL)
2688 WINE_ERR("out of memory\n");
2689 goto end;
2692 else
2693 goto end; /* no progID => not a file type association */
2695 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2696 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2697 if (mimeProgId)
2699 struct rb_string_entry *entry;
2700 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2702 HeapFree(GetProcessHeap(), 0, mimeProgId);
2703 goto end;
2705 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2706 if (!entry)
2708 WINE_ERR("out of memory allocating rb_string_entry\n");
2709 goto end;
2711 entry->string = mimeProgId;
2712 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2714 WINE_ERR("error updating rb tree\n");
2715 goto end;
2719 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, openWithIconA))
2721 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2722 if (desktopPath)
2724 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2726 hasChanged = TRUE;
2727 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, desktopPath, openWithIconA);
2729 HeapFree(GetProcessHeap(), 0, desktopPath);
2733 if (hasChanged && openWithIconA)
2735 char *outputIconA = extract_icon(executableW, 0, openWithIconA, FALSE);
2736 HeapFree(GetProcessHeap(), 0, outputIconA);
2739 end:
2740 HeapFree(GetProcessHeap(), 0, extensionA);
2741 HeapFree(GetProcessHeap(), 0, commandW);
2742 HeapFree(GetProcessHeap(), 0, executableW);
2743 HeapFree(GetProcessHeap(), 0, openWithIconA);
2744 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2745 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2746 HeapFree(GetProcessHeap(), 0, iconW);
2747 HeapFree(GetProcessHeap(), 0, iconA);
2748 HeapFree(GetProcessHeap(), 0, contentTypeW);
2749 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2750 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2751 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2752 HeapFree(GetProcessHeap(), 0, progIdW);
2753 HeapFree(GetProcessHeap(), 0, progIdA);
2755 HeapFree(GetProcessHeap(), 0, extensionW);
2756 if (ret != ERROR_SUCCESS)
2757 break;
2760 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2761 free_native_mime_types(&nativeMimeTypes);
2762 return hasChanged;
2765 static char *get_start_exe_path(void)
2767 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2768 '\\','s','t','a','r','t','.','e','x','e',0};
2769 WCHAR start_path[MAX_PATH];
2770 GetWindowsDirectoryW(start_path, MAX_PATH);
2771 lstrcatW(start_path, startW);
2772 return escape(start_path);
2775 static char* escape_unix_link_arg(LPCSTR unix_link)
2777 char *ret = NULL;
2778 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2779 if (unix_linkW)
2781 char *escaped_lnk = escape(unix_linkW);
2782 if (escaped_lnk)
2784 ret = heap_printf("/Unix %s", escaped_lnk);
2785 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2787 HeapFree(GetProcessHeap(), 0, unix_linkW);
2789 return ret;
2792 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2794 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2795 '\\','s','t','a','r','t','.','e','x','e',0};
2796 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2797 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2798 char *wmclass = NULL;
2799 WCHAR szTmp[INFOTIPSIZE];
2800 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2801 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH], szWMClass[MAX_PATH];
2802 int iIconId = 0, r = -1;
2803 DWORD csidl = -1;
2804 HANDLE hsem = NULL;
2805 char *unix_link = NULL;
2806 char *start_path = NULL;
2808 if ( !link )
2810 WINE_ERR("Link name is null\n");
2811 return FALSE;
2814 if( !GetLinkLocation( link, &csidl, &link_name ) )
2816 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2817 return TRUE;
2819 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2821 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2822 return TRUE;
2824 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2826 szTmp[0] = 0;
2827 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2828 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2829 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2831 szTmp[0] = 0;
2832 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2833 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2834 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2836 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2837 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2838 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2839 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2841 szTmp[0] = 0;
2842 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2843 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2844 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2846 szWMClass[0] = 0;
2848 if( !szPath[0] )
2850 LPITEMIDLIST pidl = NULL;
2851 IShellLinkW_GetIDList( sl, &pidl );
2852 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2853 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2856 /* extract the icon */
2857 if( szIconPath[0] )
2858 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2859 else
2860 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2862 /* fail - try once again after parent process exit */
2863 if( !icon_name )
2865 if (bWait)
2867 WINE_WARN("Unable to extract icon, deferring.\n");
2868 goto cleanup;
2870 WINE_ERR("failed to extract icon from %s\n",
2871 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2874 unix_link = wine_get_unix_file_name(link);
2875 if (unix_link == NULL)
2877 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2878 goto cleanup;
2881 /* check the path */
2882 if( szPath[0] )
2884 static const WCHAR exeW[] = {'.','e','x','e',0};
2885 WCHAR *p;
2887 /* check for .exe extension */
2888 if (!(p = strrchrW( szPath, '.' )) ||
2889 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2890 lstrcmpiW( p, exeW ))
2892 /* Not .exe - use 'start.exe' to launch this file */
2893 p = szArgs + lstrlenW(szPath) + 2;
2894 if (szArgs[0])
2896 p[0] = ' ';
2897 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2898 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2900 else
2901 p[0] = 0;
2903 szArgs[0] = '"';
2904 lstrcpyW(szArgs + 1, szPath);
2905 szArgs[lstrlenW(szArgs)] = '"';
2907 GetWindowsDirectoryW(szPath, MAX_PATH);
2908 lstrcatW(szPath, startW);
2910 else
2912 /* FIXME: Use AppUserModelID if present. */
2913 WCHAR *p = PathFindFileNameW(szPath);
2915 lstrcpyW(szWMClass, p);
2916 CharLowerW(szWMClass);
2919 /* convert app working dir */
2920 if (szWorkDir[0])
2921 work_dir = wine_get_unix_file_name( szWorkDir );
2923 else
2925 /* if there's no path... try run the link itself */
2926 lstrcpynW(szArgs, link, MAX_PATH);
2927 GetWindowsDirectoryW(szPath, MAX_PATH);
2928 lstrcatW(szPath, startW);
2931 /* escape the path and parameters */
2932 escaped_path = escape(szPath);
2933 escaped_args = escape(szArgs);
2934 description = wchars_to_utf8_chars(szDescription);
2935 wmclass = wchars_to_utf8_chars(szWMClass);
2936 if (escaped_path == NULL || escaped_args == NULL || description == NULL || wmclass == NULL)
2938 WINE_ERR("out of memory allocating/escaping parameters\n");
2939 goto cleanup;
2942 start_path = get_start_exe_path();
2943 if (start_path == NULL)
2945 WINE_ERR("out of memory\n");
2946 goto cleanup;
2949 /* building multiple menus concurrently has race conditions */
2950 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2951 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2953 WINE_ERR("failed wait for semaphore\n");
2954 goto cleanup;
2957 if (in_desktop_dir(csidl))
2959 char *location;
2960 const char *lastEntry;
2961 lastEntry = strrchr(link_name, '/');
2962 if (lastEntry == NULL)
2963 lastEntry = link_name;
2964 else
2965 ++lastEntry;
2966 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2967 if (location)
2969 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2971 char *link_arg = escape_unix_link_arg(unix_link);
2972 if (link_arg)
2974 r = !write_desktop_entry(unix_link, location, lastEntry,
2975 start_path, link_arg, description, work_dir, icon_name, wmclass);
2976 HeapFree(GetProcessHeap(), 0, link_arg);
2979 else
2980 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name, wmclass);
2981 if (r == 0)
2982 chmod(location, 0755);
2983 HeapFree(GetProcessHeap(), 0, location);
2986 else
2988 char *link_arg = escape_unix_link_arg(unix_link);
2989 if (link_arg)
2991 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name, wmclass);
2992 HeapFree(GetProcessHeap(), 0, link_arg);
2996 ReleaseSemaphore( hsem, 1, NULL );
2998 cleanup:
2999 if (hsem) CloseHandle( hsem );
3000 HeapFree( GetProcessHeap(), 0, icon_name );
3001 HeapFree( GetProcessHeap(), 0, work_dir );
3002 HeapFree( GetProcessHeap(), 0, link_name );
3003 HeapFree( GetProcessHeap(), 0, escaped_args );
3004 HeapFree( GetProcessHeap(), 0, escaped_path );
3005 HeapFree( GetProcessHeap(), 0, description );
3006 HeapFree( GetProcessHeap(), 0, wmclass );
3007 HeapFree( GetProcessHeap(), 0, unix_link );
3008 HeapFree( GetProcessHeap(), 0, start_path );
3010 if (r && !bWait)
3011 WINE_ERR("failed to build the menu\n" );
3013 return ( r == 0 );
3016 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
3018 char *link_name = NULL, *icon_name = NULL;
3019 DWORD csidl = -1;
3020 LPWSTR urlPath = NULL;
3021 char *escaped_urlPath = NULL;
3022 HRESULT hr;
3023 HANDLE hSem = NULL;
3024 BOOL ret = TRUE;
3025 int r = -1;
3026 char *unix_link = NULL;
3027 IPropertySetStorage *pPropSetStg;
3028 IPropertyStorage *pPropStg;
3029 PROPSPEC ps[2];
3030 PROPVARIANT pv[2];
3031 char *start_path = NULL;
3032 BOOL has_icon = FALSE;
3034 if ( !link )
3036 WINE_ERR("Link name is null\n");
3037 return TRUE;
3040 if( !GetLinkLocation( link, &csidl, &link_name ) )
3042 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
3043 return TRUE;
3045 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
3047 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3048 ret = TRUE;
3049 goto cleanup;
3051 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
3053 hr = url->lpVtbl->GetURL(url, &urlPath);
3054 if (FAILED(hr))
3056 ret = TRUE;
3057 goto cleanup;
3059 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
3061 unix_link = wine_get_unix_file_name(link);
3062 if (unix_link == NULL)
3064 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
3065 goto cleanup;
3068 escaped_urlPath = escape(urlPath);
3069 if (escaped_urlPath == NULL)
3071 WINE_ERR("couldn't escape url, out of memory\n");
3072 goto cleanup;
3075 start_path = get_start_exe_path();
3076 if (start_path == NULL)
3078 WINE_ERR("out of memory\n");
3079 goto cleanup;
3082 ps[0].ulKind = PRSPEC_PROPID;
3083 ps[0].u.propid = PID_IS_ICONFILE;
3084 ps[1].ulKind = PRSPEC_PROPID;
3085 ps[1].u.propid = PID_IS_ICONINDEX;
3087 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
3088 if (SUCCEEDED(hr))
3090 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
3091 if (SUCCEEDED(hr))
3093 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
3094 if (SUCCEEDED(hr))
3096 if (pv[0].vt == VT_LPWSTR && pv[0].pwszVal && pv[0].pwszVal[0])
3098 has_icon = TRUE;
3099 icon_name = extract_icon( pv[0].pwszVal, pv[1].iVal, NULL, bWait );
3101 WINE_TRACE("URL icon path: %s icon index: %d icon name: %s\n", wine_dbgstr_w(pv[0].pwszVal), pv[1].iVal, icon_name);
3103 PropVariantClear(&pv[0]);
3104 PropVariantClear(&pv[1]);
3106 IPropertyStorage_Release(pPropStg);
3108 IPropertySetStorage_Release(pPropSetStg);
3111 /* fail - try once again after parent process exit */
3112 if( has_icon && !icon_name )
3114 if (bWait)
3116 WINE_WARN("Unable to extract icon, deferring.\n");
3117 ret = FALSE;
3118 goto cleanup;
3120 WINE_ERR("failed to extract icon from %s\n",
3121 wine_dbgstr_w( pv[0].pwszVal ));
3124 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3125 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3127 WINE_ERR("failed wait for semaphore\n");
3128 goto cleanup;
3130 if (in_desktop_dir(csidl))
3132 char *location;
3133 const char *lastEntry;
3134 lastEntry = strrchr(link_name, '/');
3135 if (lastEntry == NULL)
3136 lastEntry = link_name;
3137 else
3138 ++lastEntry;
3139 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
3140 if (location)
3142 r = !write_desktop_entry(NULL, location, lastEntry, start_path, escaped_urlPath, NULL, NULL, icon_name, NULL);
3143 if (r == 0)
3144 chmod(location, 0755);
3145 HeapFree(GetProcessHeap(), 0, location);
3148 else
3149 r = !write_menu_entry(unix_link, link_name, start_path, escaped_urlPath, NULL, NULL, icon_name, NULL);
3150 ret = (r == 0);
3151 ReleaseSemaphore(hSem, 1, NULL);
3153 cleanup:
3154 if (hSem)
3155 CloseHandle(hSem);
3156 HeapFree( GetProcessHeap(), 0, icon_name );
3157 HeapFree(GetProcessHeap(), 0, link_name);
3158 CoTaskMemFree( urlPath );
3159 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
3160 HeapFree(GetProcessHeap(), 0, unix_link);
3161 return ret;
3164 static BOOL WaitForParentProcess( void )
3166 PROCESSENTRY32 procentry;
3167 HANDLE hsnapshot = NULL, hprocess = NULL;
3168 DWORD ourpid = GetCurrentProcessId();
3169 BOOL ret = FALSE, rc;
3171 WINE_TRACE("Waiting for parent process\n");
3172 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
3173 INVALID_HANDLE_VALUE)
3175 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3176 goto done;
3179 procentry.dwSize = sizeof(PROCESSENTRY32);
3180 rc = Process32First( hsnapshot, &procentry );
3181 while (rc)
3183 if (procentry.th32ProcessID == ourpid) break;
3184 rc = Process32Next( hsnapshot, &procentry );
3186 if (!rc)
3188 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
3189 goto done;
3192 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
3193 NULL)
3195 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
3196 GetLastError());
3197 goto done;
3200 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
3201 ret = TRUE;
3202 else
3203 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3205 done:
3206 if (hprocess) CloseHandle( hprocess );
3207 if (hsnapshot) CloseHandle( hsnapshot );
3208 return ret;
3211 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
3213 IShellLinkW *sl;
3214 IPersistFile *pf;
3215 HRESULT r;
3216 WCHAR fullname[MAX_PATH];
3217 DWORD len;
3219 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
3221 if( !linkname[0] )
3223 WINE_ERR("link name missing\n");
3224 return FALSE;
3227 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
3228 if (len==0 || len>MAX_PATH)
3230 WINE_ERR("couldn't get full path of link file\n");
3231 return FALSE;
3234 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3235 &IID_IShellLinkW, (LPVOID *) &sl );
3236 if( FAILED( r ) )
3238 WINE_ERR("No IID_IShellLink\n");
3239 return FALSE;
3242 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
3243 if( FAILED( r ) )
3245 WINE_ERR("No IID_IPersistFile\n");
3246 return FALSE;
3249 r = IPersistFile_Load( pf, fullname, STGM_READ );
3250 if( SUCCEEDED( r ) )
3252 /* If something fails (eg. Couldn't extract icon)
3253 * wait for parent process and try again
3255 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
3257 WaitForParentProcess();
3258 InvokeShellLinker( sl, fullname, FALSE );
3261 else
3263 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
3266 IPersistFile_Release( pf );
3267 IShellLinkW_Release( sl );
3269 return !r;
3272 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
3274 IUniformResourceLocatorW *url;
3275 IPersistFile *pf;
3276 HRESULT r;
3277 WCHAR fullname[MAX_PATH];
3278 DWORD len;
3280 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
3282 if( !urlname[0] )
3284 WINE_ERR("URL name missing\n");
3285 return FALSE;
3288 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
3289 if (len==0 || len>MAX_PATH)
3291 WINE_ERR("couldn't get full path of URL file\n");
3292 return FALSE;
3295 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
3296 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
3297 if( FAILED( r ) )
3299 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3300 return FALSE;
3303 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
3304 if( FAILED( r ) )
3306 WINE_ERR("No IID_IPersistFile\n");
3307 return FALSE;
3309 r = IPersistFile_Load( pf, fullname, STGM_READ );
3310 if( SUCCEEDED( r ) )
3312 /* If something fails (eg. Couldn't extract icon)
3313 * wait for parent process and try again
3315 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
3317 WaitForParentProcess();
3318 InvokeShellLinkerForURL( url, fullname, FALSE );
3322 IPersistFile_Release( pf );
3323 url->lpVtbl->Release( url );
3325 return !r;
3328 static void RefreshFileTypeAssociations(void)
3330 HANDLE hSem = NULL;
3331 char *mime_dir = NULL;
3332 char *packages_dir = NULL;
3333 char *applications_dir = NULL;
3334 BOOL hasChanged;
3336 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3337 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3339 WINE_ERR("failed wait for semaphore\n");
3340 CloseHandle(hSem);
3341 hSem = NULL;
3342 goto end;
3345 mime_dir = heap_printf("%s/mime", xdg_data_dir);
3346 if (mime_dir == NULL)
3348 WINE_ERR("out of memory\n");
3349 goto end;
3351 create_directories(mime_dir);
3353 packages_dir = heap_printf("%s/packages", mime_dir);
3354 if (packages_dir == NULL)
3356 WINE_ERR("out of memory\n");
3357 goto end;
3359 create_directories(packages_dir);
3361 applications_dir = heap_printf("%s/applications", xdg_data_dir);
3362 if (applications_dir == NULL)
3364 WINE_ERR("out of memory\n");
3365 goto end;
3367 create_directories(applications_dir);
3369 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3370 hasChanged |= cleanup_associations();
3371 if (hasChanged)
3373 const char *argv[3];
3375 argv[0] = "update-mime-database";
3376 argv[1] = mime_dir;
3377 argv[2] = NULL;
3378 _spawnvp( _P_DETACH, argv[0], argv );
3380 argv[0] = "update-desktop-database";
3381 argv[1] = applications_dir;
3382 _spawnvp( _P_DETACH, argv[0], argv );
3385 end:
3386 if (hSem)
3388 ReleaseSemaphore(hSem, 1, NULL);
3389 CloseHandle(hSem);
3391 HeapFree(GetProcessHeap(), 0, mime_dir);
3392 HeapFree(GetProcessHeap(), 0, packages_dir);
3393 HeapFree(GetProcessHeap(), 0, applications_dir);
3396 static void cleanup_menus(void)
3398 HKEY hkey;
3400 hkey = open_menus_reg_key();
3401 if (hkey)
3403 int i;
3404 LSTATUS lret = ERROR_SUCCESS;
3405 for (i = 0; lret == ERROR_SUCCESS; )
3407 WCHAR *value = NULL;
3408 WCHAR *data = NULL;
3409 DWORD valueSize = 4096;
3410 DWORD dataSize = 4096;
3411 while (1)
3413 lret = ERROR_OUTOFMEMORY;
3414 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3415 if (value == NULL)
3416 break;
3417 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3418 if (data == NULL)
3419 break;
3420 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3421 if (lret != ERROR_MORE_DATA)
3422 break;
3423 valueSize *= 2;
3424 dataSize *= 2;
3425 HeapFree(GetProcessHeap(), 0, value);
3426 HeapFree(GetProcessHeap(), 0, data);
3427 value = data = NULL;
3429 if (lret == ERROR_SUCCESS)
3431 char *unix_file;
3432 char *windows_file;
3433 unix_file = wchars_to_unix_chars(value);
3434 windows_file = wchars_to_unix_chars(data);
3435 if (unix_file != NULL && windows_file != NULL)
3437 struct stat filestats;
3438 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3440 WINE_TRACE("removing menu related file %s\n", unix_file);
3441 remove(unix_file);
3442 RegDeleteValueW(hkey, value);
3444 else
3445 i++;
3447 else
3449 WINE_ERR("out of memory enumerating menus\n");
3450 lret = ERROR_OUTOFMEMORY;
3452 HeapFree(GetProcessHeap(), 0, unix_file);
3453 HeapFree(GetProcessHeap(), 0, windows_file);
3455 else if (lret != ERROR_NO_MORE_ITEMS)
3456 WINE_ERR("error %d reading registry\n", lret);
3457 HeapFree(GetProcessHeap(), 0, value);
3458 HeapFree(GetProcessHeap(), 0, data);
3460 RegCloseKey(hkey);
3462 else
3463 WINE_ERR("error opening registry key, menu cleanup failed\n");
3466 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3468 char *utf8lnkPath = NULL;
3469 char *utf8OutputPath = NULL;
3470 WCHAR *winLnkPath = NULL;
3471 IShellLinkW *shellLink = NULL;
3472 IPersistFile *persistFile = NULL;
3473 WCHAR szTmp[MAX_PATH];
3474 WCHAR szPath[MAX_PATH];
3475 WCHAR szArgs[INFOTIPSIZE];
3476 WCHAR szIconPath[MAX_PATH];
3477 int iconId;
3478 IStream *stream = NULL;
3479 ICONDIRENTRY *pIconDirEntries = NULL;
3480 int numEntries;
3481 HRESULT hr;
3483 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3484 if (utf8lnkPath == NULL)
3486 WINE_ERR("out of memory converting paths\n");
3487 goto end;
3490 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3491 if (utf8OutputPath == NULL)
3493 WINE_ERR("out of memory converting paths\n");
3494 goto end;
3497 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3498 if (winLnkPath == NULL)
3500 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3501 goto end;
3504 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3505 &IID_IShellLinkW, (LPVOID*)&shellLink);
3506 if (FAILED(hr))
3508 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3509 goto end;
3512 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3513 if (FAILED(hr))
3515 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3516 goto end;
3519 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3520 if (FAILED(hr))
3522 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3523 goto end;
3526 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3527 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3528 szTmp[0] = 0;
3529 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3530 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3532 if(!szPath[0])
3534 LPITEMIDLIST pidl = NULL;
3535 IShellLinkW_GetIDList(shellLink, &pidl);
3536 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3537 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3540 if (szIconPath[0])
3542 hr = open_icon(szIconPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3543 if (SUCCEEDED(hr))
3544 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3546 else
3548 hr = open_icon(szPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3549 if (SUCCEEDED(hr))
3550 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3553 end:
3554 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3555 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3556 HeapFree(GetProcessHeap(), 0, winLnkPath);
3557 if (shellLink != NULL)
3558 IShellLinkW_Release(shellLink);
3559 if (persistFile != NULL)
3560 IPersistFile_Release(persistFile);
3561 if (stream != NULL)
3562 IStream_Release(stream);
3563 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
3566 static WCHAR *next_token( LPWSTR *p )
3568 LPWSTR token = NULL, t = *p;
3570 if( !t )
3571 return NULL;
3573 while( t && !token )
3575 switch( *t )
3577 case ' ':
3578 t++;
3579 continue;
3580 case '"':
3581 /* unquote the token */
3582 token = ++t;
3583 t = strchrW( token, '"' );
3584 if( t )
3585 *t++ = 0;
3586 break;
3587 case 0:
3588 t = NULL;
3589 break;
3590 default:
3591 token = t;
3592 t = strchrW( token, ' ' );
3593 if( t )
3594 *t++ = 0;
3595 break;
3598 *p = t;
3599 return token;
3602 static BOOL init_xdg(void)
3604 WCHAR shellDesktopPath[MAX_PATH];
3605 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3606 if (SUCCEEDED(hr))
3607 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3608 if (xdg_desktop_dir == NULL)
3610 WINE_ERR("error looking up the desktop directory\n");
3611 return FALSE;
3614 if (getenv("XDG_CONFIG_HOME"))
3615 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3616 else
3617 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3618 if (xdg_config_dir)
3620 create_directories(xdg_config_dir);
3621 if (getenv("XDG_DATA_HOME"))
3622 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3623 else
3624 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3625 if (xdg_data_dir)
3627 char *buffer;
3628 create_directories(xdg_data_dir);
3629 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3630 if (buffer)
3632 mkdir(buffer, 0777);
3633 HeapFree(GetProcessHeap(), 0, buffer);
3635 return TRUE;
3637 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3639 WINE_ERR("out of memory\n");
3640 return FALSE;
3643 static BOOL associations_enabled(void)
3645 BOOL ret = TRUE;
3646 HKEY hkey;
3647 BYTE buf[32];
3648 DWORD len;
3650 if ((hkey = open_associations_reg_key()))
3652 len = sizeof(buf);
3653 if (!RegQueryValueExA(hkey, "Enable", NULL, NULL, buf, &len))
3654 ret = IS_OPTION_TRUE(buf[0]);
3655 RegCloseKey( hkey );
3658 return ret;
3661 /***********************************************************************
3663 * wWinMain
3665 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3667 static const WCHAR dash_aW[] = {'-','a',0};
3668 static const WCHAR dash_rW[] = {'-','r',0};
3669 static const WCHAR dash_tW[] = {'-','t',0};
3670 static const WCHAR dash_uW[] = {'-','u',0};
3671 static const WCHAR dash_wW[] = {'-','w',0};
3673 LPWSTR token = NULL, p;
3674 BOOL bWait = FALSE;
3675 BOOL bURL = FALSE;
3676 HRESULT hr;
3677 int ret = 0;
3679 if (!init_xdg())
3680 return 1;
3682 hr = CoInitialize(NULL);
3683 if (FAILED(hr))
3685 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3686 return 1;
3689 for( p = cmdline; p && *p; )
3691 token = next_token( &p );
3692 if( !token )
3693 break;
3694 if( !strcmpW( token, dash_aW ) )
3696 if (associations_enabled())
3697 RefreshFileTypeAssociations();
3698 continue;
3700 if( !strcmpW( token, dash_rW ) )
3702 cleanup_menus();
3703 continue;
3705 if( !strcmpW( token, dash_wW ) )
3706 bWait = TRUE;
3707 else if ( !strcmpW( token, dash_uW ) )
3708 bURL = TRUE;
3709 else if ( !strcmpW( token, dash_tW ) )
3711 WCHAR *lnkFile = next_token( &p );
3712 if (lnkFile)
3714 WCHAR *outputFile = next_token( &p );
3715 if (outputFile)
3716 thumbnail_lnk(lnkFile, outputFile);
3719 else if( token[0] == '-' )
3721 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3723 else
3725 BOOL bRet;
3727 if (bURL)
3728 bRet = Process_URL( token, bWait );
3729 else
3730 bRet = Process_Link( token, bWait );
3731 if (!bRet)
3733 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3734 ret = 1;
3739 CoUninitialize();
3740 return ret;