crypt32: Test CryptStringToBinary with weird Base64.
[wine.git] / programs / winemenubuilder / winemenubuilder.c
blob154b575d6130518674553daa008e8f210b3843b2
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)
1451 FILE *file;
1453 WINE_TRACE("(%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));
1457 file = fopen(location, "w");
1458 if (file == NULL)
1459 return FALSE;
1461 fprintf(file, "[Desktop Entry]\n");
1462 fprintf(file, "Name=%s\n", linkname);
1463 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1464 wine_get_config_dir(), path, args);
1465 fprintf(file, "Type=Application\n");
1466 fprintf(file, "StartupNotify=true\n");
1467 if (descr && lstrlenA(descr))
1468 fprintf(file, "Comment=%s\n", descr);
1469 if (workdir && lstrlenA(workdir))
1470 fprintf(file, "Path=%s\n", workdir);
1471 if (icon && lstrlenA(icon))
1472 fprintf(file, "Icon=%s\n", icon);
1474 fclose(file);
1476 if (unix_link)
1478 DWORD ret = register_menus_entry(location, unix_link);
1479 if (ret != ERROR_SUCCESS)
1480 return FALSE;
1483 return TRUE;
1486 static BOOL write_directory_entry(const char *directory, const char *location)
1488 FILE *file;
1490 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1492 file = fopen(location, "w");
1493 if (file == NULL)
1494 return FALSE;
1496 fprintf(file, "[Desktop Entry]\n");
1497 fprintf(file, "Type=Directory\n");
1498 if (strcmp(directory, "wine") == 0)
1500 fprintf(file, "Name=Wine\n");
1501 fprintf(file, "Icon=wine\n");
1503 else
1505 fprintf(file, "Name=%s\n", directory);
1506 fprintf(file, "Icon=folder\n");
1509 fclose(file);
1510 return TRUE;
1513 static BOOL write_menu_file(const char *unix_link, const char *filename)
1515 char *tempfilename;
1516 FILE *tempfile = NULL;
1517 char *lastEntry;
1518 char *name = NULL;
1519 char *menuPath = NULL;
1520 int i;
1521 int count = 0;
1522 BOOL ret = FALSE;
1524 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1526 while (1)
1528 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1529 if (tempfilename)
1531 int tempfd = mkstemps(tempfilename, 0);
1532 if (tempfd >= 0)
1534 tempfile = fdopen(tempfd, "w");
1535 if (tempfile)
1536 break;
1537 close(tempfd);
1538 goto end;
1540 else if (errno == EEXIST)
1542 HeapFree(GetProcessHeap(), 0, tempfilename);
1543 continue;
1545 HeapFree(GetProcessHeap(), 0, tempfilename);
1547 return FALSE;
1550 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1551 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1552 fprintf(tempfile, "<Menu>\n");
1553 fprintf(tempfile, " <Name>Applications</Name>\n");
1555 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1556 if (name == NULL) goto end;
1557 lastEntry = name;
1558 for (i = 0; filename[i]; i++)
1560 name[i] = filename[i];
1561 if (filename[i] == '/')
1563 char *dir_file_name;
1564 struct stat st;
1565 name[i] = 0;
1566 fprintf(tempfile, " <Menu>\n");
1567 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1568 write_xml_text(tempfile, name);
1569 fprintf(tempfile, "</Name>\n");
1570 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1571 write_xml_text(tempfile, name);
1572 fprintf(tempfile, ".directory</Directory>\n");
1573 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1574 xdg_data_dir, count ? "" : "wine-", name);
1575 if (dir_file_name)
1577 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1578 write_directory_entry(lastEntry, dir_file_name);
1579 HeapFree(GetProcessHeap(), 0, dir_file_name);
1581 name[i] = '-';
1582 lastEntry = &name[i+1];
1583 ++count;
1586 name[i] = 0;
1588 fprintf(tempfile, " <Include>\n");
1589 fprintf(tempfile, " <Filename>");
1590 write_xml_text(tempfile, name);
1591 fprintf(tempfile, "</Filename>\n");
1592 fprintf(tempfile, " </Include>\n");
1593 for (i = 0; i < count; i++)
1594 fprintf(tempfile, " </Menu>\n");
1595 fprintf(tempfile, "</Menu>\n");
1597 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1598 if (menuPath == NULL) goto end;
1599 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1600 ret = TRUE;
1602 end:
1603 if (tempfile)
1604 fclose(tempfile);
1605 if (ret)
1606 ret = (rename(tempfilename, menuPath) == 0);
1607 if (!ret && tempfilename)
1608 remove(tempfilename);
1609 HeapFree(GetProcessHeap(), 0, tempfilename);
1610 if (ret)
1611 register_menus_entry(menuPath, unix_link);
1612 HeapFree(GetProcessHeap(), 0, name);
1613 HeapFree(GetProcessHeap(), 0, menuPath);
1614 return ret;
1617 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1618 const char *descr, const char *workdir, const char *icon)
1620 const char *linkname;
1621 char *desktopPath = NULL;
1622 char *desktopDir;
1623 char *filename = NULL;
1624 BOOL ret = TRUE;
1626 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1627 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1628 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1630 linkname = strrchr(link, '/');
1631 if (linkname == NULL)
1632 linkname = link;
1633 else
1634 ++linkname;
1636 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1637 if (!desktopPath)
1639 WINE_WARN("out of memory creating menu entry\n");
1640 ret = FALSE;
1641 goto end;
1643 desktopDir = strrchr(desktopPath, '/');
1644 *desktopDir = 0;
1645 if (!create_directories(desktopPath))
1647 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1648 ret = FALSE;
1649 goto end;
1651 *desktopDir = '/';
1652 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1654 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1655 ret = FALSE;
1656 goto end;
1659 filename = heap_printf("wine/%s.desktop", link);
1660 if (!filename || !write_menu_file(unix_link, filename))
1662 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1663 ret = FALSE;
1666 end:
1667 HeapFree(GetProcessHeap(), 0, desktopPath);
1668 HeapFree(GetProcessHeap(), 0, filename);
1669 return ret;
1672 /* This escapes reserved characters in .desktop files' Exec keys. */
1673 static LPSTR escape(LPCWSTR arg)
1675 int i, j;
1676 WCHAR *escaped_string;
1677 char *utf8_string;
1679 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1680 if (escaped_string == NULL) return NULL;
1681 for (i = j = 0; arg[i]; i++)
1683 switch (arg[i])
1685 case '\\':
1686 escaped_string[j++] = '\\';
1687 escaped_string[j++] = '\\';
1688 escaped_string[j++] = '\\';
1689 escaped_string[j++] = '\\';
1690 break;
1691 case ' ':
1692 case '\t':
1693 case '\n':
1694 case '"':
1695 case '\'':
1696 case '>':
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 escaped_string[j++] = '\\';
1710 escaped_string[j++] = '\\';
1711 /* fall through */
1712 default:
1713 escaped_string[j++] = arg[i];
1714 break;
1717 escaped_string[j] = 0;
1719 utf8_string = wchars_to_utf8_chars(escaped_string);
1720 if (utf8_string == NULL)
1722 WINE_ERR("out of memory\n");
1723 goto end;
1726 end:
1727 HeapFree(GetProcessHeap(), 0, escaped_string);
1728 return utf8_string;
1731 /* Return a heap-allocated copy of the unix format difference between the two
1732 * Windows-format paths.
1733 * locn is the owning location
1734 * link is within locn
1736 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1738 char *unix_locn, *unix_link;
1739 char *relative = NULL;
1741 unix_locn = wine_get_unix_file_name(locn);
1742 unix_link = wine_get_unix_file_name(link);
1743 if (unix_locn && unix_link)
1745 size_t len_unix_locn, len_unix_link;
1746 len_unix_locn = strlen (unix_locn);
1747 len_unix_link = strlen (unix_link);
1748 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1750 size_t len_rel;
1751 char *p = strrchr (unix_link + len_unix_locn, '/');
1752 p = strrchr (p, '.');
1753 if (p)
1755 *p = '\0';
1756 len_unix_link = p - unix_link;
1758 len_rel = len_unix_link - len_unix_locn;
1759 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1760 if (relative)
1762 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1766 if (!relative)
1767 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1768 HeapFree(GetProcessHeap(), 0, unix_locn);
1769 HeapFree(GetProcessHeap(), 0, unix_link);
1770 return relative;
1773 /***********************************************************************
1775 * GetLinkLocation
1777 * returns TRUE if successful
1778 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1779 * *relative will contain the address of a heap-allocated copy of the portion
1780 * of the filename that is within the specified location, in unix form
1782 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1784 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1785 DWORD len, i, r, filelen;
1786 const DWORD locations[] = {
1787 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1788 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1789 CSIDL_COMMON_STARTMENU };
1791 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1792 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1793 if (filelen==0 || filelen>MAX_PATH)
1794 return FALSE;
1796 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1798 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1799 * expand or our hardcoded list won't match.
1801 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1802 if (filelen==0 || filelen>MAX_PATH)
1803 return FALSE;
1805 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1807 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1809 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1810 continue;
1812 len = lstrlenW(buffer);
1813 if (len >= MAX_PATH)
1814 continue; /* We've just trashed memory! Hopefully we are OK */
1816 if (len > filelen || filename[len]!='\\')
1817 continue;
1818 /* do a lstrcmpinW */
1819 filename[len] = 0;
1820 r = lstrcmpiW( filename, buffer );
1821 filename[len] = '\\';
1822 if ( r )
1823 continue;
1825 /* return the remainder of the string and link type */
1826 *loc = locations[i];
1827 *relative = relative_path (filename, buffer);
1828 return (*relative != NULL);
1831 return FALSE;
1834 /* gets the target path directly or through MSI */
1835 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1836 LPWSTR szArgs, DWORD argsSize)
1838 IShellLinkDataList *dl = NULL;
1839 EXP_DARWIN_LINK *dar = NULL;
1840 HRESULT hr;
1842 szPath[0] = 0;
1843 szArgs[0] = 0;
1845 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1846 if (hr == S_OK && szPath[0])
1848 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1849 return hr;
1852 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1853 if (FAILED(hr))
1854 return hr;
1856 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1857 if (SUCCEEDED(hr))
1859 WCHAR* szCmdline;
1860 DWORD cmdSize;
1862 cmdSize=0;
1863 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1864 if (hr == ERROR_SUCCESS)
1866 cmdSize++;
1867 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1868 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1869 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1870 if (hr == ERROR_SUCCESS)
1872 WCHAR *s, *d;
1873 int bcount = 0;
1874 BOOL in_quotes = FALSE;
1876 /* Extract the application path */
1877 s=szCmdline;
1878 d=szPath;
1879 while (*s)
1881 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1883 /* skip the remaining spaces */
1884 do {
1885 s++;
1886 } while (*s==0x0009 || *s==0x0020);
1887 break;
1889 else if (*s==0x005c)
1891 /* '\\' */
1892 *d++=*s++;
1893 bcount++;
1895 else if (*s==0x0022)
1897 /* '"' */
1898 if ((bcount & 1)==0)
1900 /* Preceded by an even number of '\', this is
1901 * half that number of '\', plus a quote which
1902 * we erase.
1904 d-=bcount/2;
1905 in_quotes=!in_quotes;
1906 s++;
1908 else
1910 /* Preceded by an odd number of '\', this is
1911 * half that number of '\' followed by a '"'
1913 d=d-bcount/2-1;
1914 *d++='"';
1915 s++;
1917 bcount=0;
1919 else
1921 /* a regular character */
1922 *d++=*s++;
1923 bcount=0;
1925 if ((d-szPath) == pathSize)
1927 /* Keep processing the path till we get to the
1928 * arguments, but 'stand still'
1930 d--;
1933 /* Close the application path */
1934 *d=0;
1936 lstrcpynW(szArgs, s, argsSize);
1938 HeapFree( GetProcessHeap(), 0, szCmdline );
1940 LocalFree( dar );
1943 IShellLinkDataList_Release( dl );
1944 return hr;
1947 static char *slashes_to_minuses(const char *string)
1949 int i;
1950 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1951 if (ret)
1953 for (i = 0; string[i]; i++)
1955 if (string[i] == '/')
1956 ret[i] = '-';
1957 else
1958 ret[i] = string[i];
1960 ret[i] = 0;
1961 return ret;
1963 return NULL;
1966 static BOOL next_line(FILE *file, char **line, int *size)
1968 int pos = 0;
1969 char *cr;
1970 if (*line == NULL)
1972 *size = 4096;
1973 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1975 while (*line != NULL)
1977 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1979 HeapFree(GetProcessHeap(), 0, *line);
1980 *line = NULL;
1981 if (feof(file))
1982 return TRUE;
1983 return FALSE;
1985 pos = strlen(*line);
1986 cr = strchr(*line, '\n');
1987 if (cr == NULL)
1989 char *line2;
1990 (*size) *= 2;
1991 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1992 if (line2)
1993 *line = line2;
1994 else
1996 HeapFree(GetProcessHeap(), 0, *line);
1997 *line = NULL;
2000 else
2002 *cr = 0;
2003 return TRUE;
2006 return FALSE;
2009 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
2011 char *globs_filename = NULL;
2012 BOOL ret = TRUE;
2013 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
2014 if (globs_filename)
2016 FILE *globs_file = fopen(globs_filename, "r");
2017 if (globs_file) /* doesn't have to exist */
2019 char *line = NULL;
2020 int size = 0;
2021 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
2023 char *pos;
2024 struct xdg_mime_type *mime_type_entry = NULL;
2025 if (line[0] != '#' && (pos = strchr(line, ':')))
2027 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
2028 if (mime_type_entry)
2030 *pos = 0;
2031 mime_type_entry->mimeType = strdupA(line);
2032 mime_type_entry->glob = strdupA(pos + 1);
2033 mime_type_entry->lower_glob = strdupA(pos + 1);
2034 if (mime_type_entry->lower_glob)
2036 char *l;
2037 for (l = mime_type_entry->lower_glob; *l; l++)
2038 *l = tolower(*l);
2040 if (mime_type_entry->mimeType && mime_type_entry->glob && mime_type_entry->lower_glob)
2041 list_add_tail(mime_types, &mime_type_entry->entry);
2042 else
2044 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2045 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2046 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2047 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2048 ret = FALSE;
2051 else
2052 ret = FALSE;
2055 HeapFree(GetProcessHeap(), 0, line);
2056 fclose(globs_file);
2058 HeapFree(GetProcessHeap(), 0, globs_filename);
2060 else
2061 ret = FALSE;
2062 return ret;
2065 static void free_native_mime_types(struct list *native_mime_types)
2067 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
2069 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
2071 list_remove(&mime_type_entry->entry);
2072 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2073 HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2074 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
2075 HeapFree(GetProcessHeap(), 0, mime_type_entry);
2079 static BOOL build_native_mime_types(const char *xdg_data_home, struct list *mime_types)
2081 char *xdg_data_dirs;
2082 BOOL ret;
2084 xdg_data_dirs = getenv("XDG_DATA_DIRS");
2085 if (xdg_data_dirs == NULL)
2086 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
2087 else
2088 xdg_data_dirs = strdupA(xdg_data_dirs);
2090 if (xdg_data_dirs)
2092 const char *begin;
2093 char *end;
2095 ret = add_mimes(xdg_data_home, mime_types);
2096 if (ret)
2098 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
2100 *end = '\0';
2101 ret = add_mimes(begin, mime_types);
2102 *end = ':';
2103 if (!ret)
2104 break;
2106 if (ret)
2107 ret = add_mimes(begin, mime_types);
2109 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
2111 else
2112 ret = FALSE;
2113 if (!ret)
2114 free_native_mime_types(mime_types);
2115 return ret;
2118 static BOOL match_glob(struct list *native_mime_types, const char *extension,
2119 int ignoreGlobCase, char **match)
2121 #ifdef HAVE_FNMATCH
2122 struct xdg_mime_type *mime_type_entry;
2123 int matchLength = 0;
2125 *match = NULL;
2127 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
2129 const char *glob = ignoreGlobCase ? mime_type_entry->lower_glob : mime_type_entry->glob;
2130 if (fnmatch(glob, extension, 0) == 0)
2132 if (*match == NULL || matchLength < strlen(glob))
2134 *match = mime_type_entry->mimeType;
2135 matchLength = strlen(glob);
2140 if (*match != NULL)
2142 *match = strdupA(*match);
2143 if (*match == NULL)
2144 return FALSE;
2146 #else
2147 *match = NULL;
2148 #endif
2149 return TRUE;
2152 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
2153 const char *extensionA,
2154 LPCWSTR extensionW,
2155 char **mime_type)
2157 WCHAR *lower_extensionW;
2158 INT len;
2159 BOOL ret = match_glob(native_mime_types, extensionA, 0, mime_type);
2160 if (ret == FALSE || *mime_type != NULL)
2161 return ret;
2162 len = strlenW(extensionW);
2163 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
2164 if (lower_extensionW)
2166 char *lower_extensionA;
2167 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
2168 strlwrW(lower_extensionW);
2169 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
2170 if (lower_extensionA)
2172 ret = match_glob(native_mime_types, lower_extensionA, 1, mime_type);
2173 HeapFree(GetProcessHeap(), 0, lower_extensionA);
2175 else
2177 ret = FALSE;
2178 WINE_FIXME("out of memory\n");
2180 HeapFree(GetProcessHeap(), 0, lower_extensionW);
2182 else
2184 ret = FALSE;
2185 WINE_FIXME("out of memory\n");
2187 return ret;
2190 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
2192 DWORD size;
2193 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
2195 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
2196 if (ret)
2198 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
2199 return ret;
2201 HeapFree(GetProcessHeap(), 0, ret);
2203 return NULL;
2206 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
2208 WCHAR *valW = reg_get_valW(key, subkey, name);
2209 if (valW)
2211 char *val = wchars_to_utf8_chars(valW);
2212 HeapFree(GetProcessHeap(), 0, valW);
2213 return val;
2215 return NULL;
2218 static HKEY open_associations_reg_key(void)
2220 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
2221 '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};
2222 HKEY assocKey;
2223 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
2224 return assocKey;
2225 return NULL;
2228 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
2229 LPCSTR appName, LPCSTR openWithIcon)
2231 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2232 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2233 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2234 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2235 HKEY assocKey;
2236 BOOL ret;
2238 if ((assocKey = open_associations_reg_key()))
2240 CHAR *valueA;
2241 WCHAR *value;
2243 ret = FALSE;
2245 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
2246 if (!valueA || lstrcmpA(valueA, mimeType))
2247 ret = TRUE;
2248 HeapFree(GetProcessHeap(), 0, valueA);
2250 value = reg_get_valW(assocKey, extensionW, ProgIDW);
2251 if (!value || strcmpW(value, progId))
2252 ret = TRUE;
2253 HeapFree(GetProcessHeap(), 0, value);
2255 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2256 if (!valueA || lstrcmpA(valueA, appName))
2257 ret = TRUE;
2258 HeapFree(GetProcessHeap(), 0, valueA);
2260 valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
2261 if ((openWithIcon && !valueA) ||
2262 (!openWithIcon && valueA) ||
2263 (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
2264 ret = TRUE;
2265 HeapFree(GetProcessHeap(), 0, valueA);
2267 RegCloseKey(assocKey);
2269 else
2271 WINE_ERR("error opening associations registry key\n");
2272 ret = FALSE;
2274 return ret;
2277 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2278 LPCSTR appName, LPCSTR desktopFile, LPCSTR openWithIcon)
2280 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2281 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2282 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2283 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2284 static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2285 HKEY assocKey = NULL;
2286 HKEY subkey = NULL;
2287 WCHAR *mimeTypeW = NULL;
2288 WCHAR *appNameW = NULL;
2289 WCHAR *desktopFileW = NULL;
2290 WCHAR *openWithIconW = NULL;
2292 assocKey = open_associations_reg_key();
2293 if (assocKey == NULL)
2295 WINE_ERR("could not open file associations key\n");
2296 goto done;
2299 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2301 WINE_ERR("could not create extension subkey\n");
2302 goto done;
2305 mimeTypeW = utf8_chars_to_wchars(mimeType);
2306 if (mimeTypeW == NULL)
2308 WINE_ERR("out of memory\n");
2309 goto done;
2312 appNameW = utf8_chars_to_wchars(appName);
2313 if (appNameW == NULL)
2315 WINE_ERR("out of memory\n");
2316 goto done;
2319 desktopFileW = utf8_chars_to_wchars(desktopFile);
2320 if (desktopFileW == NULL)
2322 WINE_ERR("out of memory\n");
2323 goto done;
2326 if (openWithIcon)
2328 openWithIconW = utf8_chars_to_wchars(openWithIcon);
2329 if (openWithIconW == NULL)
2331 WINE_ERR("out of memory\n");
2332 goto done;
2336 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2337 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2338 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2339 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2340 if (openWithIcon)
2341 RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
2342 else
2343 RegDeleteValueW(subkey, OpenWithIconW);
2345 done:
2346 RegCloseKey(assocKey);
2347 RegCloseKey(subkey);
2348 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2349 HeapFree(GetProcessHeap(), 0, appNameW);
2350 HeapFree(GetProcessHeap(), 0, desktopFileW);
2351 HeapFree(GetProcessHeap(), 0, openWithIconW);
2354 static BOOL cleanup_associations(void)
2356 static const WCHAR openW[] = {'o','p','e','n',0};
2357 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2358 HKEY assocKey;
2359 BOOL hasChanged = FALSE;
2360 if ((assocKey = open_associations_reg_key()))
2362 int i;
2363 BOOL done = FALSE;
2364 for (i = 0; !done;)
2366 WCHAR *extensionW = NULL;
2367 DWORD size = 1024;
2368 LSTATUS ret;
2372 HeapFree(GetProcessHeap(), 0, extensionW);
2373 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2374 if (extensionW == NULL)
2376 WINE_ERR("out of memory\n");
2377 ret = ERROR_OUTOFMEMORY;
2378 break;
2380 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2381 size *= 2;
2382 } while (ret == ERROR_MORE_DATA);
2384 if (ret == ERROR_SUCCESS)
2386 WCHAR *command;
2387 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2388 if (command == NULL)
2390 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2391 if (desktopFile)
2393 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2394 remove(desktopFile);
2396 RegDeleteKeyW(assocKey, extensionW);
2397 hasChanged = TRUE;
2398 HeapFree(GetProcessHeap(), 0, desktopFile);
2400 else
2401 i++;
2402 HeapFree(GetProcessHeap(), 0, command);
2404 else
2406 if (ret != ERROR_NO_MORE_ITEMS)
2407 WINE_ERR("error %d while reading registry\n", ret);
2408 done = TRUE;
2410 HeapFree(GetProcessHeap(), 0, extensionW);
2412 RegCloseKey(assocKey);
2414 else
2415 WINE_ERR("could not open file associations key\n");
2416 return hasChanged;
2419 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2420 const char *mime_type, const char *comment)
2422 BOOL ret = FALSE;
2423 char *filename;
2425 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2426 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2428 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2429 if (filename)
2431 FILE *packageFile = fopen(filename, "w");
2432 if (packageFile)
2434 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2435 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2436 fprintf(packageFile, " <mime-type type=\"");
2437 write_xml_text(packageFile, mime_type);
2438 fprintf(packageFile, "\">\n");
2439 fprintf(packageFile, " <glob pattern=\"*");
2440 write_xml_text(packageFile, dot_extension);
2441 fprintf(packageFile, "\"/>\n");
2442 if (comment)
2444 fprintf(packageFile, " <comment>");
2445 write_xml_text(packageFile, comment);
2446 fprintf(packageFile, "</comment>\n");
2448 fprintf(packageFile, " </mime-type>\n");
2449 fprintf(packageFile, "</mime-info>\n");
2450 ret = TRUE;
2451 fclose(packageFile);
2453 else
2454 WINE_ERR("error writing file %s\n", filename);
2455 HeapFree(GetProcessHeap(), 0, filename);
2457 else
2458 WINE_ERR("out of memory\n");
2459 return ret;
2462 static BOOL is_extension_blacklisted(LPCWSTR extension)
2464 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2465 static const WCHAR comW[] = {'.','c','o','m',0};
2466 static const WCHAR exeW[] = {'.','e','x','e',0};
2467 static const WCHAR msiW[] = {'.','m','s','i',0};
2469 if (!strcmpiW(extension, comW) ||
2470 !strcmpiW(extension, exeW) ||
2471 !strcmpiW(extension, msiW))
2472 return TRUE;
2473 return FALSE;
2476 static const char* get_special_mime_type(LPCWSTR extension)
2478 static const WCHAR lnkW[] = {'.','l','n','k',0};
2479 if (!strcmpiW(extension, lnkW))
2480 return "application/x-ms-shortcut";
2481 return NULL;
2484 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2485 const char *friendlyAppName, const char *mimeType,
2486 const char *progId, const char *openWithIcon)
2488 BOOL ret = FALSE;
2489 FILE *desktop;
2491 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2492 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2493 wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2495 desktop = fopen(desktopPath, "w");
2496 if (desktop)
2498 fprintf(desktop, "[Desktop Entry]\n");
2499 fprintf(desktop, "Type=Application\n");
2500 fprintf(desktop, "Name=%s\n", friendlyAppName);
2501 fprintf(desktop, "MimeType=%s;\n", mimeType);
2502 fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId);
2503 fprintf(desktop, "NoDisplay=true\n");
2504 fprintf(desktop, "StartupNotify=true\n");
2505 if (openWithIcon)
2506 fprintf(desktop, "Icon=%s\n", openWithIcon);
2507 ret = TRUE;
2508 fclose(desktop);
2510 else
2511 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2512 return ret;
2515 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2517 static const WCHAR openW[] = {'o','p','e','n',0};
2518 struct wine_rb_tree mimeProgidTree = { winemenubuilder_rb_string_compare };
2519 struct list nativeMimeTypes = LIST_INIT(nativeMimeTypes);
2520 LSTATUS ret = 0;
2521 int i;
2522 BOOL hasChanged = FALSE;
2524 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2526 WINE_ERR("could not build native MIME types\n");
2527 return FALSE;
2530 for (i = 0; ; i++)
2532 WCHAR *extensionW = NULL;
2533 DWORD size = 1024;
2537 HeapFree(GetProcessHeap(), 0, extensionW);
2538 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2539 if (extensionW == NULL)
2541 WINE_ERR("out of memory\n");
2542 ret = ERROR_OUTOFMEMORY;
2543 break;
2545 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2546 size *= 2;
2547 } while (ret == ERROR_MORE_DATA);
2549 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2551 char *extensionA = NULL;
2552 WCHAR *commandW = NULL;
2553 WCHAR *executableW = NULL;
2554 char *openWithIconA = NULL;
2555 WCHAR *friendlyDocNameW = NULL;
2556 char *friendlyDocNameA = NULL;
2557 WCHAR *iconW = NULL;
2558 char *iconA = NULL;
2559 WCHAR *contentTypeW = NULL;
2560 char *mimeTypeA = NULL;
2561 WCHAR *friendlyAppNameW = NULL;
2562 char *friendlyAppNameA = NULL;
2563 WCHAR *progIdW = NULL;
2564 char *progIdA = NULL;
2565 char *mimeProgId = NULL;
2567 extensionA = wchars_to_utf8_chars(strlwrW(extensionW));
2568 if (extensionA == NULL)
2570 WINE_ERR("out of memory\n");
2571 goto end;
2574 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2575 if (friendlyDocNameW)
2577 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2578 if (friendlyDocNameA == NULL)
2580 WINE_ERR("out of memory\n");
2581 goto end;
2585 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2587 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2588 if (contentTypeW)
2589 strlwrW(contentTypeW);
2591 if (!freedesktop_mime_type_for_extension(&nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2592 goto end;
2594 if (mimeTypeA == NULL)
2596 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2597 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2598 else if ((get_special_mime_type(extensionW)))
2599 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2600 else
2601 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2603 if (mimeTypeA != NULL)
2605 /* GNOME seems to ignore the <icon> tag in MIME packages,
2606 * and the default name is more intuitive anyway.
2608 if (iconW)
2610 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2611 if (flattened_mime)
2613 int index = 0;
2614 WCHAR *comma = strrchrW(iconW, ',');
2615 if (comma)
2617 *comma = 0;
2618 index = atoiW(comma + 1);
2620 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2621 HeapFree(GetProcessHeap(), 0, flattened_mime);
2625 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2626 hasChanged = TRUE;
2628 else
2630 WINE_FIXME("out of memory\n");
2631 goto end;
2635 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2636 if (commandW == NULL)
2637 /* no command => no application is associated */
2638 goto end;
2640 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
2641 if (executableW)
2642 openWithIconA = extract_icon(executableW, 0, NULL, FALSE);
2644 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, openW);
2645 if (friendlyAppNameW)
2647 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2648 if (friendlyAppNameA == NULL)
2650 WINE_ERR("out of memory\n");
2651 goto end;
2654 else
2656 friendlyAppNameA = heap_printf("A Wine application");
2657 if (friendlyAppNameA == NULL)
2659 WINE_ERR("out of memory\n");
2660 goto end;
2664 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2665 if (progIdW)
2667 progIdA = escape(progIdW);
2668 if (progIdA == NULL)
2670 WINE_ERR("out of memory\n");
2671 goto end;
2674 else
2675 goto end; /* no progID => not a file type association */
2677 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2678 mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
2679 if (mimeProgId)
2681 struct rb_string_entry *entry;
2682 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2684 HeapFree(GetProcessHeap(), 0, mimeProgId);
2685 goto end;
2687 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
2688 if (!entry)
2690 WINE_ERR("out of memory allocating rb_string_entry\n");
2691 goto end;
2693 entry->string = mimeProgId;
2694 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2696 WINE_ERR("error updating rb tree\n");
2697 goto end;
2701 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, openWithIconA))
2703 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2704 if (desktopPath)
2706 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2708 hasChanged = TRUE;
2709 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, desktopPath, openWithIconA);
2711 HeapFree(GetProcessHeap(), 0, desktopPath);
2715 end:
2716 HeapFree(GetProcessHeap(), 0, extensionA);
2717 HeapFree(GetProcessHeap(), 0, commandW);
2718 HeapFree(GetProcessHeap(), 0, executableW);
2719 HeapFree(GetProcessHeap(), 0, openWithIconA);
2720 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2721 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2722 HeapFree(GetProcessHeap(), 0, iconW);
2723 HeapFree(GetProcessHeap(), 0, iconA);
2724 HeapFree(GetProcessHeap(), 0, contentTypeW);
2725 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2726 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2727 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2728 HeapFree(GetProcessHeap(), 0, progIdW);
2729 HeapFree(GetProcessHeap(), 0, progIdA);
2731 HeapFree(GetProcessHeap(), 0, extensionW);
2732 if (ret != ERROR_SUCCESS)
2733 break;
2736 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2737 free_native_mime_types(&nativeMimeTypes);
2738 return hasChanged;
2741 static char *get_start_exe_path(void)
2743 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2744 '\\','s','t','a','r','t','.','e','x','e',0};
2745 WCHAR start_path[MAX_PATH];
2746 GetWindowsDirectoryW(start_path, MAX_PATH);
2747 lstrcatW(start_path, startW);
2748 return escape(start_path);
2751 static char* escape_unix_link_arg(LPCSTR unix_link)
2753 char *ret = NULL;
2754 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2755 if (unix_linkW)
2757 char *escaped_lnk = escape(unix_linkW);
2758 if (escaped_lnk)
2760 ret = heap_printf("/Unix %s", escaped_lnk);
2761 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2763 HeapFree(GetProcessHeap(), 0, unix_linkW);
2765 return ret;
2768 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2770 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2771 '\\','s','t','a','r','t','.','e','x','e',0};
2772 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2773 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2774 WCHAR szTmp[INFOTIPSIZE];
2775 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2776 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2777 int iIconId = 0, r = -1;
2778 DWORD csidl = -1;
2779 HANDLE hsem = NULL;
2780 char *unix_link = NULL;
2781 char *start_path = NULL;
2783 if ( !link )
2785 WINE_ERR("Link name is null\n");
2786 return FALSE;
2789 if( !GetLinkLocation( link, &csidl, &link_name ) )
2791 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2792 return TRUE;
2794 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2796 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2797 return TRUE;
2799 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2801 szTmp[0] = 0;
2802 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2803 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2804 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2806 szTmp[0] = 0;
2807 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2808 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2809 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2811 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2812 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2813 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2814 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2816 szTmp[0] = 0;
2817 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2818 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2819 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2821 if( !szPath[0] )
2823 LPITEMIDLIST pidl = NULL;
2824 IShellLinkW_GetIDList( sl, &pidl );
2825 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2826 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2829 /* extract the icon */
2830 if( szIconPath[0] )
2831 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2832 else
2833 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2835 /* fail - try once again after parent process exit */
2836 if( !icon_name )
2838 if (bWait)
2840 WINE_WARN("Unable to extract icon, deferring.\n");
2841 goto cleanup;
2843 WINE_ERR("failed to extract icon from %s\n",
2844 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2847 unix_link = wine_get_unix_file_name(link);
2848 if (unix_link == NULL)
2850 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2851 goto cleanup;
2854 /* check the path */
2855 if( szPath[0] )
2857 static const WCHAR exeW[] = {'.','e','x','e',0};
2858 WCHAR *p;
2860 /* check for .exe extension */
2861 if (!(p = strrchrW( szPath, '.' )) ||
2862 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2863 lstrcmpiW( p, exeW ))
2865 /* Not .exe - use 'start.exe' to launch this file */
2866 p = szArgs + lstrlenW(szPath) + 2;
2867 if (szArgs[0])
2869 p[0] = ' ';
2870 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2871 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2873 else
2874 p[0] = 0;
2876 szArgs[0] = '"';
2877 lstrcpyW(szArgs + 1, szPath);
2878 p[-1] = '"';
2880 GetWindowsDirectoryW(szPath, MAX_PATH);
2881 lstrcatW(szPath, startW);
2884 /* convert app working dir */
2885 if (szWorkDir[0])
2886 work_dir = wine_get_unix_file_name( szWorkDir );
2888 else
2890 /* if there's no path... try run the link itself */
2891 lstrcpynW(szArgs, link, MAX_PATH);
2892 GetWindowsDirectoryW(szPath, MAX_PATH);
2893 lstrcatW(szPath, startW);
2896 /* escape the path and parameters */
2897 escaped_path = escape(szPath);
2898 escaped_args = escape(szArgs);
2899 description = wchars_to_utf8_chars(szDescription);
2900 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2902 WINE_ERR("out of memory allocating/escaping parameters\n");
2903 goto cleanup;
2906 start_path = get_start_exe_path();
2907 if (start_path == NULL)
2909 WINE_ERR("out of memory\n");
2910 goto cleanup;
2913 /* building multiple menus concurrently has race conditions */
2914 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2915 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2917 WINE_ERR("failed wait for semaphore\n");
2918 goto cleanup;
2921 if (in_desktop_dir(csidl))
2923 char *location;
2924 const char *lastEntry;
2925 lastEntry = strrchr(link_name, '/');
2926 if (lastEntry == NULL)
2927 lastEntry = link_name;
2928 else
2929 ++lastEntry;
2930 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2931 if (location)
2933 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2935 char *link_arg = escape_unix_link_arg(unix_link);
2936 if (link_arg)
2938 r = !write_desktop_entry(unix_link, location, lastEntry,
2939 start_path, link_arg, description, work_dir, icon_name);
2940 HeapFree(GetProcessHeap(), 0, link_arg);
2943 else
2944 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2945 if (r == 0)
2946 chmod(location, 0755);
2947 HeapFree(GetProcessHeap(), 0, location);
2950 else
2952 char *link_arg = escape_unix_link_arg(unix_link);
2953 if (link_arg)
2955 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name);
2956 HeapFree(GetProcessHeap(), 0, link_arg);
2960 ReleaseSemaphore( hsem, 1, NULL );
2962 cleanup:
2963 if (hsem) CloseHandle( hsem );
2964 HeapFree( GetProcessHeap(), 0, icon_name );
2965 HeapFree( GetProcessHeap(), 0, work_dir );
2966 HeapFree( GetProcessHeap(), 0, link_name );
2967 HeapFree( GetProcessHeap(), 0, escaped_args );
2968 HeapFree( GetProcessHeap(), 0, escaped_path );
2969 HeapFree( GetProcessHeap(), 0, description );
2970 HeapFree( GetProcessHeap(), 0, unix_link );
2971 HeapFree( GetProcessHeap(), 0, start_path );
2973 if (r && !bWait)
2974 WINE_ERR("failed to build the menu\n" );
2976 return ( r == 0 );
2979 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2981 char *link_name = NULL, *icon_name = NULL;
2982 DWORD csidl = -1;
2983 LPWSTR urlPath = NULL;
2984 char *escaped_urlPath = NULL;
2985 HRESULT hr;
2986 HANDLE hSem = NULL;
2987 BOOL ret = TRUE;
2988 int r = -1;
2989 char *unix_link = NULL;
2990 IPropertySetStorage *pPropSetStg;
2991 IPropertyStorage *pPropStg;
2992 PROPSPEC ps[2];
2993 PROPVARIANT pv[2];
2994 char *start_path = NULL;
2995 BOOL has_icon = FALSE;
2997 if ( !link )
2999 WINE_ERR("Link name is null\n");
3000 return TRUE;
3003 if( !GetLinkLocation( link, &csidl, &link_name ) )
3005 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
3006 return TRUE;
3008 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
3010 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3011 ret = TRUE;
3012 goto cleanup;
3014 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
3016 hr = url->lpVtbl->GetURL(url, &urlPath);
3017 if (FAILED(hr))
3019 ret = TRUE;
3020 goto cleanup;
3022 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
3024 unix_link = wine_get_unix_file_name(link);
3025 if (unix_link == NULL)
3027 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
3028 goto cleanup;
3031 escaped_urlPath = escape(urlPath);
3032 if (escaped_urlPath == NULL)
3034 WINE_ERR("couldn't escape url, out of memory\n");
3035 goto cleanup;
3038 start_path = get_start_exe_path();
3039 if (start_path == NULL)
3041 WINE_ERR("out of memory\n");
3042 goto cleanup;
3045 ps[0].ulKind = PRSPEC_PROPID;
3046 ps[0].u.propid = PID_IS_ICONFILE;
3047 ps[1].ulKind = PRSPEC_PROPID;
3048 ps[1].u.propid = PID_IS_ICONINDEX;
3050 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
3051 if (SUCCEEDED(hr))
3053 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
3054 if (SUCCEEDED(hr))
3056 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
3057 if (SUCCEEDED(hr))
3059 if (pv[0].vt == VT_LPWSTR && pv[0].u.pwszVal && pv[0].u.pwszVal[0])
3061 has_icon = TRUE;
3062 icon_name = extract_icon( pv[0].u.pwszVal, pv[1].u.iVal, NULL, bWait );
3064 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);
3066 PropVariantClear(&pv[0]);
3067 PropVariantClear(&pv[1]);
3069 IPropertyStorage_Release(pPropStg);
3071 IPropertySetStorage_Release(pPropSetStg);
3074 /* fail - try once again after parent process exit */
3075 if( has_icon && !icon_name )
3077 if (bWait)
3079 WINE_WARN("Unable to extract icon, deferring.\n");
3080 ret = FALSE;
3081 goto cleanup;
3083 WINE_ERR("failed to extract icon from %s\n",
3084 wine_dbgstr_w( pv[0].u.pwszVal ));
3087 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3088 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3090 WINE_ERR("failed wait for semaphore\n");
3091 goto cleanup;
3093 if (in_desktop_dir(csidl))
3095 char *location;
3096 const char *lastEntry;
3097 lastEntry = strrchr(link_name, '/');
3098 if (lastEntry == NULL)
3099 lastEntry = link_name;
3100 else
3101 ++lastEntry;
3102 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
3103 if (location)
3105 r = !write_desktop_entry(NULL, location, lastEntry, start_path, escaped_urlPath, NULL, NULL, icon_name);
3106 if (r == 0)
3107 chmod(location, 0755);
3108 HeapFree(GetProcessHeap(), 0, location);
3111 else
3112 r = !write_menu_entry(unix_link, link_name, start_path, escaped_urlPath, NULL, NULL, icon_name);
3113 ret = (r == 0);
3114 ReleaseSemaphore(hSem, 1, NULL);
3116 cleanup:
3117 if (hSem)
3118 CloseHandle(hSem);
3119 HeapFree( GetProcessHeap(), 0, icon_name );
3120 HeapFree(GetProcessHeap(), 0, link_name);
3121 CoTaskMemFree( urlPath );
3122 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
3123 HeapFree(GetProcessHeap(), 0, unix_link);
3124 return ret;
3127 static BOOL WaitForParentProcess( void )
3129 PROCESSENTRY32 procentry;
3130 HANDLE hsnapshot = NULL, hprocess = NULL;
3131 DWORD ourpid = GetCurrentProcessId();
3132 BOOL ret = FALSE, rc;
3134 WINE_TRACE("Waiting for parent process\n");
3135 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
3136 INVALID_HANDLE_VALUE)
3138 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3139 goto done;
3142 procentry.dwSize = sizeof(PROCESSENTRY32);
3143 rc = Process32First( hsnapshot, &procentry );
3144 while (rc)
3146 if (procentry.th32ProcessID == ourpid) break;
3147 rc = Process32Next( hsnapshot, &procentry );
3149 if (!rc)
3151 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
3152 goto done;
3155 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
3156 NULL)
3158 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
3159 GetLastError());
3160 goto done;
3163 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
3164 ret = TRUE;
3165 else
3166 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3168 done:
3169 if (hprocess) CloseHandle( hprocess );
3170 if (hsnapshot) CloseHandle( hsnapshot );
3171 return ret;
3174 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
3176 IShellLinkW *sl;
3177 IPersistFile *pf;
3178 HRESULT r;
3179 WCHAR fullname[MAX_PATH];
3180 DWORD len;
3182 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
3184 if( !linkname[0] )
3186 WINE_ERR("link name missing\n");
3187 return FALSE;
3190 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
3191 if (len==0 || len>MAX_PATH)
3193 WINE_ERR("couldn't get full path of link file\n");
3194 return FALSE;
3197 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3198 &IID_IShellLinkW, (LPVOID *) &sl );
3199 if( FAILED( r ) )
3201 WINE_ERR("No IID_IShellLink\n");
3202 return FALSE;
3205 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
3206 if( FAILED( r ) )
3208 WINE_ERR("No IID_IPersistFile\n");
3209 return FALSE;
3212 r = IPersistFile_Load( pf, fullname, STGM_READ );
3213 if( SUCCEEDED( r ) )
3215 /* If something fails (eg. Couldn't extract icon)
3216 * wait for parent process and try again
3218 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
3220 WaitForParentProcess();
3221 InvokeShellLinker( sl, fullname, FALSE );
3224 else
3226 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
3229 IPersistFile_Release( pf );
3230 IShellLinkW_Release( sl );
3232 return !r;
3235 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
3237 IUniformResourceLocatorW *url;
3238 IPersistFile *pf;
3239 HRESULT r;
3240 WCHAR fullname[MAX_PATH];
3241 DWORD len;
3243 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
3245 if( !urlname[0] )
3247 WINE_ERR("URL name missing\n");
3248 return FALSE;
3251 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
3252 if (len==0 || len>MAX_PATH)
3254 WINE_ERR("couldn't get full path of URL file\n");
3255 return FALSE;
3258 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
3259 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
3260 if( FAILED( r ) )
3262 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3263 return FALSE;
3266 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
3267 if( FAILED( r ) )
3269 WINE_ERR("No IID_IPersistFile\n");
3270 return FALSE;
3272 r = IPersistFile_Load( pf, fullname, STGM_READ );
3273 if( SUCCEEDED( r ) )
3275 /* If something fails (eg. Couldn't extract icon)
3276 * wait for parent process and try again
3278 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
3280 WaitForParentProcess();
3281 InvokeShellLinkerForURL( url, fullname, FALSE );
3285 IPersistFile_Release( pf );
3286 url->lpVtbl->Release( url );
3288 return !r;
3291 static void RefreshFileTypeAssociations(void)
3293 HANDLE hSem = NULL;
3294 char *mime_dir = NULL;
3295 char *packages_dir = NULL;
3296 char *applications_dir = NULL;
3297 BOOL hasChanged;
3299 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
3300 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
3302 WINE_ERR("failed wait for semaphore\n");
3303 CloseHandle(hSem);
3304 hSem = NULL;
3305 goto end;
3308 mime_dir = heap_printf("%s/mime", xdg_data_dir);
3309 if (mime_dir == NULL)
3311 WINE_ERR("out of memory\n");
3312 goto end;
3314 create_directories(mime_dir);
3316 packages_dir = heap_printf("%s/packages", mime_dir);
3317 if (packages_dir == NULL)
3319 WINE_ERR("out of memory\n");
3320 goto end;
3322 create_directories(packages_dir);
3324 applications_dir = heap_printf("%s/applications", xdg_data_dir);
3325 if (applications_dir == NULL)
3327 WINE_ERR("out of memory\n");
3328 goto end;
3330 create_directories(applications_dir);
3332 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3333 hasChanged |= cleanup_associations();
3334 if (hasChanged)
3336 const char *argv[3];
3338 argv[0] = "update-mime-database";
3339 argv[1] = mime_dir;
3340 argv[2] = NULL;
3341 _spawnvp( _P_DETACH, argv[0], argv );
3343 argv[0] = "update-desktop-database";
3344 argv[1] = applications_dir;
3345 _spawnvp( _P_DETACH, argv[0], argv );
3348 end:
3349 if (hSem)
3351 ReleaseSemaphore(hSem, 1, NULL);
3352 CloseHandle(hSem);
3354 HeapFree(GetProcessHeap(), 0, mime_dir);
3355 HeapFree(GetProcessHeap(), 0, packages_dir);
3356 HeapFree(GetProcessHeap(), 0, applications_dir);
3359 static void cleanup_menus(void)
3361 HKEY hkey;
3363 hkey = open_menus_reg_key();
3364 if (hkey)
3366 int i;
3367 LSTATUS lret = ERROR_SUCCESS;
3368 for (i = 0; lret == ERROR_SUCCESS; )
3370 WCHAR *value = NULL;
3371 WCHAR *data = NULL;
3372 DWORD valueSize = 4096;
3373 DWORD dataSize = 4096;
3374 while (1)
3376 lret = ERROR_OUTOFMEMORY;
3377 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3378 if (value == NULL)
3379 break;
3380 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3381 if (data == NULL)
3382 break;
3383 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3384 if (lret != ERROR_MORE_DATA)
3385 break;
3386 valueSize *= 2;
3387 dataSize *= 2;
3388 HeapFree(GetProcessHeap(), 0, value);
3389 HeapFree(GetProcessHeap(), 0, data);
3390 value = data = NULL;
3392 if (lret == ERROR_SUCCESS)
3394 char *unix_file;
3395 char *windows_file;
3396 unix_file = wchars_to_unix_chars(value);
3397 windows_file = wchars_to_unix_chars(data);
3398 if (unix_file != NULL && windows_file != NULL)
3400 struct stat filestats;
3401 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3403 WINE_TRACE("removing menu related file %s\n", unix_file);
3404 remove(unix_file);
3405 RegDeleteValueW(hkey, value);
3407 else
3408 i++;
3410 else
3412 WINE_ERR("out of memory enumerating menus\n");
3413 lret = ERROR_OUTOFMEMORY;
3415 HeapFree(GetProcessHeap(), 0, unix_file);
3416 HeapFree(GetProcessHeap(), 0, windows_file);
3418 else if (lret != ERROR_NO_MORE_ITEMS)
3419 WINE_ERR("error %d reading registry\n", lret);
3420 HeapFree(GetProcessHeap(), 0, value);
3421 HeapFree(GetProcessHeap(), 0, data);
3423 RegCloseKey(hkey);
3425 else
3426 WINE_ERR("error opening registry key, menu cleanup failed\n");
3429 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
3431 char *utf8lnkPath = NULL;
3432 char *utf8OutputPath = NULL;
3433 WCHAR *winLnkPath = NULL;
3434 IShellLinkW *shellLink = NULL;
3435 IPersistFile *persistFile = NULL;
3436 WCHAR szTmp[MAX_PATH];
3437 WCHAR szPath[MAX_PATH];
3438 WCHAR szArgs[INFOTIPSIZE];
3439 WCHAR szIconPath[MAX_PATH];
3440 int iconId;
3441 IStream *stream = NULL;
3442 ICONDIRENTRY *pIconDirEntries = NULL;
3443 int numEntries;
3444 HRESULT hr;
3446 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
3447 if (utf8lnkPath == NULL)
3449 WINE_ERR("out of memory converting paths\n");
3450 goto end;
3453 utf8OutputPath = wchars_to_utf8_chars(outputPath);
3454 if (utf8OutputPath == NULL)
3456 WINE_ERR("out of memory converting paths\n");
3457 goto end;
3460 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
3461 if (winLnkPath == NULL)
3463 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
3464 goto end;
3467 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3468 &IID_IShellLinkW, (LPVOID*)&shellLink);
3469 if (FAILED(hr))
3471 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
3472 goto end;
3475 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
3476 if (FAILED(hr))
3478 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
3479 goto end;
3482 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
3483 if (FAILED(hr))
3485 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
3486 goto end;
3489 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
3490 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
3491 szTmp[0] = 0;
3492 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
3493 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
3495 if(!szPath[0])
3497 LPITEMIDLIST pidl = NULL;
3498 IShellLinkW_GetIDList(shellLink, &pidl);
3499 if (pidl && SHGetPathFromIDListW(pidl, szPath))
3500 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
3503 if (szIconPath[0])
3505 hr = open_icon(szIconPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3506 if (SUCCEEDED(hr))
3507 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3509 else
3511 hr = open_icon(szPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3512 if (SUCCEEDED(hr))
3513 hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3516 end:
3517 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
3518 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
3519 HeapFree(GetProcessHeap(), 0, winLnkPath);
3520 if (shellLink != NULL)
3521 IShellLinkW_Release(shellLink);
3522 if (persistFile != NULL)
3523 IPersistFile_Release(persistFile);
3524 if (stream != NULL)
3525 IStream_Release(stream);
3526 HeapFree(GetProcessHeap(), 0, pIconDirEntries);
3529 static WCHAR *next_token( LPWSTR *p )
3531 LPWSTR token = NULL, t = *p;
3533 if( !t )
3534 return NULL;
3536 while( t && !token )
3538 switch( *t )
3540 case ' ':
3541 t++;
3542 continue;
3543 case '"':
3544 /* unquote the token */
3545 token = ++t;
3546 t = strchrW( token, '"' );
3547 if( t )
3548 *t++ = 0;
3549 break;
3550 case 0:
3551 t = NULL;
3552 break;
3553 default:
3554 token = t;
3555 t = strchrW( token, ' ' );
3556 if( t )
3557 *t++ = 0;
3558 break;
3561 *p = t;
3562 return token;
3565 static BOOL init_xdg(void)
3567 WCHAR shellDesktopPath[MAX_PATH];
3568 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3569 if (SUCCEEDED(hr))
3570 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3571 if (xdg_desktop_dir == NULL)
3573 WINE_ERR("error looking up the desktop directory\n");
3574 return FALSE;
3577 if (getenv("XDG_CONFIG_HOME"))
3578 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3579 else
3580 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3581 if (xdg_config_dir)
3583 create_directories(xdg_config_dir);
3584 if (getenv("XDG_DATA_HOME"))
3585 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3586 else
3587 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3588 if (xdg_data_dir)
3590 char *buffer;
3591 create_directories(xdg_data_dir);
3592 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3593 if (buffer)
3595 mkdir(buffer, 0777);
3596 HeapFree(GetProcessHeap(), 0, buffer);
3598 return TRUE;
3600 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3602 WINE_ERR("out of memory\n");
3603 return FALSE;
3606 /***********************************************************************
3608 * wWinMain
3610 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3612 static const WCHAR dash_aW[] = {'-','a',0};
3613 static const WCHAR dash_rW[] = {'-','r',0};
3614 static const WCHAR dash_tW[] = {'-','t',0};
3615 static const WCHAR dash_uW[] = {'-','u',0};
3616 static const WCHAR dash_wW[] = {'-','w',0};
3618 LPWSTR token = NULL, p;
3619 BOOL bWait = FALSE;
3620 BOOL bURL = FALSE;
3621 HRESULT hr;
3622 int ret = 0;
3624 if (!init_xdg())
3625 return 1;
3627 hr = CoInitialize(NULL);
3628 if (FAILED(hr))
3630 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3631 return 1;
3634 for( p = cmdline; p && *p; )
3636 token = next_token( &p );
3637 if( !token )
3638 break;
3639 if( !strcmpW( token, dash_aW ) )
3641 RefreshFileTypeAssociations();
3642 continue;
3644 if( !strcmpW( token, dash_rW ) )
3646 cleanup_menus();
3647 continue;
3649 if( !strcmpW( token, dash_wW ) )
3650 bWait = TRUE;
3651 else if ( !strcmpW( token, dash_uW ) )
3652 bURL = TRUE;
3653 else if ( !strcmpW( token, dash_tW ) )
3655 WCHAR *lnkFile = next_token( &p );
3656 if (lnkFile)
3658 WCHAR *outputFile = next_token( &p );
3659 if (outputFile)
3660 thumbnail_lnk(lnkFile, outputFile);
3663 else if( token[0] == '-' )
3665 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3667 else
3669 BOOL bRet;
3671 if (bURL)
3672 bRet = Process_URL( token, bWait );
3673 else
3674 bRet = Process_Link( token, bWait );
3675 if (!bRet)
3677 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3678 ret = 1;
3683 CoUninitialize();
3684 return ret;