mshtml/tests: Remove null check after dereference (Coverity).
[wine.git] / programs / winemenubuilder / winemenubuilder.c
blob0013b04ceea4e075967dd94aed689fae3a96d9f8
1 /*
2 * Helper program to build unix menu entries
4 * Copyright 1997 Marcus Meissner
5 * Copyright 1998 Juergen Schmied
6 * Copyright 2003 Mike McCormack for CodeWeavers
7 * Copyright 2004 Dmitry Timoshkov
8 * Copyright 2005 Bill Medland
9 * Copyright 2008 Damjan Jovanovic
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 * This program is used to replicate the Windows desktop and start menu
27 * into the native desktop's copies. Desktop entries are merged directly
28 * into the native desktop. The Windows Start Menu corresponds to a Wine
29 * entry within the native "start" menu and replicates the whole tree
30 * structure of the Windows Start Menu. Currently it does not differentiate
31 * between the user's desktop/start menu and the "All Users" copies.
33 * This program will read a Windows shortcut file using the IShellLink
34 * interface, then create a KDE/GNOME menu entry for the shortcut.
36 * winemenubuilder [ -w ] <shortcut.lnk>
38 * If the -w parameter is passed, and the shortcut cannot be created,
39 * this program will wait for the parent process to finish and then try
40 * again. This covers the case when a ShortCut is created before the
41 * executable containing its icon.
43 * TODO
44 * Handle data lnk files. There is no icon in the file; the icon is in
45 * the handler for the file type (or pointed to by the lnk file). Also it
46 * might be better to use a native handler (e.g. a native acroread for pdf
47 * files).
48 * Differentiate between the user's entries and the "All Users" entries.
49 * If it is possible to add the desktop files to the native system's
50 * shared location for an "All Users" entry then do so. As a suggestion the
51 * shared menu Wine base could be writable to the wine group, or a wineadm
52 * group.
53 * Clean up fd.o menu icons and .directory files when the menu is deleted
54 * in Windows.
55 * Associate applications under HKCR\Applications to open any MIME type
56 * (by associating with application/octet-stream, or how?).
57 * Clean up fd.o MIME types when they are deleted in Windows, their icons
58 * too. Very hard - once we associate them with fd.o, we can't tell whether
59 * they are ours or not, and the extension <-> MIME type mapping isn't
60 * one-to-one either.
61 * Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
62 * that write associations there won't associate (#17019).
65 #include "config.h"
66 #include "wine/port.h"
68 #include <ctype.h>
69 #include <stdio.h>
70 #include <string.h>
71 #ifdef HAVE_UNISTD_H
72 #include <unistd.h>
73 #endif
74 #include <errno.h>
75 #include <stdarg.h>
76 #ifdef HAVE_FNMATCH_H
77 #include <fnmatch.h>
78 #endif
80 #define COBJMACROS
81 #define NONAMELESSUNION
83 #include <windows.h>
84 #include <shlobj.h>
85 #include <objidl.h>
86 #include <shlguid.h>
87 #include <appmgmt.h>
88 #include <tlhelp32.h>
89 #include <intshcut.h>
90 #include <shlwapi.h>
91 #include <initguid.h>
92 #include <wincodec.h>
94 #include "wine/unicode.h"
95 #include "wine/debug.h"
96 #include "wine/library.h"
97 #include "wine/list.h"
98 #include "wine/rbtree.h"
100 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
102 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
103 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
104 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
105 (csidl)==CSIDL_COMMON_STARTMENU)
107 /* link file formats */
109 #include "pshpack1.h"
111 typedef struct
113 BYTE bWidth;
114 BYTE bHeight;
115 BYTE bColorCount;
116 BYTE bReserved;
117 WORD wPlanes;
118 WORD wBitCount;
119 DWORD dwBytesInRes;
120 WORD nID;
121 } GRPICONDIRENTRY;
123 typedef struct
125 WORD idReserved;
126 WORD idType;
127 WORD idCount;
128 GRPICONDIRENTRY idEntries[1];
129 } GRPICONDIR;
131 typedef struct
133 BYTE bWidth;
134 BYTE bHeight;
135 BYTE bColorCount;
136 BYTE bReserved;
137 WORD wPlanes;
138 WORD wBitCount;
139 DWORD dwBytesInRes;
140 DWORD dwImageOffset;
141 } ICONDIRENTRY;
143 typedef struct
145 WORD idReserved;
146 WORD idType;
147 WORD idCount;
148 } ICONDIR;
150 typedef struct
152 WORD offset;
153 WORD length;
154 WORD flags;
155 WORD id;
156 WORD handle;
157 WORD usage;
158 } NE_NAMEINFO;
160 typedef struct
162 WORD type_id;
163 WORD count;
164 DWORD resloader;
165 } NE_TYPEINFO;
167 #define NE_RSCTYPE_ICON 0x8003
168 #define NE_RSCTYPE_GROUP_ICON 0x800e
170 #include "poppack.h"
172 typedef struct
174 HRSRC *pResInfo;
175 int nIndex;
176 } ENUMRESSTRUCT;
178 struct xdg_mime_type
180 char *mimeType;
181 char *glob;
182 char *lower_glob;
183 struct list entry;
186 struct rb_string_entry
188 char *string;
189 struct wine_rb_entry entry;
192 DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
194 static char *xdg_config_dir;
195 static char *xdg_data_dir;
196 static char *xdg_desktop_dir;
199 /* Utility routines */
200 static unsigned short crc16(const char* string)
202 unsigned short crc = 0;
203 int i, j, xor_poly;
205 for (i = 0; string[i] != 0; i++)
207 char c = string[i];
208 for (j = 0; j < 8; c >>= 1, j++)
210 xor_poly = (c ^ crc) & 1;
211 crc >>= 1;
212 if (xor_poly)
213 crc ^= 0xa001;
216 return crc;
219 static char *strdupA( const char *str )
221 char *ret;
223 if (!str) return NULL;
224 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
225 return ret;
228 static char* heap_printf(const char *format, ...)
230 va_list args;
231 int size = 4096;
232 char *buffer, *ret;
233 int n;
235 while (1)
237 buffer = HeapAlloc(GetProcessHeap(), 0, size);
238 if (buffer == NULL)
239 break;
240 va_start(args, format);
241 n = vsnprintf(buffer, size, format, args);
242 va_end(args);
243 if (n == -1)
244 size *= 2;
245 else if (n >= size)
246 size = n + 1;
247 else
248 break;
249 HeapFree(GetProcessHeap(), 0, buffer);
252 if (!buffer) return NULL;
253 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
254 if (!ret) ret = buffer;
255 return ret;
258 static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
260 const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);
262 return strcmp((char*)key, t->string);
265 static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
267 struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
268 HeapFree(GetProcessHeap(), 0, t->string);
269 HeapFree(GetProcessHeap(), 0, t);
272 static void write_xml_text(FILE *file, const char *text)
274 int i;
275 for (i = 0; text[i]; i++)
277 if (text[i] == '&')
278 fputs("&amp;", file);
279 else if (text[i] == '<')
280 fputs("&lt;", file);
281 else if (text[i] == '>')
282 fputs("&gt;", file);
283 else if (text[i] == '\'')
284 fputs("&apos;", file);
285 else if (text[i] == '"')
286 fputs("&quot;", file);
287 else
288 fputc(text[i], file);
292 static BOOL create_directories(char *directory)
294 BOOL ret = TRUE;
295 int i;
297 for (i = 0; directory[i]; i++)
299 if (i > 0 && directory[i] == '/')
301 directory[i] = 0;
302 mkdir(directory, 0777);
303 directory[i] = '/';
306 if (mkdir(directory, 0777) && errno != EEXIST)
307 ret = FALSE;
309 return ret;
312 static char* wchars_to_utf8_chars(LPCWSTR string)
314 char *ret;
315 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
316 ret = HeapAlloc(GetProcessHeap(), 0, size);
317 if (ret)
318 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
319 return ret;
322 static char* wchars_to_unix_chars(LPCWSTR string)
324 char *ret;
325 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
326 ret = HeapAlloc(GetProcessHeap(), 0, size);
327 if (ret)
328 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
329 return ret;
332 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
334 WCHAR *ret;
335 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
336 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
337 if (ret)
338 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
339 return ret;
342 /* Icon extraction routines
344 * FIXME: should use PrivateExtractIcons and friends
345 * FIXME: should not use stdio
348 static HRESULT convert_to_native_icon(IStream *icoFile, int *indices, int numIndices,
349 const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
351 WCHAR *dosOutputFileName = NULL;
352 IWICImagingFactory *factory = NULL;
353 IWICBitmapDecoder *decoder = NULL;
354 IWICBitmapEncoder *encoder = NULL;
355 IWICBitmapScaler *scaler = NULL;
356 IStream *outputFile = NULL;
357 int i;
358 HRESULT hr = E_FAIL;
360 dosOutputFileName = wine_get_dos_file_name(outputFileName);
361 if (dosOutputFileName == NULL)
363 WINE_ERR("error converting %s to DOS file name\n", outputFileName);
364 goto end;
366 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
367 &IID_IWICImagingFactory, (void**)&factory);
368 if (FAILED(hr))
370 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
371 goto end;
373 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
374 WICDecodeMetadataCacheOnDemand, &decoder);
375 if (FAILED(hr))
377 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
378 goto end;
380 if (IsEqualCLSID(outputFormat,&CLSID_WICIcnsEncoder))
382 hr = IWICImagingFactory_CreateBitmapScaler(factory, &scaler);
383 if (FAILED(hr))
385 WINE_WARN("error 0x%08X creating IWICBitmapScaler\n", hr);
388 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
389 &IID_IWICBitmapEncoder, (void**)&encoder);
390 if (FAILED(hr))
392 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
393 goto end;
395 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
396 if (FAILED(hr))
398 WINE_ERR("error 0x%08X creating output file %s\n", hr, wine_dbgstr_w(dosOutputFileName));
399 goto end;
401 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, GENERIC_WRITE);
402 if (FAILED(hr))
404 WINE_ERR("error 0x%08X initializing encoder\n", hr);
405 goto end;
408 for (i = 0; i < numIndices; i++)
410 IWICBitmapFrameDecode *sourceFrame = NULL;
411 IWICBitmapSource *sourceBitmap = NULL;
412 IWICBitmapFrameEncode *dstFrame = NULL;
413 IPropertyBag2 *options = NULL;
414 UINT width, height;
416 hr = IWICBitmapDecoder_GetFrame(decoder, indices[i], &sourceFrame);
417 if (FAILED(hr))
419 WINE_ERR("error 0x%08X getting frame %d\n", hr, indices[i]);
420 goto endloop;
422 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
423 if (FAILED(hr))
425 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
426 goto endloop;
428 if ( scaler)
430 IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
431 if (width == 64) /* Classic Mode */
433 hr = IWICBitmapScaler_Initialize( scaler, sourceBitmap, 128, 128,
434 WICBitmapInterpolationModeNearestNeighbor);
435 if (FAILED(hr))
436 WINE_ERR("error 0x%08X scaling bitmap\n", hr);
437 else
439 IWICBitmapSource_Release(sourceBitmap);
440 IWICBitmapScaler_QueryInterface(scaler, &IID_IWICBitmapSource, (LPVOID)&sourceBitmap);
444 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
445 if (FAILED(hr))
447 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
448 goto endloop;
450 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
451 if (FAILED(hr))
453 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
454 goto endloop;
456 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
457 if (FAILED(hr))
459 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
460 goto endloop;
462 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
463 if (FAILED(hr))
465 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
466 goto endloop;
468 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
469 if (FAILED(hr))
471 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
472 goto endloop;
474 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
475 if (FAILED(hr))
477 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
478 goto endloop;
480 hr = IWICBitmapFrameEncode_Commit(dstFrame);
481 if (FAILED(hr))
483 WINE_ERR("error 0x%08X committing frame\n", hr);
484 goto endloop;
486 endloop:
487 if (sourceFrame)
488 IWICBitmapFrameDecode_Release(sourceFrame);
489 if (sourceBitmap)
490 IWICBitmapSource_Release(sourceBitmap);
491 if (dstFrame)
492 IWICBitmapFrameEncode_Release(dstFrame);
493 if (options)
494 IPropertyBag2_Release(options);
497 hr = IWICBitmapEncoder_Commit(encoder);
498 if (FAILED(hr))
500 WINE_ERR("error 0x%08X committing encoder\n", hr);
501 goto end;
504 end:
505 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
506 if (factory)
507 IWICImagingFactory_Release(factory);
508 if (decoder)
509 IWICBitmapDecoder_Release(decoder);
510 if (scaler)
511 IWICBitmapScaler_Release(scaler);
512 if (encoder)
513 IWICBitmapEncoder_Release(encoder);
514 if (outputFile)
515 IStream_Release(outputFile);
516 return hr;
519 struct IconData16 {
520 BYTE *fileBytes;
521 DWORD fileSize;
522 NE_TYPEINFO *iconResources;
523 WORD alignmentShiftCount;
526 static int populate_module16_icons(struct IconData16 *iconData16, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
528 int i, j;
529 int validEntries = 0;
531 for (i = 0; i < grpIconDir->idCount; i++)
533 BYTE *iconPtr = (BYTE*)iconData16->iconResources;
534 NE_NAMEINFO *matchingIcon = NULL;
535 iconPtr += sizeof(NE_TYPEINFO);
536 for (j = 0; j < iconData16->iconResources->count; j++)
538 NE_NAMEINFO *iconInfo = (NE_NAMEINFO*)iconPtr;
539 if ((((BYTE*)iconPtr) + sizeof(NE_NAMEINFO)) > (iconData16->fileBytes + iconData16->fileSize))
541 WINE_WARN("file too small for icon NE_NAMEINFO\n");
542 break;
544 if (iconInfo->id == (0x8000 | grpIconDir->idEntries[i].nID))
546 matchingIcon = iconInfo;
547 break;
549 iconPtr += sizeof(NE_NAMEINFO);
552 if (matchingIcon == NULL)
553 continue;
554 if (((matchingIcon->offset << iconData16->alignmentShiftCount) + grpIconDir->idEntries[i].dwBytesInRes) > iconData16->fileSize)
556 WINE_WARN("file too small for icon contents\n");
557 break;
560 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
561 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
562 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
563 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
564 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
565 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
566 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
567 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
568 validEntries++;
569 memcpy(&icons[*iconOffset], &iconData16->fileBytes[matchingIcon->offset << iconData16->alignmentShiftCount], grpIconDir->idEntries[i].dwBytesInRes);
570 *iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
572 return validEntries;
575 static int populate_module_icons(HMODULE hModule, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
577 int i;
578 int validEntries = 0;
580 for (i = 0; i < grpIconDir->idCount; i++)
582 HRSRC hResInfo;
583 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
584 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
586 HGLOBAL hResData;
587 if ((hResData = LoadResource(hModule, hResInfo)))
589 BITMAPINFO *pIcon;
590 DWORD size = min( grpIconDir->idEntries[i].dwBytesInRes, ((IMAGE_RESOURCE_DATA_ENTRY *)hResInfo)->Size );
591 if ((pIcon = LockResource(hResData)))
593 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
594 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
595 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
596 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
597 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
598 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
599 iconDirEntries[validEntries].dwBytesInRes = size;
600 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
601 validEntries++;
602 memcpy(&icons[*iconOffset], pIcon, size);
603 *iconOffset += size;
605 FreeResource(hResData);
609 return validEntries;
612 static IStream *add_module_icons_to_stream(struct IconData16 *iconData16, HMODULE hModule, GRPICONDIR *grpIconDir)
614 int i;
615 SIZE_T iconsSize = 0;
616 BYTE *icons = NULL;
617 ICONDIRENTRY *iconDirEntries = NULL;
618 IStream *stream = NULL;
619 HRESULT hr = E_FAIL;
620 ULONG bytesWritten;
621 ICONDIR iconDir;
622 SIZE_T iconOffset;
623 int validEntries = 0;
624 LARGE_INTEGER zero;
626 for (i = 0; i < grpIconDir->idCount; i++)
627 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
628 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
629 if (icons == NULL)
631 WINE_ERR("out of memory allocating icon\n");
632 goto end;
635 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
636 if (iconDirEntries == NULL)
638 WINE_ERR("out of memory allocating icon dir entries\n");
639 goto end;
642 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
643 if (FAILED(hr))
645 WINE_ERR("error creating icon stream\n");
646 goto end;
649 iconOffset = 0;
650 if (iconData16)
651 validEntries = populate_module16_icons(iconData16, grpIconDir, iconDirEntries, icons, &iconOffset);
652 else if (hModule)
653 validEntries = populate_module_icons(hModule, grpIconDir, iconDirEntries, icons, &iconOffset);
655 if (validEntries == 0)
657 WINE_ERR("no valid icon entries\n");
658 goto end;
661 iconDir.idReserved = 0;
662 iconDir.idType = 1;
663 iconDir.idCount = validEntries;
664 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
665 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
667 WINE_ERR("error 0x%08X writing icon stream\n", hr);
668 goto end;
670 for (i = 0; i < validEntries; i++)
671 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
672 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
673 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
675 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
676 goto end;
678 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
679 if (FAILED(hr) || bytesWritten != iconOffset)
681 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
682 goto end;
684 zero.QuadPart = 0;
685 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
687 end:
688 HeapFree(GetProcessHeap(), 0, icons);
689 HeapFree(GetProcessHeap(), 0, iconDirEntries);
690 if (FAILED(hr) && stream != NULL)
692 IStream_Release(stream);
693 stream = NULL;
695 return stream;
698 static HRESULT open_module16_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
700 HANDLE hFile = INVALID_HANDLE_VALUE;
701 HANDLE hFileMapping = NULL;
702 DWORD fileSize;
703 BYTE *fileBytes = NULL;
704 IMAGE_DOS_HEADER *dosHeader;
705 IMAGE_OS2_HEADER *neHeader;
706 BYTE *rsrcTab;
707 NE_TYPEINFO *iconGroupResources;
708 NE_TYPEINFO *iconResources;
709 NE_NAMEINFO *iconDirPtr;
710 GRPICONDIR *iconDir;
711 WORD alignmentShiftCount;
712 struct IconData16 iconData16;
713 HRESULT hr = E_FAIL;
715 hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
716 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
717 if (hFile == INVALID_HANDLE_VALUE)
719 WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName), GetLastError());
720 goto end;
723 hFileMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
724 if (hFileMapping == NULL)
726 WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
727 goto end;
730 fileSize = GetFileSize(hFile, NULL);
732 fileBytes = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
733 if (fileBytes == NULL)
735 WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
736 goto end;
739 dosHeader = (IMAGE_DOS_HEADER*)fileBytes;
740 if (sizeof(IMAGE_DOS_HEADER) >= fileSize || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
742 WINE_WARN("file too small for MZ header\n");
743 goto end;
746 neHeader = (IMAGE_OS2_HEADER*)(fileBytes + dosHeader->e_lfanew);
747 if ((((BYTE*)neHeader) + sizeof(IMAGE_OS2_HEADER)) > (fileBytes + fileSize) ||
748 neHeader->ne_magic != IMAGE_OS2_SIGNATURE)
750 WINE_WARN("file too small for NE header\n");
751 goto end;
754 rsrcTab = ((BYTE*)neHeader) + neHeader->ne_rsrctab;
755 if ((rsrcTab + 2) > (fileBytes + fileSize))
757 WINE_WARN("file too small for resource table\n");
758 goto end;
761 alignmentShiftCount = *(WORD*)rsrcTab;
762 rsrcTab += 2;
763 iconGroupResources = NULL;
764 iconResources = NULL;
765 for (;;)
767 NE_TYPEINFO *neTypeInfo = (NE_TYPEINFO*)rsrcTab;
768 if ((rsrcTab + sizeof(NE_TYPEINFO)) > (fileBytes + fileSize))
770 WINE_WARN("file too small for resource table\n");
771 goto end;
773 if (neTypeInfo->type_id == 0)
774 break;
775 else if (neTypeInfo->type_id == NE_RSCTYPE_GROUP_ICON)
776 iconGroupResources = neTypeInfo;
777 else if (neTypeInfo->type_id == NE_RSCTYPE_ICON)
778 iconResources = neTypeInfo;
779 rsrcTab += sizeof(NE_TYPEINFO) + neTypeInfo->count*sizeof(NE_NAMEINFO);
781 if (iconGroupResources == NULL)
783 WINE_WARN("no group icon resource type found\n");
784 goto end;
786 if (iconResources == NULL)
788 WINE_WARN("no icon resource type found\n");
789 goto end;
792 if (nIndex >= iconGroupResources->count)
794 WINE_WARN("icon index out of range\n");
795 goto end;
798 iconDirPtr = (NE_NAMEINFO*)(((BYTE*)iconGroupResources) + sizeof(NE_TYPEINFO) + nIndex*sizeof(NE_NAMEINFO));
799 if ((((BYTE*)iconDirPtr) + sizeof(NE_NAMEINFO)) > (fileBytes + fileSize))
801 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
802 goto end;
804 iconDir = (GRPICONDIR*)(fileBytes + (iconDirPtr->offset << alignmentShiftCount));
805 if ((((BYTE*)iconDir) + sizeof(GRPICONDIR) + iconDir->idCount*sizeof(GRPICONDIRENTRY)) > (fileBytes + fileSize))
807 WINE_WARN("file too small for GRPICONDIR\n");
808 goto end;
811 iconData16.fileBytes = fileBytes;
812 iconData16.fileSize = fileSize;
813 iconData16.iconResources = iconResources;
814 iconData16.alignmentShiftCount = alignmentShiftCount;
815 *ppStream = add_module_icons_to_stream(&iconData16, NULL, iconDir);
816 if (*ppStream)
817 hr = S_OK;
819 end:
820 if (hFile != INVALID_HANDLE_VALUE)
821 CloseHandle(hFile);
822 if (hFileMapping != NULL)
823 CloseHandle(hFileMapping);
824 if (fileBytes != NULL)
825 UnmapViewOfFile(fileBytes);
826 return hr;
829 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
831 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
833 if (!sEnumRes->nIndex--)
835 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
836 return FALSE;
838 else
839 return TRUE;
842 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
844 HMODULE hModule;
845 HRSRC hResInfo;
846 HGLOBAL hResData;
847 GRPICONDIR *pIconDir;
848 ENUMRESSTRUCT sEnumRes;
849 HRESULT hr = E_FAIL;
851 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
852 if (!hModule)
854 if (GetLastError() == ERROR_BAD_EXE_FORMAT)
855 return open_module16_icon(szFileName, nIndex, ppStream);
856 else
858 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
859 wine_dbgstr_w(szFileName), GetLastError());
860 return HRESULT_FROM_WIN32(GetLastError());
864 if (nIndex < 0)
866 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
867 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
868 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
870 else
872 hResInfo=NULL;
873 sEnumRes.pResInfo = &hResInfo;
874 sEnumRes.nIndex = nIndex;
875 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
876 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
877 sEnumRes.nIndex != -1)
879 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
883 if (hResInfo)
885 if ((hResData = LoadResource(hModule, hResInfo)))
887 if ((pIconDir = LockResource(hResData)))
889 *ppStream = add_module_icons_to_stream(0, hModule, pIconDir);
890 if (*ppStream)
891 hr = S_OK;
894 FreeResource(hResData);
897 else
899 WINE_WARN("found no icon\n");
900 FreeLibrary(hModule);
901 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
904 FreeLibrary(hModule);
905 return hr;
908 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
910 ICONDIR iconDir;
911 ULONG bytesRead;
912 HRESULT hr;
914 *ppIconDirEntries = NULL;
916 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
917 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
918 (iconDir.idReserved != 0) || (iconDir.idType != 1))
920 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
921 hr = E_FAIL;
922 goto end;
924 *numEntries = iconDir.idCount;
926 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
928 hr = E_OUTOFMEMORY;
929 goto end;
931 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
932 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
934 if (SUCCEEDED(hr)) hr = E_FAIL;
935 goto end;
938 end:
939 if (FAILED(hr))
940 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
941 return hr;
944 static HRESULT validate_ico(IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
946 HRESULT hr;
948 hr = read_ico_direntries(*ppStream, ppIconDirEntries, numEntries);
949 if (SUCCEEDED(hr))
951 if (*numEntries)
952 return hr;
953 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
954 *ppIconDirEntries = NULL;
956 IStream_Release(*ppStream);
957 *ppStream = NULL;
958 return E_FAIL;
961 static HRESULT write_native_icon(IStream *iconStream, ICONDIRENTRY *pIconDirEntry,
962 int numEntries, const char *icon_name, LPCWSTR szFileName)
964 int nMax = 0, nMaxBits = 0;
965 int nIndex = 0;
966 int i;
967 LARGE_INTEGER position;
968 HRESULT hr;
970 for (i = 0; i < numEntries; i++)
972 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
973 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
974 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
976 nIndex = i;
977 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
978 nMaxBits = pIconDirEntry[i].wBitCount;
981 WINE_TRACE("Selected: %d\n", nIndex);
983 position.QuadPart = 0;
984 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
985 if (FAILED(hr)) return hr;
986 return convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
989 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
991 HRESULT hr;
992 WCHAR *value = NULL;
993 DWORD size = 0;
994 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
995 if (SUCCEEDED(hr))
997 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
998 if (value)
1000 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1001 if (FAILED(hr))
1003 HeapFree(GetProcessHeap(), 0, value);
1004 value = NULL;
1008 return value;
1011 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
1013 static const WCHAR openW[] = {'o','p','e','n',0};
1014 WCHAR *extension;
1015 WCHAR *icon = NULL;
1016 WCHAR *comma;
1017 WCHAR *executable = NULL;
1018 int index = 0;
1019 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
1021 extension = strrchrW(szFileName, '.');
1022 if (extension == NULL)
1023 goto end;
1025 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
1026 if (icon)
1028 comma = strrchrW(icon, ',');
1029 if (comma)
1031 *comma = 0;
1032 index = atoiW(comma + 1);
1034 hr = open_module_icon(icon, index, ppStream);
1036 else
1038 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, openW);
1039 if (executable)
1040 hr = open_module_icon(executable, 0, ppStream);
1043 end:
1044 HeapFree(GetProcessHeap(), 0, icon);
1045 HeapFree(GetProcessHeap(), 0, executable);
1046 return hr;
1049 static HRESULT open_default_icon(IStream **ppStream)
1051 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
1053 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
1056 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
1058 HRESULT hr;
1060 hr = open_module_icon(filename, index, ppStream);
1061 if (FAILED(hr))
1063 if(bWait && hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
1065 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1066 wine_dbgstr_w(filename));
1067 return hr;
1069 else
1071 /* This might be a raw .ico file */
1072 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
1075 if (SUCCEEDED(hr))
1076 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1078 if (FAILED(hr))
1080 hr = open_file_type_icon(filename, ppStream);
1081 if (SUCCEEDED(hr))
1082 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1084 if (FAILED(hr) && !bWait)
1086 hr = open_default_icon(ppStream);
1087 if (SUCCEEDED(hr))
1088 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1090 return hr;
1093 static char* compute_native_identifier(int exeIndex, LPCWSTR icoPathW)
1095 char* nativeIdentifier;
1096 char *icoPathA;
1097 unsigned short crc;
1098 char *basename, *ext;
1100 icoPathA = wchars_to_utf8_chars(icoPathW);
1101 if (icoPathA == NULL)
1102 return NULL;
1104 crc = crc16(icoPathA);
1105 basename = strrchr(icoPathA, '\\');
1106 if (basename == NULL)
1107 basename = icoPathA;
1108 else
1110 *basename = 0;
1111 basename++;
1113 ext = strrchr(basename, '.');
1114 if (ext)
1115 *ext = 0;
1117 nativeIdentifier = heap_printf("%04X_%s.%d", crc, basename, exeIndex);
1118 HeapFree(GetProcessHeap(), 0, icoPathA);
1119 return nativeIdentifier;
1122 #ifdef __APPLE__
1123 #define ICNS_SLOTS 6
1125 static inline int size_to_slot(int size)
1127 switch (size)
1129 case 16: return 0;
1130 case 32: return 1;
1131 case 48: return 2;
1132 case 64: return -2; /* Classic Mode */
1133 case 128: return 3;
1134 case 256: return 4;
1135 case 512: return 5;
1138 return -1;
1141 #define CLASSIC_SLOT 3
1143 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1144 int numEntries, int exeIndex, LPCWSTR icoPathW,
1145 const char *destFilename, char **nativeIdentifier)
1147 struct {
1148 int index;
1149 int maxBits;
1150 BOOL scaled;
1151 } best[ICNS_SLOTS];
1152 int indexes[ICNS_SLOTS];
1153 int i;
1154 const char* tmpdir;
1155 char *icnsPath = NULL;
1156 LARGE_INTEGER zero;
1157 HRESULT hr;
1159 for (i = 0; i < ICNS_SLOTS; i++)
1161 best[i].index = -1;
1162 best[i].maxBits = 0;
1164 for (i = 0; i < numEntries; i++)
1166 int slot;
1167 int width = iconDirEntries[i].bWidth ? iconDirEntries[i].bWidth : 256;
1168 int height = iconDirEntries[i].bHeight ? iconDirEntries[i].bHeight : 256;
1169 BOOL scaled = FALSE;
1171 WINE_TRACE("[%d]: %d x %d @ %d\n", i, width, height, iconDirEntries[i].wBitCount);
1172 if (height != width)
1173 continue;
1174 slot = size_to_slot(width);
1175 if (slot == -2)
1177 scaled = TRUE;
1178 slot = CLASSIC_SLOT;
1180 else if (slot < 0)
1181 continue;
1182 if (scaled && best[slot].maxBits && !best[slot].scaled)
1183 continue; /* don't replace unscaled with scaled */
1184 if (iconDirEntries[i].wBitCount >= best[slot].maxBits || (!scaled && best[slot].scaled))
1186 best[slot].index = i;
1187 best[slot].maxBits = iconDirEntries[i].wBitCount;
1188 best[slot].scaled = scaled;
1191 /* remove the scaled icon if a larger unscaled icon exists */
1192 if (best[CLASSIC_SLOT].scaled)
1194 for (i = CLASSIC_SLOT+1; i < ICNS_SLOTS; i++)
1195 if (best[i].index >= 0 && !best[i].scaled)
1197 best[CLASSIC_SLOT].index = -1;
1198 break;
1202 numEntries = 0;
1203 for (i = 0; i < ICNS_SLOTS; i++)
1205 if (best[i].index >= 0)
1207 indexes[numEntries] = best[i].index;
1208 numEntries++;
1212 if (destFilename)
1213 *nativeIdentifier = heap_printf("%s", destFilename);
1214 else
1215 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1216 if (*nativeIdentifier == NULL)
1218 hr = E_OUTOFMEMORY;
1219 goto end;
1221 if (!(tmpdir = getenv("TMPDIR"))) tmpdir = "/tmp";
1222 icnsPath = heap_printf("%s/%s.icns", tmpdir, *nativeIdentifier);
1223 if (icnsPath == NULL)
1225 hr = E_OUTOFMEMORY;
1226 WINE_WARN("out of memory creating ICNS path\n");
1227 goto end;
1229 zero.QuadPart = 0;
1230 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1231 if (FAILED(hr))
1233 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
1234 goto end;
1236 hr = convert_to_native_icon(icoStream, indexes, numEntries, &CLSID_WICIcnsEncoder,
1237 icnsPath, icoPathW);
1238 if (FAILED(hr))
1240 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
1241 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
1242 goto end;
1245 end:
1246 HeapFree(GetProcessHeap(), 0, icnsPath);
1247 return hr;
1249 #else
1250 static void refresh_icon_cache(const char *iconsDir)
1252 /* The icon theme spec only requires the mtime on the "toplevel"
1253 * directory (whatever that is) to be changed for a refresh,
1254 * but on GNOME you have to create a file in that directory
1255 * instead. Creating a file also works on KDE, Xfce and LXDE.
1257 char *filename = heap_printf("%s/.wine-refresh-XXXXXX", iconsDir);
1258 if (filename != NULL)
1260 int fd = mkstemps(filename, 0);
1261 if (fd >= 0)
1263 close(fd);
1264 unlink(filename);
1266 HeapFree(GetProcessHeap(), 0, filename);
1270 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1271 int numEntries, int exeIndex, LPCWSTR icoPathW,
1272 const char *destFilename, char **nativeIdentifier)
1274 int i;
1275 char *iconsDir = NULL;
1276 HRESULT hr = S_OK;
1277 LARGE_INTEGER zero;
1279 if (destFilename)
1280 *nativeIdentifier = heap_printf("%s", destFilename);
1281 else
1282 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1283 if (*nativeIdentifier == NULL)
1285 hr = E_OUTOFMEMORY;
1286 goto end;
1288 iconsDir = heap_printf("%s/icons/hicolor", xdg_data_dir);
1289 if (iconsDir == NULL)
1291 hr = E_OUTOFMEMORY;
1292 goto end;
1295 for (i = 0; i < numEntries; i++)
1297 int bestIndex = i;
1298 int j;
1299 BOOLEAN duplicate = FALSE;
1300 int w, h;
1301 char *iconDir = NULL;
1302 char *pngPath = NULL;
1304 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
1305 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
1307 for (j = 0; j < i; j++)
1309 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1310 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
1312 duplicate = TRUE;
1313 break;
1316 if (duplicate)
1317 continue;
1318 for (j = i + 1; j < numEntries; j++)
1320 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1321 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1322 iconDirEntries[j].wBitCount >= iconDirEntries[bestIndex].wBitCount)
1324 bestIndex = j;
1327 WINE_TRACE("Selected: %d\n", bestIndex);
1329 w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
1330 h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
1331 iconDir = heap_printf("%s/%dx%d/apps", iconsDir, w, h);
1332 if (iconDir == NULL)
1334 hr = E_OUTOFMEMORY;
1335 goto endloop;
1337 create_directories(iconDir);
1338 pngPath = heap_printf("%s/%s.png", iconDir, *nativeIdentifier);
1339 if (pngPath == NULL)
1341 hr = E_OUTOFMEMORY;
1342 goto endloop;
1344 zero.QuadPart = 0;
1345 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1346 if (FAILED(hr))
1347 goto endloop;
1348 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
1349 pngPath, icoPathW);
1351 endloop:
1352 HeapFree(GetProcessHeap(), 0, iconDir);
1353 HeapFree(GetProcessHeap(), 0, pngPath);
1355 refresh_icon_cache(iconsDir);
1357 end:
1358 HeapFree(GetProcessHeap(), 0, iconsDir);
1359 return hr;
1361 #endif /* defined(__APPLE__) */
1363 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1364 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
1366 IStream *stream = NULL;
1367 ICONDIRENTRY *pIconDirEntries = NULL;
1368 int numEntries;
1369 HRESULT hr;
1370 char *nativeIdentifier = NULL;
1372 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
1374 hr = open_icon(icoPathW, index, bWait, &stream, &pIconDirEntries, &numEntries);
1375 if (FAILED(hr))
1377 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
1378 goto end;
1380 hr = platform_write_icon(stream, pIconDirEntries, numEntries, index, icoPathW, destFilename, &nativeIdentifier);
1381 if (FAILED(hr))
1382 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
1384 end:
1385 if (stream)
1386 IStream_Release(stream);
1387 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
1388 if (FAILED(hr))
1390 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
1391 nativeIdentifier = NULL;
1393 return nativeIdentifier;
1396 static HKEY open_menus_reg_key(void)
1398 static const WCHAR Software_Wine_FileOpenMenuFilesW[] = {
1399 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1400 HKEY assocKey;
1401 DWORD ret;
1402 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenMenuFilesW, &assocKey);
1403 if (ret == ERROR_SUCCESS)
1404 return assocKey;
1405 SetLastError(ret);
1406 return NULL;
1409 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1411 WCHAR *unix_fileW;
1412 WCHAR *windows_fileW;
1413 INT size;
1414 DWORD ret;
1416 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1417 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1418 if (unix_fileW)
1420 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1421 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1422 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1423 if (windows_fileW)
1425 HKEY hkey;
1426 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1427 hkey = open_menus_reg_key();
1428 if (hkey)
1430 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1431 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1432 RegCloseKey(hkey);
1434 else
1435 ret = GetLastError();
1436 HeapFree(GetProcessHeap(), 0, windows_fileW);
1438 else
1439 ret = ERROR_NOT_ENOUGH_MEMORY;
1440 HeapFree(GetProcessHeap(), 0, unix_fileW);
1442 else
1443 ret = ERROR_NOT_ENOUGH_MEMORY;
1444 return ret;
1447 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1448 const char *path, const char *args, const char *descr,
1449 const char *workdir, const char *icon, const char *wmclass)
1451 FILE *file;
1453 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1454 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1455 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon),
1456 wine_dbgstr_a(wmclass));
1458 file = fopen(location, "w");
1459 if (file == NULL)
1460 return FALSE;
1462 fprintf(file, "[Desktop Entry]\n");
1463 fprintf(file, "Name=%s\n", linkname);
1464 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1465 wine_get_config_dir(), path, args);
1466 fprintf(file, "Type=Application\n");
1467 fprintf(file, "StartupNotify=true\n");
1468 if (descr && lstrlenA(descr))
1469 fprintf(file, "Comment=%s\n", descr);
1470 if (workdir && lstrlenA(workdir))
1471 fprintf(file, "Path=%s\n", workdir);
1472 if (icon && lstrlenA(icon))
1473 fprintf(file, "Icon=%s\n", icon);
1474 if (wmclass && lstrlenA(wmclass))
1475 fprintf(file, "StartupWMClass=%s\n", wmclass);
1477 fclose(file);
1479 if (unix_link)
1481 DWORD ret = register_menus_entry(location, unix_link);
1482 if (ret != ERROR_SUCCESS)
1483 return FALSE;
1486 return TRUE;
1489 static BOOL write_directory_entry(const char *directory, const char *location)
1491 FILE *file;
1493 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1495 file = fopen(location, "w");
1496 if (file == NULL)
1497 return FALSE;
1499 fprintf(file, "[Desktop Entry]\n");
1500 fprintf(file, "Type=Directory\n");
1501 if (strcmp(directory, "wine") == 0)
1503 fprintf(file, "Name=Wine\n");
1504 fprintf(file, "Icon=wine\n");
1506 else
1508 fprintf(file, "Name=%s\n", directory);
1509 fprintf(file, "Icon=folder\n");
1512 fclose(file);
1513 return TRUE;
1516 static BOOL write_menu_file(const char *unix_link, const char *filename)
1518 char *tempfilename;
1519 FILE *tempfile = NULL;
1520 char *lastEntry;
1521 char *name = NULL;
1522 char *menuPath = NULL;
1523 int i;
1524 int count = 0;
1525 BOOL ret = FALSE;
1527 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1529 while (1)
1531 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1532 if (tempfilename)
1534 int tempfd = mkstemps(tempfilename, 0);
1535 if (tempfd >= 0)
1537 tempfile = fdopen(tempfd, "w");
1538 if (tempfile)
1539 break;
1540 close(tempfd);
1541 goto end;
1543 else if (errno == EEXIST)
1545 HeapFree(GetProcessHeap(), 0, tempfilename);
1546 continue;
1548 HeapFree(GetProcessHeap(), 0, tempfilename);
1550 return FALSE;
1553 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1554 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1555 fprintf(tempfile, "<Menu>\n");
1556 fprintf(tempfile, " <Name>Applications</Name>\n");
1558 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1559 if (name == NULL) goto end;
1560 lastEntry = name;
1561 for (i = 0; filename[i]; i++)
1563 name[i] = filename[i];
1564 if (filename[i] == '/')
1566 char *dir_file_name;
1567 struct stat st;
1568 name[i] = 0;
1569 fprintf(tempfile, " <Menu>\n");
1570 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1571 write_xml_text(tempfile, name);
1572 fprintf(tempfile, "</Name>\n");
1573 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1574 write_xml_text(tempfile, name);
1575 fprintf(tempfile, ".directory</Directory>\n");
1576 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1577 xdg_data_dir, count ? "" : "wine-", name);
1578 if (dir_file_name)
1580 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1581 write_directory_entry(lastEntry, dir_file_name);
1582 HeapFree(GetProcessHeap(), 0, dir_file_name);
1584 name[i] = '-';
1585 lastEntry = &name[i+1];
1586 ++count;
1589 name[i] = 0;
1591 fprintf(tempfile, " <Include>\n");
1592 fprintf(tempfile, " <Filename>");
1593 write_xml_text(tempfile, name);
1594 fprintf(tempfile, "</Filename>\n");
1595 fprintf(tempfile, " </Include>\n");
1596 for (i = 0; i < count; i++)
1597 fprintf(tempfile, " </Menu>\n");
1598 fprintf(tempfile, "</Menu>\n");
1600 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1601 if (menuPath == NULL) goto end;
1602 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1603 ret = TRUE;
1605 end:
1606 if (tempfile)
1607 fclose(tempfile);
1608 if (ret)
1609 ret = (rename(tempfilename, menuPath) == 0);
1610 if (!ret && tempfilename)
1611 remove(tempfilename);
1612 HeapFree(GetProcessHeap(), 0, tempfilename);
1613 if (ret)
1614 register_menus_entry(menuPath, unix_link);
1615 HeapFree(GetProcessHeap(), 0, name);
1616 HeapFree(GetProcessHeap(), 0, menuPath);
1617 return ret;
1620 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1621 const char *descr, const char *workdir, const char *icon, const char *wmclass)
1623 const char *linkname;
1624 char *desktopPath = NULL;
1625 char *desktopDir;
1626 char *filename = NULL;
1627 BOOL ret = TRUE;
1629 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1630 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1631 wine_dbgstr_a(workdir), wine_dbgstr_a(icon), wine_dbgstr_a(wmclass));
1633 linkname = strrchr(link, '/');
1634 if (linkname == NULL)
1635 linkname = link;
1636 else
1637 ++linkname;
1639 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1640 if (!desktopPath)
1642 WINE_WARN("out of memory creating menu entry\n");
1643 ret = FALSE;
1644 goto end;
1646 desktopDir = strrchr(desktopPath, '/');
1647 *desktopDir = 0;
1648 if (!create_directories(desktopPath))
1650 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1651 ret = FALSE;
1652 goto end;
1654 *desktopDir = '/';
1655 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon, wmclass))
1657 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1658 ret = FALSE;
1659 goto end;
1662 filename = heap_printf("wine/%s.desktop", link);
1663 if (!filename || !write_menu_file(unix_link, filename))
1665 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1666 ret = FALSE;
1669 end:
1670 HeapFree(GetProcessHeap(), 0, desktopPath);
1671 HeapFree(GetProcessHeap(), 0, filename);
1672 return ret;
1675 /* This escapes reserved characters in .desktop files' Exec keys. */
1676 static LPSTR escape(LPCWSTR arg)
1678 int i, j;
1679 WCHAR *escaped_string;
1680 char *utf8_string;
1682 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1683 if (escaped_string == NULL) return NULL;
1684 for (i = j = 0; arg[i]; i++)
1686 switch (arg[i])
1688 case '\\':
1689 escaped_string[j++] = '\\';
1690 escaped_string[j++] = '\\';
1691 escaped_string[j++] = '\\';
1692 escaped_string[j++] = '\\';
1693 break;
1694 case ' ':
1695 case '\t':
1696 case '\n':
1697 case '"':
1698 case '\'':
1699 case '>':
1700 case '<':
1701 case '~':
1702 case '|':
1703 case '&':
1704 case ';':
1705 case '$':
1706 case '*':
1707 case '?':
1708 case '#':
1709 case '(':
1710 case ')':
1711 case '`':
1712 escaped_string[j++] = '\\';
1713 escaped_string[j++] = '\\';
1714 /* fall through */
1715 default:
1716 escaped_string[j++] = arg[i];
1717 break;
1720 escaped_string[j] = 0;
1722 utf8_string = wchars_to_utf8_chars(escaped_string);
1723 if (utf8_string == NULL)
1725 WINE_ERR("out of memory\n");
1726 goto end;
1729 end:
1730 HeapFree(GetProcessHeap(), 0, escaped_string);
1731 return utf8_string;
1734 /* Return a heap-allocated copy of the unix format difference between the two
1735 * Windows-format paths.
1736 * locn is the owning location
1737 * link is within locn
1739 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1741 char *unix_locn, *unix_link;
1742 char *relative = NULL;
1744 unix_locn = wine_get_unix_file_name(locn);
1745 unix_link = wine_get_unix_file_name(link);
1746 if (unix_locn && unix_link)
1748 size_t len_unix_locn, len_unix_link;
1749 len_unix_locn = strlen (unix_locn);
1750 len_unix_link = strlen (unix_link);
1751 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1753 size_t len_rel;
1754 char *p = strrchr (unix_link + len_unix_locn, '/');
1755 p = strrchr (p, '.');
1756 if (p)
1758 *p = '\0';
1759 len_unix_link = p - unix_link;
1761 len_rel = len_unix_link - len_unix_locn;
1762 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1763 if (relative)
1765 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1769 if (!relative)
1770 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1771 HeapFree(GetProcessHeap(), 0, unix_locn);
1772 HeapFree(GetProcessHeap(), 0, unix_link);
1773 return relative;
1776 /***********************************************************************
1778 * GetLinkLocation
1780 * returns TRUE if successful
1781 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1782 * *relative will contain the address of a heap-allocated copy of the portion
1783 * of the filename that is within the specified location, in unix form
1785 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1787 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1788 DWORD len, i, r, filelen;
1789 const DWORD locations[] = {
1790 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1791 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1792 CSIDL_COMMON_STARTMENU };
1794 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1795 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1796 if (filelen==0 || filelen>MAX_PATH)
1797 return FALSE;
1799 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1801 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1802 * expand or our hardcoded list won't match.
1804 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1805 if (filelen==0 || filelen>MAX_PATH)
1806 return FALSE;
1808 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1810 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1812 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1813 continue;
1815 len = lstrlenW(buffer);
1816 if (len >= MAX_PATH)
1817 continue; /* We've just trashed memory! Hopefully we are OK */
1819 if (len > filelen || filename[len]!='\\')
1820 continue;
1821 /* do a lstrcmpinW */
1822 filename[len] = 0;
1823 r = lstrcmpiW( filename, buffer );
1824 filename[len] = '\\';
1825 if ( r )
1826 continue;
1828 /* return the remainder of the string and link type */
1829 *loc = locations[i];
1830 *relative = relative_path (filename, buffer);
1831 return (*relative != NULL);
1834 return FALSE;
1837 /* gets the target path directly or through MSI */
1838 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1839 LPWSTR szArgs, DWORD argsSize)
1841 IShellLinkDataList *dl = NULL;
1842 EXP_DARWIN_LINK *dar = NULL;
1843 HRESULT hr;
1845 szPath[0] = 0;
1846 szArgs[0] = 0;
1848 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1849 if (hr == S_OK && szPath[0])
1851 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1852 return hr;
1855 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1856 if (FAILED(hr))
1857 return hr;
1859 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1860 if (SUCCEEDED(hr))
1862 WCHAR* szCmdline;
1863 DWORD cmdSize;
1865 cmdSize=0;
1866 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1867 if (hr == ERROR_SUCCESS)
1869 cmdSize++;
1870 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1871 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1872 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1873 if (hr == ERROR_SUCCESS)
1875 WCHAR *s, *d;
1876 int bcount = 0;
1877 BOOL in_quotes = FALSE;
1879 /* Extract the application path */
1880 s=szCmdline;
1881 d=szPath;
1882 while (*s)
1884 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1886 /* skip the remaining spaces */
1887 do {
1888 s++;
1889 } while (*s==0x0009 || *s==0x0020);
1890 break;
1892 else if (*s==0x005c)
1894 /* '\\' */
1895 *d++=*s++;
1896 bcount++;
1898 else if (*s==0x0022)
1900 /* '"' */
1901 if ((bcount & 1)==0)
1903 /* Preceded by an even number of '\', this is
1904 * half that number of '\', plus a quote which
1905 * we erase.
1907 d-=bcount/2;
1908 in_quotes=!in_quotes;
1909 s++;
1911 else
1913 /* Preceded by an odd number of '\', this is
1914 * half that number of '\' followed by a '"'
1916 d=d-bcount/2-1;
1917 *d++='"';
1918 s++;
1920 bcount=0;
1922 else
1924 /* a regular character */
1925 *d++=*s++;
1926 bcount=0;
1928 if ((d-szPath) == pathSize)
1930 /* Keep processing the path till we get to the
1931 * arguments, but 'stand still'
1933 d--;
1936 /* Close the application path */
1937 *d=0;
1939 lstrcpynW(szArgs, s, argsSize);
1941 HeapFree( GetProcessHeap(), 0, szCmdline );
1943 LocalFree( dar );
1946 IShellLinkDataList_Release( dl );
1947 return hr;
1950 static char *slashes_to_minuses(const char *string)
1952 int i;
1953 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1954 if (ret)
1956 for (i = 0; string[i]; i++)
1958 if (string[i] == '/')
1959 ret[i] = '-';
1960 else
1961 ret[i] = string[i];
1963 ret[i] = 0;
1964 return ret;
1966 return NULL;
1969 static BOOL next_line(FILE *file, char **line, int *size)
1971 int pos = 0;
1972 char *cr;
1973 if (*line == NULL)
1975 *size = 4096;
1976 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1978 while (*line != NULL)
1980 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1982 HeapFree(GetProcessHeap(), 0, *line);
1983 *line = NULL;
1984 if (feof(file))
1985 return TRUE;
1986 return FALSE;
1988 pos = strlen(*line);
1989 cr = strchr(*line, '\n');
1990 if (cr == NULL)
1992 char *line2;
1993 (*size) *= 2;
1994 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1995 if (line2)
1996 *line = line2;
1997 else
1999 HeapFree(GetProcessHeap(), 0, *line);
2000 *line = NULL;
2003 else
2005 *cr = 0;
2006 return TRUE;
2009 return FALSE;
2012 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
2014 char *globs_filename = NULL;
2015 BOOL ret = TRUE;
2016 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
2017 if (globs_filename)
2019 FILE *globs_file = fopen(globs_filename, "r");
2020 if (globs_file) /* doesn't have to exist */
2022 char *line = NULL;
2023 int size = 0;
2024 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
2026 char *pos;
2027 struct xdg_mime_type *mime_type_entry = NULL;
2028 if (line[0] != '#' && (pos = strchr(line, ':')))
2030 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
2031 if (mime_type_entry)
2033 *pos = 0;
2034 mime_type_entry->mimeType = strdupA(line);
2035 mime_type_entry->glob = strdupA(pos + 1);
2036 mime_type_entry->lower_glob = strdupA(pos + 1);
2037 if (mime_type_entry->lower_glob)
2039 char *l;
2040 for (l = mime_type_entry->lower_glob; *l; l++)
2041 *l = tolower(*l);
2043 if (mime_type_entry->mimeType && mime_type_entry->glob && mime_type_entry->lower_glob)
2044 list_add_tail(mime_types, &mime_type_entry->entry);
2045 else
2047 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2048 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2049 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2050 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2051 ret = FALSE;
2054 else
2055 ret = FALSE;
2058 HeapFree(GetProcessHeap(), 0, line);
2059 fclose(globs_file);
2061 HeapFree(GetProcessHeap(), 0, globs_filename);
2063 else
2064 ret = FALSE;
2065 return ret;
2068 static void free_native_mime_types(struct list *native_mime_types)
2070 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
2072 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
2074 list_remove(&mime_type_entry->entry);
2075 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2076 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2077 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2078 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2082 static BOOL build_native_mime_types(const char *xdg_data_home, struct list *mime_types)
2084 char *xdg_data_dirs;
2085 BOOL ret;
2087 xdg_data_dirs = getenv("XDG_DATA_DIRS");
2088 if (xdg_data_dirs == NULL)
2089 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
2090 else
2091 xdg_data_dirs = strdupA(xdg_data_dirs);
2093 if (xdg_data_dirs)
2095 const char *begin;
2096 char *end;
2098 ret = add_mimes(xdg_data_home, mime_types);
2099 if (ret)
2101 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
2103 *end = '\0';
2104 ret = add_mimes(begin, mime_types);
2105 *end = ':';
2106 if (!ret)
2107 break;
2109 if (ret)
2110 ret = add_mimes(begin, mime_types);
2112 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
2114 else
2115 ret = FALSE;
2116 if (!ret)
2117 free_native_mime_types(mime_types);
2118 return ret;
2121 static BOOL match_glob(struct list *native_mime_types, const char *extension,
2122 int ignoreGlobCase, char **match)
2124 #ifdef HAVE_FNMATCH
2125 struct xdg_mime_type *mime_type_entry;
2126 int matchLength = 0;
2128 *match = NULL;
2130 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
2132 const char *glob = ignoreGlobCase ? mime_type_entry->lower_glob : mime_type_entry->glob;
2133 if (fnmatch(glob, extension, 0) == 0)
2135 if (*match == NULL || matchLength < strlen(glob))
2137 *match = mime_type_entry->mimeType;
2138 matchLength = strlen(glob);
2143 if (*match != NULL)
2145 *match = strdupA(*match);
2146 if (*match == NULL)
2147 return FALSE;
2149 #else
2150 *match = NULL;
2151 #endif
2152 return TRUE;
2155 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
2156 const char *extensionA,
2157 LPCWSTR extensionW,
2158 char **mime_type)
2160 WCHAR *lower_extensionW;
2161 INT len;
2162 BOOL ret = match_glob(native_mime_types, extensionA, 0, mime_type);
2163 if (ret == FALSE || *mime_type != NULL)
2164 return ret;
2165 len = strlenW(extensionW);
2166 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
2167 if (lower_extensionW)
2169 char *lower_extensionA;
2170 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
2171 strlwrW(lower_extensionW);
2172 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
2173 if (lower_extensionA)
2175 ret = match_glob(native_mime_types, lower_extensionA, 1, mime_type);
2176 HeapFree(GetProcessHeap(), 0, lower_extensionA);
2178 else
2180 ret = FALSE;
2181 WINE_FIXME("out of memory\n");
2183 HeapFree(GetProcessHeap(), 0, lower_extensionW);
2185 else
2187 ret = FALSE;
2188 WINE_FIXME("out of memory\n");
2190 return ret;
2193 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
2195 DWORD size;
2196 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
2198 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
2199 if (ret)
2201 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
2202 return ret;
2204 HeapFree(GetProcessHeap(), 0, ret);
2206 return NULL;
2209 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
2211 WCHAR *valW = reg_get_valW(key, subkey, name);
2212 if (valW)
2214 char *val = wchars_to_utf8_chars(valW);
2215 HeapFree(GetProcessHeap(), 0, valW);
2216 return val;
2218 return NULL;
2221 static HKEY open_associations_reg_key(void)
2223 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
2224 '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};
2225 HKEY assocKey;
2226 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
2227 return assocKey;
2228 return NULL;
2231 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
2232 LPCSTR appName, LPCSTR openWithIcon)
2234 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2235 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2236 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2237 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2238 HKEY assocKey;
2239 BOOL ret;
2241 if ((assocKey = open_associations_reg_key()))
2243 CHAR *valueA;
2244 WCHAR *value;
2246 ret = FALSE;
2248 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
2249 if (!valueA || lstrcmpA(valueA, mimeType))
2250 ret = TRUE;
2251 HeapFree(GetProcessHeap(), 0, valueA);
2253 value = reg_get_valW(assocKey, extensionW, ProgIDW);
2254 if (!value || strcmpW(value, progId))
2255 ret = TRUE;
2256 HeapFree(GetProcessHeap(), 0, value);
2258 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2259 if (!valueA || lstrcmpA(valueA, appName))
2260 ret = TRUE;
2261 HeapFree(GetProcessHeap(), 0, valueA);
2263 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
2264 if ((openWithIcon && !valueA) ||
2265 (!openWithIcon && valueA) ||
2266 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
2267 ret = TRUE;
2268 HeapFree(GetProcessHeap(), 0, valueA);
2270 RegCloseKey(assocKey);
2272 else
2274 WINE_ERR("error opening associations registry key\n");
2275 ret = FALSE;
2277 return ret;
2280 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2281 LPCSTR appName, LPCSTR desktopFile, LPCSTR openWithIcon)
2283 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2284 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2285 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2286 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2287 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2288 HKEY assocKey = NULL;
2289 HKEY subkey = NULL;
2290 WCHAR *mimeTypeW = NULL;
2291 WCHAR *appNameW = NULL;
2292 WCHAR *desktopFileW = NULL;
2293 WCHAR *openWithIconW = NULL;
2295 assocKey = open_associations_reg_key();
2296 if (assocKey == NULL)
2298 WINE_ERR("could not open file associations key\n");
2299 goto done;
2302 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2304 WINE_ERR("could not create extension subkey\n");
2305 goto done;
2308 mimeTypeW = utf8_chars_to_wchars(mimeType);
2309 if (mimeTypeW == NULL)
2311 WINE_ERR("out of memory\n");
2312 goto done;
2315 appNameW = utf8_chars_to_wchars(appName);
2316 if (appNameW == NULL)
2318 WINE_ERR("out of memory\n");
2319 goto done;
2322 desktopFileW = utf8_chars_to_wchars(desktopFile);
2323 if (desktopFileW == NULL)
2325 WINE_ERR("out of memory\n");
2326 goto done;
2329 if (openWithIcon)
2331 openWithIconW = utf8_chars_to_wchars(openWithIcon);
2332 if (openWithIconW == NULL)
2334 WINE_ERR("out of memory\n");
2335 goto done;
2339 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2340 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2341 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2342 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2343 if (openWithIcon)
2344 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
2345 else
2346 RegDeleteValueW(subkey, OpenWithIconW);
2348 done:
2349 RegCloseKey(assocKey);
2350 RegCloseKey(subkey);
2351 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2352 HeapFree(GetProcessHeap(), 0, appNameW);
2353 HeapFree(GetProcessHeap(), 0, desktopFileW);
2354 HeapFree(GetProcessHeap(), 0, openWithIconW);
2357 static BOOL cleanup_associations(void)
2359 static const WCHAR openW[] = {'o','p','e','n',0};
2360 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2361 HKEY assocKey;
2362 BOOL hasChanged = FALSE;
2363 if ((assocKey = open_associations_reg_key()))
2365 int i;
2366 BOOL done = FALSE;
2367 for (i = 0; !done;)
2369 WCHAR *extensionW = NULL;
2370 DWORD size = 1024;
2371 LSTATUS ret;
2375 HeapFree(GetProcessHeap(), 0, extensionW);
2376 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2377 if (extensionW == NULL)
2379 WINE_ERR("out of memory\n");
2380 ret = ERROR_OUTOFMEMORY;
2381 break;
2383 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2384 size *= 2;
2385 } while (ret == ERROR_MORE_DATA);
2387 if (ret == ERROR_SUCCESS)
2389 WCHAR *command;
2390 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2391 if (command == NULL)
2393 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2394 if (desktopFile)
2396 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2397 remove(desktopFile);
2399 RegDeleteKeyW(assocKey, extensionW);
2400 hasChanged = TRUE;
2401 HeapFree(GetProcessHeap(), 0, desktopFile);
2403 else
2404 i++;
2405 HeapFree(GetProcessHeap(), 0, command);
2407 else
2409 if (ret != ERROR_NO_MORE_ITEMS)
2410 WINE_ERR("error %d while reading registry\n", ret);
2411 done = TRUE;
2413 HeapFree(GetProcessHeap(), 0, extensionW);
2415 RegCloseKey(assocKey);
2417 else
2418 WINE_ERR("could not open file associations key\n");
2419 return hasChanged;
2422 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2423 const char *mime_type, const char *comment)
2425 BOOL ret = FALSE;
2426 char *filename;
2428 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2429 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2431 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2432 if (filename)
2434 FILE *packageFile = fopen(filename, "w");
2435 if (packageFile)
2437 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2438 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2439 fprintf(packageFile, " <mime-type type=\"");
2440 write_xml_text(packageFile, mime_type);
2441 fprintf(packageFile, "\">\n");
2442 fprintf(packageFile, " <glob pattern=\"*");
2443 write_xml_text(packageFile, dot_extension);
2444 fprintf(packageFile, "\"/>\n");
2445 if (comment)
2447 fprintf(packageFile, " <comment>");
2448 write_xml_text(packageFile, comment);
2449 fprintf(packageFile, "</comment>\n");
2451 fprintf(packageFile, " </mime-type>\n");
2452 fprintf(packageFile, "</mime-info>\n");
2453 ret = TRUE;
2454 fclose(packageFile);
2456 else
2457 WINE_ERR("error writing file %s\n", filename);
2458 HeapFree(GetProcessHeap(), 0, filename);
2460 else
2461 WINE_ERR("out of memory\n");
2462 return ret;
2465 static BOOL is_extension_blacklisted(LPCWSTR extension)
2467 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2468 static const WCHAR comW[] = {'.','c','o','m',0};
2469 static const WCHAR exeW[] = {'.','e','x','e',0};
2470 static const WCHAR msiW[] = {'.','m','s','i',0};
2472 if (!strcmpiW(extension, comW) ||
2473 !strcmpiW(extension, exeW) ||
2474 !strcmpiW(extension, msiW))
2475 return TRUE;
2476 return FALSE;
2479 static const char* get_special_mime_type(LPCWSTR extension)
2481 static const WCHAR lnkW[] = {'.','l','n','k',0};
2482 if (!strcmpiW(extension, lnkW))
2483 return "application/x-ms-shortcut";
2484 return NULL;
2487 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2488 const char *friendlyAppName, const char *mimeType,
2489 const char *progId, const char *openWithIcon)
2491 BOOL ret = FALSE;
2492 FILE *desktop;
2494 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2495 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2496 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2498 desktop = fopen(desktopPath, "w");
2499 if (desktop)
2501 fprintf(desktop, "[Desktop Entry]\n");
2502 fprintf(desktop, "Type=Application\n");
2503 fprintf(desktop, "Name=%s\n", friendlyAppName);
2504 fprintf(desktop, "MimeType=%s;\n", mimeType);
2505 fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId);
2506 fprintf(desktop, "NoDisplay=true\n");
2507 fprintf(desktop, "StartupNotify=true\n");
2508 if (openWithIcon)
2509 fprintf(desktop, "Icon=%s\n", openWithIcon);
2510 ret = TRUE;
2511 fclose(desktop);
2513 else
2514 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2515 return ret;
2518 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2520 static const WCHAR openW[] = {'o','p','e','n',0};
2521 struct wine_rb_tree mimeProgidTree = { winemenubuilder_rb_string_compare };
2522 struct list nativeMimeTypes = LIST_INIT(nativeMimeTypes);
2523 LSTATUS ret = 0;
2524 int i;
2525 BOOL hasChanged = FALSE;
2527 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2529 WINE_ERR("could not build native MIME types\n");
2530 return FALSE;
2533 for (i = 0; ; i++)
2535 WCHAR *extensionW = NULL;
2536 DWORD size = 1024;
2540 HeapFree(GetProcessHeap(), 0, extensionW);
2541 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2542 if (extensionW == NULL)
2544 WINE_ERR("out of memory\n");
2545 ret = ERROR_OUTOFMEMORY;
2546 break;
2548 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2549 size *= 2;
2550 } while (ret == ERROR_MORE_DATA);
2552 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2554 char *extensionA = NULL;
2555 WCHAR *commandW = NULL;
2556 WCHAR *executableW = NULL;
2557 char *openWithIconA = NULL;
2558 WCHAR *friendlyDocNameW = NULL;
2559 char *friendlyDocNameA = NULL;
2560 WCHAR *iconW = NULL;
2561 char *iconA = NULL;
2562 WCHAR *contentTypeW = NULL;
2563 char *mimeTypeA = NULL;
2564 WCHAR *friendlyAppNameW = NULL;
2565 char *friendlyAppNameA = NULL;
2566 WCHAR *progIdW = NULL;
2567 char *progIdA = NULL;
2568 char *mimeProgId = NULL;
2570 extensionA = wchars_to_utf8_chars(strlwrW(extensionW));
2571 if (extensionA == NULL)
2573 WINE_ERR("out of memory\n");
2574 goto end;
2577 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2578 if (friendlyDocNameW)
2580 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2581 if (friendlyDocNameA == NULL)
2583 WINE_ERR("out of memory\n");
2584 goto end;
2588 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2590 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2591 if (contentTypeW)
2592 strlwrW(contentTypeW);
2594 if (!freedesktop_mime_type_for_extension(&nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2595 goto end;
2597 if (mimeTypeA == NULL)
2599 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2600 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2601 else if ((get_special_mime_type(extensionW)))
2602 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2603 else
2604 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2606 if (mimeTypeA != NULL)
2608 /* GNOME seems to ignore the <icon> tag in MIME packages,
2609 * and the default name is more intuitive anyway.
2611 if (iconW)
2613 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2614 if (flattened_mime)
2616 int index = 0;
2617 WCHAR *comma = strrchrW(iconW, ',');
2618 if (comma)
2620 *comma = 0;
2621 index = atoiW(comma + 1);
2623 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2624 HeapFree(GetProcessHeap(), 0, flattened_mime);
2628 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2629 hasChanged = TRUE;
2631 else
2633 WINE_FIXME("out of memory\n");
2634 goto end;
2638 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2639 if (commandW == NULL)
2640 /* no command => no application is associated */
2641 goto end;
2643 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2644 if (executableW)
2645 openWithIconA = extract_icon(executableW, 0, NULL, FALSE);
2647 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, openW);
2648 if (friendlyAppNameW)
2650 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2651 if (friendlyAppNameA == NULL)
2653 WINE_ERR("out of memory\n");
2654 goto end;
2657 else
2659 friendlyAppNameA = heap_printf("A Wine application");
2660 if (friendlyAppNameA == NULL)
2662 WINE_ERR("out of memory\n");
2663 goto end;
2667 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2668 if (progIdW)
2670 progIdA = escape(progIdW);
2671 if (progIdA == NULL)
2673 WINE_ERR("out of memory\n");
2674 goto end;
2677 else
2678 goto end; /* no progID => not a file type association */
2680 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2681 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2682 if (mimeProgId)
2684 struct rb_string_entry *entry;
2685 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2687 HeapFree(GetProcessHeap(), 0, mimeProgId);
2688 goto end;
2690 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2691 if (!entry)
2693 WINE_ERR("out of memory allocating rb_string_entry\n");
2694 goto end;
2696 entry->string = mimeProgId;
2697 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2699 WINE_ERR("error updating rb tree\n");
2700 goto end;
2704 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, openWithIconA))
2706 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2707 if (desktopPath)
2709 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2711 hasChanged = TRUE;
2712 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, desktopPath, openWithIconA);
2714 HeapFree(GetProcessHeap(), 0, desktopPath);
2718 end:
2719 HeapFree(GetProcessHeap(), 0, extensionA);
2720 HeapFree(GetProcessHeap(), 0, commandW);
2721 HeapFree(GetProcessHeap(), 0, executableW);
2722 HeapFree(GetProcessHeap(), 0, openWithIconA);
2723 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2724 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2725 HeapFree(GetProcessHeap(), 0, iconW);
2726 HeapFree(GetProcessHeap(), 0, iconA);
2727 HeapFree(GetProcessHeap(), 0, contentTypeW);
2728 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2729 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2730 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2731 HeapFree(GetProcessHeap(), 0, progIdW);
2732 HeapFree(GetProcessHeap(), 0, progIdA);
2734 HeapFree(GetProcessHeap(), 0, extensionW);
2735 if (ret != ERROR_SUCCESS)
2736 break;
2739 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2740 free_native_mime_types(&nativeMimeTypes);
2741 return hasChanged;
2744 static char *get_start_exe_path(void)
2746 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2747 '\\','s','t','a','r','t','.','e','x','e',0};
2748 WCHAR start_path[MAX_PATH];
2749 GetWindowsDirectoryW(start_path, MAX_PATH);
2750 lstrcatW(start_path, startW);
2751 return escape(start_path);
2754 static char* escape_unix_link_arg(LPCSTR unix_link)
2756 char *ret = NULL;
2757 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2758 if (unix_linkW)
2760 char *escaped_lnk = escape(unix_linkW);
2761 if (escaped_lnk)
2763 ret = heap_printf("/Unix %s", escaped_lnk);
2764 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2766 HeapFree(GetProcessHeap(), 0, unix_linkW);
2768 return ret;
2771 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2773 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2774 '\\','s','t','a','r','t','.','e','x','e',0};
2775 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2776 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2777 char *wmclass = NULL;
2778 WCHAR szTmp[INFOTIPSIZE];
2779 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2780 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH], szWMClass[MAX_PATH];
2781 int iIconId = 0, r = -1;
2782 DWORD csidl = -1;
2783 HANDLE hsem = NULL;
2784 char *unix_link = NULL;
2785 char *start_path = NULL;
2787 if ( !link )
2789 WINE_ERR("Link name is null\n");
2790 return FALSE;
2793 if( !GetLinkLocation( link, &csidl, &link_name ) )
2795 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2796 return TRUE;
2798 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2800 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2801 return TRUE;
2803 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2805 szTmp[0] = 0;
2806 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2807 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2808 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2810 szTmp[0] = 0;
2811 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2812 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2813 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2815 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2816 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2817 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2818 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2820 szTmp[0] = 0;
2821 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2822 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2823 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2825 szWMClass[0] = 0;
2827 if( !szPath[0] )
2829 LPITEMIDLIST pidl = NULL;
2830 IShellLinkW_GetIDList( sl, &pidl );
2831 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2832 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2835 /* extract the icon */
2836 if( szIconPath[0] )
2837 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2838 else
2839 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2841 /* fail - try once again after parent process exit */
2842 if( !icon_name )
2844 if (bWait)
2846 WINE_WARN("Unable to extract icon, deferring.\n");
2847 goto cleanup;
2849 WINE_ERR("failed to extract icon from %s\n",
2850 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2853 unix_link = wine_get_unix_file_name(link);
2854 if (unix_link == NULL)
2856 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2857 goto cleanup;
2860 /* check the path */
2861 if( szPath[0] )
2863 static const WCHAR exeW[] = {'.','e','x','e',0};
2864 WCHAR *p;
2866 /* check for .exe extension */
2867 if (!(p = strrchrW( szPath, '.' )) ||
2868 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2869 lstrcmpiW( p, exeW ))
2871 /* Not .exe - use 'start.exe' to launch this file */
2872 p = szArgs + lstrlenW(szPath) + 2;
2873 if (szArgs[0])
2875 p[0] = ' ';
2876 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2877 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2879 else
2880 p[0] = 0;
2882 szArgs[0] = '"';
2883 lstrcpyW(szArgs + 1, szPath);
2884 p[-1] = '"';
2886 GetWindowsDirectoryW(szPath, MAX_PATH);
2887 lstrcatW(szPath, startW);
2889 else
2891 /* FIXME: Use AppUserModelID if present. */
2892 WCHAR *p = PathFindFileNameW(szPath);
2894 lstrcpyW(szWMClass, p);
2895 CharLowerW(szWMClass);
2898 /* convert app working dir */
2899 if (szWorkDir[0])
2900 work_dir = wine_get_unix_file_name( szWorkDir );
2902 else
2904 /* if there's no path... try run the link itself */
2905 lstrcpynW(szArgs, link, MAX_PATH);
2906 GetWindowsDirectoryW(szPath, MAX_PATH);
2907 lstrcatW(szPath, startW);
2910 /* escape the path and parameters */
2911 escaped_path = escape(szPath);
2912 escaped_args = escape(szArgs);
2913 description = wchars_to_utf8_chars(szDescription);
2914 wmclass = wchars_to_utf8_chars(szWMClass);
2915 if (escaped_path == NULL || escaped_args == NULL || description == NULL || wmclass == NULL)
2917 WINE_ERR("out of memory allocating/escaping parameters\n");
2918 goto cleanup;
2921 start_path = get_start_exe_path();
2922 if (start_path == NULL)
2924 WINE_ERR("out of memory\n");
2925 goto cleanup;
2928 /* building multiple menus concurrently has race conditions */
2929 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2930 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2932 WINE_ERR("failed wait for semaphore\n");
2933 goto cleanup;
2936 if (in_desktop_dir(csidl))
2938 char *location;
2939 const char *lastEntry;
2940 lastEntry = strrchr(link_name, '/');
2941 if (lastEntry == NULL)
2942 lastEntry = link_name;
2943 else
2944 ++lastEntry;
2945 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2946 if (location)
2948 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2950 char *link_arg = escape_unix_link_arg(unix_link);
2951 if (link_arg)
2953 r = !write_desktop_entry(unix_link, location, lastEntry,
2954 start_path, link_arg, description, work_dir, icon_name, wmclass);
2955 HeapFree(GetProcessHeap(), 0, link_arg);
2958 else
2959 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name, wmclass);
2960 if (r == 0)
2961 chmod(location, 0755);
2962 HeapFree(GetProcessHeap(), 0, location);
2965 else
2967 char *link_arg = escape_unix_link_arg(unix_link);
2968 if (link_arg)
2970 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name, wmclass);
2971 HeapFree(GetProcessHeap(), 0, link_arg);
2975 ReleaseSemaphore( hsem, 1, NULL );
2977 cleanup:
2978 if (hsem) CloseHandle( hsem );
2979 HeapFree( GetProcessHeap(), 0, icon_name );
2980 HeapFree( GetProcessHeap(), 0, work_dir );
2981 HeapFree( GetProcessHeap(), 0, link_name );
2982 HeapFree( GetProcessHeap(), 0, escaped_args );
2983 HeapFree( GetProcessHeap(), 0, escaped_path );
2984 HeapFree( GetProcessHeap(), 0, description );
2985 HeapFree( GetProcessHeap(), 0, wmclass );
2986 HeapFree( GetProcessHeap(), 0, unix_link );
2987 HeapFree( GetProcessHeap(), 0, start_path );
2989 if (r && !bWait)
2990 WINE_ERR("failed to build the menu\n" );
2992 return ( r == 0 );
2995 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2997 char *link_name = NULL, *icon_name = NULL;
2998 DWORD csidl = -1;
2999 LPWSTR urlPath = NULL;
3000 char *escaped_urlPath = NULL;
3001 HRESULT hr;
3002 HANDLE hSem = NULL;
3003 BOOL ret = TRUE;
3004 int r = -1;
3005 char *unix_link = NULL;
3006 IPropertySetStorage *pPropSetStg;
3007 IPropertyStorage *pPropStg;
3008 PROPSPEC ps[2];
3009 PROPVARIANT pv[2];
3010 char *start_path = NULL;
3011 BOOL has_icon = FALSE;
3013 if ( !link )
3015 WINE_ERR("Link name is null\n");
3016 return TRUE;
3019 if( !GetLinkLocation( link, &csidl, &link_name ) )
3021 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
3022 return TRUE;
3024 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
3026 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3027 ret = TRUE;
3028 goto cleanup;
3030 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
3032 hr = url->lpVtbl->GetURL(url, &urlPath);
3033 if (FAILED(hr))
3035 ret = TRUE;
3036 goto cleanup;
3038 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
3040 unix_link = wine_get_unix_file_name(link);
3041 if (unix_link == NULL)
3043 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
3044 goto cleanup;
3047 escaped_urlPath = escape(urlPath);
3048 if (escaped_urlPath == NULL)
3050 WINE_ERR("couldn't escape url, out of memory\n");
3051 goto cleanup;
3054 start_path = get_start_exe_path();
3055 if (start_path == NULL)
3057 WINE_ERR("out of memory\n");
3058 goto cleanup;
3061 ps[0].ulKind = PRSPEC_PROPID;
3062 ps[0].u.propid = PID_IS_ICONFILE;
3063 ps[1].ulKind = PRSPEC_PROPID;
3064 ps[1].u.propid = PID_IS_ICONINDEX;
3066 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
3067 if (SUCCEEDED(hr))
3069 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
3070 if (SUCCEEDED(hr))
3072 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
3073 if (SUCCEEDED(hr))
3075 if (pv[0].vt == VT_LPWSTR && pv[0].u.pwszVal && pv[0].u.pwszVal[0])
3077 has_icon = TRUE;
3078 icon_name = extract_icon( pv[0].u.pwszVal, pv[1].u.iVal, NULL, bWait );
3080 WINE_TRACE("URL icon path: %s icon index: %d icon name: %s\n", wine_dbgstr_w(pv[0].u.pwszVal), pv[1].u.iVal, icon_name);
3082 PropVariantClear(&pv[0]);
3083 PropVariantClear(&pv[1]);
3085 IPropertyStorage_Release(pPropStg);
3087 IPropertySetStorage_Release(pPropSetStg);
3090 /* fail - try once again after parent process exit */
3091 if( has_icon && !icon_name )
3093 if (bWait)
3095 WINE_WARN("Unable to extract icon, deferring.\n");
3096 ret = FALSE;
3097 goto cleanup;
3099 WINE_ERR("failed to extract icon from %s\n",
3100 wine_dbgstr_w( pv[0].u.pwszVal ));
3103 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3104 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3106 WINE_ERR("failed wait for semaphore\n");
3107 goto cleanup;
3109 if (in_desktop_dir(csidl))
3111 char *location;
3112 const char *lastEntry;
3113 lastEntry = strrchr(link_name, '/');
3114 if (lastEntry == NULL)
3115 lastEntry = link_name;
3116 else
3117 ++lastEntry;
3118 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
3119 if (location)
3121 r = !write_desktop_entry(NULL, location, lastEntry, start_path, escaped_urlPath, NULL, NULL, icon_name, NULL);
3122 if (r == 0)
3123 chmod(location, 0755);
3124 HeapFree(GetProcessHeap(), 0, location);
3127 else
3128 r = !write_menu_entry(unix_link, link_name, start_path, escaped_urlPath, NULL, NULL, icon_name, NULL);
3129 ret = (r == 0);
3130 ReleaseSemaphore(hSem, 1, NULL);
3132 cleanup:
3133 if (hSem)
3134 CloseHandle(hSem);
3135 HeapFree( GetProcessHeap(), 0, icon_name );
3136 HeapFree(GetProcessHeap(), 0, link_name);
3137 CoTaskMemFree( urlPath );
3138 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
3139 HeapFree(GetProcessHeap(), 0, unix_link);
3140 return ret;
3143 static BOOL WaitForParentProcess( void )
3145 PROCESSENTRY32 procentry;
3146 HANDLE hsnapshot = NULL, hprocess = NULL;
3147 DWORD ourpid = GetCurrentProcessId();
3148 BOOL ret = FALSE, rc;
3150 WINE_TRACE("Waiting for parent process\n");
3151 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
3152 INVALID_HANDLE_VALUE)
3154 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3155 goto done;
3158 procentry.dwSize = sizeof(PROCESSENTRY32);
3159 rc = Process32First( hsnapshot, &procentry );
3160 while (rc)
3162 if (procentry.th32ProcessID == ourpid) break;
3163 rc = Process32Next( hsnapshot, &procentry );
3165 if (!rc)
3167 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
3168 goto done;
3171 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
3172 NULL)
3174 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
3175 GetLastError());
3176 goto done;
3179 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
3180 ret = TRUE;
3181 else
3182 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3184 done:
3185 if (hprocess) CloseHandle( hprocess );
3186 if (hsnapshot) CloseHandle( hsnapshot );
3187 return ret;
3190 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
3192 IShellLinkW *sl;
3193 IPersistFile *pf;
3194 HRESULT r;
3195 WCHAR fullname[MAX_PATH];
3196 DWORD len;
3198 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
3200 if( !linkname[0] )
3202 WINE_ERR("link name missing\n");
3203 return FALSE;
3206 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
3207 if (len==0 || len>MAX_PATH)
3209 WINE_ERR("couldn't get full path of link file\n");
3210 return FALSE;
3213 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3214 &IID_IShellLinkW, (LPVOID *) &sl );
3215 if( FAILED( r ) )
3217 WINE_ERR("No IID_IShellLink\n");
3218 return FALSE;
3221 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
3222 if( FAILED( r ) )
3224 WINE_ERR("No IID_IPersistFile\n");
3225 return FALSE;
3228 r = IPersistFile_Load( pf, fullname, STGM_READ );
3229 if( SUCCEEDED( r ) )
3231 /* If something fails (eg. Couldn't extract icon)
3232 * wait for parent process and try again
3234 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
3236 WaitForParentProcess();
3237 InvokeShellLinker( sl, fullname, FALSE );
3240 else
3242 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
3245 IPersistFile_Release( pf );
3246 IShellLinkW_Release( sl );
3248 return !r;
3251 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
3253 IUniformResourceLocatorW *url;
3254 IPersistFile *pf;
3255 HRESULT r;
3256 WCHAR fullname[MAX_PATH];
3257 DWORD len;
3259 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
3261 if( !urlname[0] )
3263 WINE_ERR("URL name missing\n");
3264 return FALSE;
3267 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
3268 if (len==0 || len>MAX_PATH)
3270 WINE_ERR("couldn't get full path of URL file\n");
3271 return FALSE;
3274 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
3275 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
3276 if( FAILED( r ) )
3278 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3279 return FALSE;
3282 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
3283 if( FAILED( r ) )
3285 WINE_ERR("No IID_IPersistFile\n");
3286 return FALSE;
3288 r = IPersistFile_Load( pf, fullname, STGM_READ );
3289 if( SUCCEEDED( r ) )
3291 /* If something fails (eg. Couldn't extract icon)
3292 * wait for parent process and try again
3294 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
3296 WaitForParentProcess();
3297 InvokeShellLinkerForURL( url, fullname, FALSE );
3301 IPersistFile_Release( pf );
3302 url->lpVtbl->Release( url );
3304 return !r;
3307 static void RefreshFileTypeAssociations(void)
3309 HANDLE hSem = NULL;
3310 char *mime_dir = NULL;
3311 char *packages_dir = NULL;
3312 char *applications_dir = NULL;
3313 BOOL hasChanged;
3315 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3316 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3318 WINE_ERR("failed wait for semaphore\n");
3319 CloseHandle(hSem);
3320 hSem = NULL;
3321 goto end;
3324 mime_dir = heap_printf("%s/mime", xdg_data_dir);
3325 if (mime_dir == NULL)
3327 WINE_ERR("out of memory\n");
3328 goto end;
3330 create_directories(mime_dir);
3332 packages_dir = heap_printf("%s/packages", mime_dir);
3333 if (packages_dir == NULL)
3335 WINE_ERR("out of memory\n");
3336 goto end;
3338 create_directories(packages_dir);
3340 applications_dir = heap_printf("%s/applications", xdg_data_dir);
3341 if (applications_dir == NULL)
3343 WINE_ERR("out of memory\n");
3344 goto end;
3346 create_directories(applications_dir);
3348 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3349 hasChanged |= cleanup_associations();
3350 if (hasChanged)
3352 const char *argv[3];
3354 argv[0] = "update-mime-database";
3355 argv[1] = mime_dir;
3356 argv[2] = NULL;
3357 _spawnvp( _P_DETACH, argv[0], argv );
3359 argv[0] = "update-desktop-database";
3360 argv[1] = applications_dir;
3361 _spawnvp( _P_DETACH, argv[0], argv );
3364 end:
3365 if (hSem)
3367 ReleaseSemaphore(hSem, 1, NULL);
3368 CloseHandle(hSem);
3370 HeapFree(GetProcessHeap(), 0, mime_dir);
3371 HeapFree(GetProcessHeap(), 0, packages_dir);
3372 HeapFree(GetProcessHeap(), 0, applications_dir);
3375 static void cleanup_menus(void)
3377 HKEY hkey;
3379 hkey = open_menus_reg_key();
3380 if (hkey)
3382 int i;
3383 LSTATUS lret = ERROR_SUCCESS;
3384 for (i = 0; lret == ERROR_SUCCESS; )
3386 WCHAR *value = NULL;
3387 WCHAR *data = NULL;
3388 DWORD valueSize = 4096;
3389 DWORD dataSize = 4096;
3390 while (1)
3392 lret = ERROR_OUTOFMEMORY;
3393 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3394 if (value == NULL)
3395 break;
3396 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3397 if (data == NULL)
3398 break;
3399 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3400 if (lret != ERROR_MORE_DATA)
3401 break;
3402 valueSize *= 2;
3403 dataSize *= 2;
3404 HeapFree(GetProcessHeap(), 0, value);
3405 HeapFree(GetProcessHeap(), 0, data);
3406 value = data = NULL;
3408 if (lret == ERROR_SUCCESS)
3410 char *unix_file;
3411 char *windows_file;
3412 unix_file = wchars_to_unix_chars(value);
3413 windows_file = wchars_to_unix_chars(data);
3414 if (unix_file != NULL && windows_file != NULL)
3416 struct stat filestats;
3417 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3419 WINE_TRACE("removing menu related file %s\n", unix_file);
3420 remove(unix_file);
3421 RegDeleteValueW(hkey, value);
3423 else
3424 i++;
3426 else
3428 WINE_ERR("out of memory enumerating menus\n");
3429 lret = ERROR_OUTOFMEMORY;
3431 HeapFree(GetProcessHeap(), 0, unix_file);
3432 HeapFree(GetProcessHeap(), 0, windows_file);
3434 else if (lret != ERROR_NO_MORE_ITEMS)
3435 WINE_ERR("error %d reading registry\n", lret);
3436 HeapFree(GetProcessHeap(), 0, value);
3437 HeapFree(GetProcessHeap(), 0, data);
3439 RegCloseKey(hkey);
3441 else
3442 WINE_ERR("error opening registry key, menu cleanup failed\n");
3445 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3447 char *utf8lnkPath = NULL;
3448 char *utf8OutputPath = NULL;
3449 WCHAR *winLnkPath = NULL;
3450 IShellLinkW *shellLink = NULL;
3451 IPersistFile *persistFile = NULL;
3452 WCHAR szTmp[MAX_PATH];
3453 WCHAR szPath[MAX_PATH];
3454 WCHAR szArgs[INFOTIPSIZE];
3455 WCHAR szIconPath[MAX_PATH];
3456 int iconId;
3457 IStream *stream = NULL;
3458 ICONDIRENTRY *pIconDirEntries = NULL;
3459 int numEntries;
3460 HRESULT hr;
3462 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3463 if (utf8lnkPath == NULL)
3465 WINE_ERR("out of memory converting paths\n");
3466 goto end;
3469 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3470 if (utf8OutputPath == NULL)
3472 WINE_ERR("out of memory converting paths\n");
3473 goto end;
3476 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3477 if (winLnkPath == NULL)
3479 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3480 goto end;
3483 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3484 &IID_IShellLinkW, (LPVOID*)&shellLink);
3485 if (FAILED(hr))
3487 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3488 goto end;
3491 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3492 if (FAILED(hr))
3494 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3495 goto end;
3498 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3499 if (FAILED(hr))
3501 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3502 goto end;
3505 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3506 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3507 szTmp[0] = 0;
3508 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3509 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3511 if(!szPath[0])
3513 LPITEMIDLIST pidl = NULL;
3514 IShellLinkW_GetIDList(shellLink, &pidl);
3515 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3516 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3519 if (szIconPath[0])
3521 hr = open_icon(szIconPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3522 if (SUCCEEDED(hr))
3523 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3525 else
3527 hr = open_icon(szPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3528 if (SUCCEEDED(hr))
3529 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3532 end:
3533 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3534 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3535 HeapFree(GetProcessHeap(), 0, winLnkPath);
3536 if (shellLink != NULL)
3537 IShellLinkW_Release(shellLink);
3538 if (persistFile != NULL)
3539 IPersistFile_Release(persistFile);
3540 if (stream != NULL)
3541 IStream_Release(stream);
3542 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
3545 static WCHAR *next_token( LPWSTR *p )
3547 LPWSTR token = NULL, t = *p;
3549 if( !t )
3550 return NULL;
3552 while( t && !token )
3554 switch( *t )
3556 case ' ':
3557 t++;
3558 continue;
3559 case '"':
3560 /* unquote the token */
3561 token = ++t;
3562 t = strchrW( token, '"' );
3563 if( t )
3564 *t++ = 0;
3565 break;
3566 case 0:
3567 t = NULL;
3568 break;
3569 default:
3570 token = t;
3571 t = strchrW( token, ' ' );
3572 if( t )
3573 *t++ = 0;
3574 break;
3577 *p = t;
3578 return token;
3581 static BOOL init_xdg(void)
3583 WCHAR shellDesktopPath[MAX_PATH];
3584 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3585 if (SUCCEEDED(hr))
3586 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3587 if (xdg_desktop_dir == NULL)
3589 WINE_ERR("error looking up the desktop directory\n");
3590 return FALSE;
3593 if (getenv("XDG_CONFIG_HOME"))
3594 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3595 else
3596 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3597 if (xdg_config_dir)
3599 create_directories(xdg_config_dir);
3600 if (getenv("XDG_DATA_HOME"))
3601 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3602 else
3603 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3604 if (xdg_data_dir)
3606 char *buffer;
3607 create_directories(xdg_data_dir);
3608 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3609 if (buffer)
3611 mkdir(buffer, 0777);
3612 HeapFree(GetProcessHeap(), 0, buffer);
3614 return TRUE;
3616 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3618 WINE_ERR("out of memory\n");
3619 return FALSE;
3622 /***********************************************************************
3624 * wWinMain
3626 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3628 static const WCHAR dash_aW[] = {'-','a',0};
3629 static const WCHAR dash_rW[] = {'-','r',0};
3630 static const WCHAR dash_tW[] = {'-','t',0};
3631 static const WCHAR dash_uW[] = {'-','u',0};
3632 static const WCHAR dash_wW[] = {'-','w',0};
3634 LPWSTR token = NULL, p;
3635 BOOL bWait = FALSE;
3636 BOOL bURL = FALSE;
3637 HRESULT hr;
3638 int ret = 0;
3640 if (!init_xdg())
3641 return 1;
3643 hr = CoInitialize(NULL);
3644 if (FAILED(hr))
3646 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3647 return 1;
3650 for( p = cmdline; p && *p; )
3652 token = next_token( &p );
3653 if( !token )
3654 break;
3655 if( !strcmpW( token, dash_aW ) )
3657 RefreshFileTypeAssociations();
3658 continue;
3660 if( !strcmpW( token, dash_rW ) )
3662 cleanup_menus();
3663 continue;
3665 if( !strcmpW( token, dash_wW ) )
3666 bWait = TRUE;
3667 else if ( !strcmpW( token, dash_uW ) )
3668 bURL = TRUE;
3669 else if ( !strcmpW( token, dash_tW ) )
3671 WCHAR *lnkFile = next_token( &p );
3672 if (lnkFile)
3674 WCHAR *outputFile = next_token( &p );
3675 if (outputFile)
3676 thumbnail_lnk(lnkFile, outputFile);
3679 else if( token[0] == '-' )
3681 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3683 else
3685 BOOL bRet;
3687 if (bURL)
3688 bRet = Process_URL( token, bWait );
3689 else
3690 bRet = Process_Link( token, bWait );
3691 if (!bRet)
3693 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3694 ret = 1;
3699 CoUninitialize();
3700 return ret;