wined3d: Always invalidate ~map_binding in texture write maps.
[wine.git] / programs / winemenubuilder / winemenubuilder.c
blob1579ca8dafa7bced2fb61d48b854e3f95d0f1433
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 <ctype.h>
66 #include <stdio.h>
67 #include <string.h>
68 #include <errno.h>
69 #include <stdarg.h>
71 #define COBJMACROS
72 #define NONAMELESSUNION
74 #include <windows.h>
75 #include <winternl.h>
76 #include <shlobj.h>
77 #include <objidl.h>
78 #include <shlguid.h>
79 #include <appmgmt.h>
80 #include <tlhelp32.h>
81 #include <intshcut.h>
82 #include <shlwapi.h>
83 #include <initguid.h>
84 #include <wincodec.h>
86 #include "wine/debug.h"
87 #include "wine/list.h"
88 #include "wine/rbtree.h"
90 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
92 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
93 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
94 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
95 (csidl)==CSIDL_COMMON_STARTMENU)
97 #define IS_OPTION_TRUE(ch) \
98 ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
100 /* link file formats */
102 #include "pshpack1.h"
104 typedef struct
106 BYTE bWidth;
107 BYTE bHeight;
108 BYTE bColorCount;
109 BYTE bReserved;
110 WORD wPlanes;
111 WORD wBitCount;
112 DWORD dwBytesInRes;
113 WORD nID;
114 } GRPICONDIRENTRY;
116 typedef struct
118 WORD idReserved;
119 WORD idType;
120 WORD idCount;
121 GRPICONDIRENTRY idEntries[1];
122 } GRPICONDIR;
124 typedef struct
126 BYTE bWidth;
127 BYTE bHeight;
128 BYTE bColorCount;
129 BYTE bReserved;
130 WORD wPlanes;
131 WORD wBitCount;
132 DWORD dwBytesInRes;
133 DWORD dwImageOffset;
134 } ICONDIRENTRY;
136 typedef struct
138 WORD idReserved;
139 WORD idType;
140 WORD idCount;
141 } ICONDIR;
143 typedef struct
145 WORD offset;
146 WORD length;
147 WORD flags;
148 WORD id;
149 WORD handle;
150 WORD usage;
151 } NE_NAMEINFO;
153 typedef struct
155 WORD type_id;
156 WORD count;
157 DWORD resloader;
158 } NE_TYPEINFO;
160 #define NE_RSCTYPE_ICON 0x8003
161 #define NE_RSCTYPE_GROUP_ICON 0x800e
163 #include "poppack.h"
165 typedef struct
167 HRSRC *pResInfo;
168 int nIndex;
169 } ENUMRESSTRUCT;
171 struct xdg_mime_type
173 WCHAR *mimeType;
174 WCHAR *glob;
175 struct list entry;
178 struct rb_string_entry
180 WCHAR *string;
181 struct wine_rb_entry entry;
184 static WCHAR *xdg_menu_dir;
185 static WCHAR *xdg_data_dir;
186 static WCHAR xdg_desktop_dir[MAX_PATH];
189 /* Utility routines */
190 static unsigned short crc16(const WCHAR *string)
192 unsigned short crc = 0;
193 int i, j, xor_poly;
195 for (i = 0; string[i] != 0; i++)
197 WCHAR c = string[i];
198 for (j = 0; j < 16; c >>= 1, j++)
200 xor_poly = (c ^ crc) & 1;
201 crc >>= 1;
202 if (xor_poly)
203 crc ^= 0xa001;
206 return crc;
209 static void *xmalloc( size_t size )
211 void *ret = HeapAlloc( GetProcessHeap(), 0, size );
212 if (!ret)
214 ERR( "out of memory\n" );
215 ExitProcess(1);
217 return ret;
220 static void *xrealloc( void *ptr, size_t size )
222 if (!ptr) return xmalloc( size );
223 ptr = HeapReAlloc( GetProcessHeap(), 0, ptr, size );
224 if (!ptr)
226 ERR( "out of memory\n" );
227 ExitProcess(1);
229 return ptr;
232 static WCHAR *xwcsdup( const WCHAR *str )
234 WCHAR *ret;
236 if (!str) return NULL;
237 ret = xmalloc( (lstrlenW(str) + 1) * sizeof(WCHAR) );
238 lstrcpyW( ret, str );
239 return ret;
242 static void heap_free( void *ptr )
244 HeapFree( GetProcessHeap(), 0, ptr );
247 static WCHAR * WINAPIV heap_wprintf(const WCHAR *format, ...)
249 va_list args;
250 int size = 4096;
251 WCHAR *buffer;
252 int n;
254 while (1)
256 buffer = xmalloc(size * sizeof(WCHAR));
257 va_start(args, format);
258 n = _vsnwprintf(buffer, size, format, args);
259 va_end(args);
260 if (n == -1)
261 size *= 2;
262 else if (n >= size)
263 size = n + 1;
264 else
265 return buffer;
266 heap_free(buffer);
270 static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
272 const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);
274 return wcscmp((WCHAR *)key, t->string);
277 static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
279 struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
280 heap_free(t->string);
281 heap_free(t);
284 static BOOL create_directories(WCHAR *directory)
286 WCHAR *p = PathSkipRootW( directory );
288 for ( ; p && *p; p++)
290 if (*p == '\\')
292 *p = 0;
293 CreateDirectoryW( directory, NULL );
294 *p = '\\';
297 return CreateDirectoryW( directory, NULL ) || GetLastError() == ERROR_ALREADY_EXISTS;
300 static char* wchars_to_utf8_chars(LPCWSTR string)
302 char *ret;
303 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
304 ret = xmalloc(size);
305 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
306 return ret;
309 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
311 WCHAR *ret;
312 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
313 ret = xmalloc(size * sizeof(WCHAR));
314 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
315 return ret;
318 static char *wchars_to_xml_text(const WCHAR *string)
320 int i, pos;
321 char *text = wchars_to_utf8_chars( string );
322 char *ret = xmalloc( 6 * strlen(text) + 1 );
324 for (i = pos = 0; text[i]; i++)
326 if (text[i] == '&')
327 pos += sprintf(ret + pos, "&amp;");
328 else if (text[i] == '<')
329 pos += sprintf(ret + pos, "&lt;");
330 else if (text[i] == '>')
331 pos += sprintf(ret + pos, "&gt;");
332 else if (text[i] == '\'')
333 pos += sprintf(ret + pos, "&apos;");
334 else if (text[i] == '"')
335 pos += sprintf(ret + pos, "&quot;");
336 else
337 ret[pos++] = text[i];
339 heap_free( text );
340 ret[pos] = 0;
341 return ret;
344 /* Icon extraction routines
346 * FIXME: should use PrivateExtractIcons and friends
347 * FIXME: should not use stdio
350 static HRESULT convert_to_native_icon(IStream *icoFile, int *indices, int numIndices,
351 const CLSID *outputFormat, const WCHAR *outputFileName)
353 IWICImagingFactory *factory = NULL;
354 IWICBitmapDecoder *decoder = NULL;
355 IWICBitmapEncoder *encoder = NULL;
356 IStream *outputFile = NULL;
357 int i;
358 HRESULT hr = E_FAIL;
360 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
361 &IID_IWICImagingFactory, (void**)&factory);
362 if (FAILED(hr))
364 WINE_ERR("error 0x%08lX creating IWICImagingFactory\n", hr);
365 goto end;
367 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
368 WICDecodeMetadataCacheOnDemand, &decoder);
369 if (FAILED(hr))
371 WINE_ERR("error 0x%08lX creating IWICBitmapDecoder\n", hr);
372 goto end;
374 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
375 &IID_IWICBitmapEncoder, (void**)&encoder);
376 if (FAILED(hr))
378 WINE_ERR("error 0x%08lX creating bitmap encoder\n", hr);
379 goto end;
381 hr = SHCreateStreamOnFileW(outputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
382 if (FAILED(hr))
384 WINE_ERR("error 0x%08lX creating output file %s\n", hr, wine_dbgstr_w(outputFileName));
385 goto end;
387 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, WICBitmapEncoderNoCache);
388 if (FAILED(hr))
390 WINE_ERR("error 0x%08lX initializing encoder\n", hr);
391 goto end;
394 for (i = 0; i < numIndices; i++)
396 IWICBitmapFrameDecode *sourceFrame = NULL;
397 IWICBitmapSource *sourceBitmap = NULL;
398 IWICBitmapFrameEncode *dstFrame = NULL;
399 IPropertyBag2 *options = NULL;
400 UINT width, height;
402 hr = IWICBitmapDecoder_GetFrame(decoder, indices[i], &sourceFrame);
403 if (FAILED(hr))
405 WINE_ERR("error 0x%08lX getting frame %d\n", hr, indices[i]);
406 goto endloop;
408 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
409 if (FAILED(hr))
411 WINE_ERR("error 0x%08lX converting bitmap to 32bppBGRA\n", hr);
412 goto endloop;
414 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
415 if (FAILED(hr))
417 WINE_ERR("error 0x%08lX creating encoder frame\n", hr);
418 goto endloop;
420 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
421 if (FAILED(hr))
423 WINE_ERR("error 0x%08lX initializing encoder frame\n", hr);
424 goto endloop;
426 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
427 if (FAILED(hr))
429 WINE_ERR("error 0x%08lX getting source bitmap size\n", hr);
430 goto endloop;
432 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
433 if (FAILED(hr))
435 WINE_ERR("error 0x%08lX setting destination bitmap size\n", hr);
436 goto endloop;
438 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
439 if (FAILED(hr))
441 WINE_ERR("error 0x%08lX setting destination bitmap resolution\n", hr);
442 goto endloop;
444 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
445 if (FAILED(hr))
447 WINE_ERR("error 0x%08lX copying bitmaps\n", hr);
448 goto endloop;
450 hr = IWICBitmapFrameEncode_Commit(dstFrame);
451 if (FAILED(hr))
453 WINE_ERR("error 0x%08lX committing frame\n", hr);
454 goto endloop;
456 endloop:
457 if (sourceFrame)
458 IWICBitmapFrameDecode_Release(sourceFrame);
459 if (sourceBitmap)
460 IWICBitmapSource_Release(sourceBitmap);
461 if (dstFrame)
462 IWICBitmapFrameEncode_Release(dstFrame);
463 if (options)
464 IPropertyBag2_Release(options);
467 hr = IWICBitmapEncoder_Commit(encoder);
468 if (FAILED(hr))
470 WINE_ERR("error 0x%08lX committing encoder\n", hr);
471 goto end;
474 end:
475 if (factory)
476 IWICImagingFactory_Release(factory);
477 if (decoder)
478 IWICBitmapDecoder_Release(decoder);
479 if (encoder)
480 IWICBitmapEncoder_Release(encoder);
481 if (outputFile)
482 IStream_Release(outputFile);
483 return hr;
486 struct IconData16 {
487 BYTE *fileBytes;
488 DWORD fileSize;
489 NE_TYPEINFO *iconResources;
490 WORD alignmentShiftCount;
493 static int populate_module16_icons(struct IconData16 *iconData16, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
495 int i, j;
496 int validEntries = 0;
498 for (i = 0; i < grpIconDir->idCount; i++)
500 BYTE *iconPtr = (BYTE*)iconData16->iconResources;
501 NE_NAMEINFO *matchingIcon = NULL;
502 iconPtr += sizeof(NE_TYPEINFO);
503 for (j = 0; j < iconData16->iconResources->count; j++)
505 NE_NAMEINFO *iconInfo = (NE_NAMEINFO*)iconPtr;
506 if ((iconPtr + sizeof(NE_NAMEINFO)) > (iconData16->fileBytes + iconData16->fileSize))
508 WINE_WARN("file too small for icon NE_NAMEINFO\n");
509 break;
511 if (iconInfo->id == (0x8000 | grpIconDir->idEntries[i].nID))
513 matchingIcon = iconInfo;
514 break;
516 iconPtr += sizeof(NE_NAMEINFO);
519 if (matchingIcon == NULL)
520 continue;
521 if (((matchingIcon->offset << iconData16->alignmentShiftCount) + grpIconDir->idEntries[i].dwBytesInRes) > iconData16->fileSize)
523 WINE_WARN("file too small for icon contents\n");
524 break;
527 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
528 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
529 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
530 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
531 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
532 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
533 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
534 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
535 validEntries++;
536 memcpy(&icons[*iconOffset], &iconData16->fileBytes[matchingIcon->offset << iconData16->alignmentShiftCount], grpIconDir->idEntries[i].dwBytesInRes);
537 *iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
539 return validEntries;
542 static int populate_module_icons(HMODULE hModule, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
544 int i;
545 int validEntries = 0;
547 for (i = 0; i < grpIconDir->idCount; i++)
549 HRSRC hResInfo;
550 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
551 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
553 HGLOBAL hResData;
554 if ((hResData = LoadResource(hModule, hResInfo)))
556 BITMAPINFO *pIcon;
557 DWORD size = min( grpIconDir->idEntries[i].dwBytesInRes, ((IMAGE_RESOURCE_DATA_ENTRY *)hResInfo)->Size );
558 if ((pIcon = LockResource(hResData)))
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 = size;
567 iconDirEntries[validEntries].dwImageOffset = *iconOffset;
568 validEntries++;
569 memcpy(&icons[*iconOffset], pIcon, size);
570 *iconOffset += size;
572 FreeResource(hResData);
576 return validEntries;
579 static IStream *add_module_icons_to_stream(struct IconData16 *iconData16, HMODULE hModule, GRPICONDIR *grpIconDir)
581 int i;
582 SIZE_T iconsSize = 0;
583 BYTE *icons = NULL;
584 ICONDIRENTRY *iconDirEntries = NULL;
585 IStream *stream = NULL;
586 HRESULT hr = E_FAIL;
587 ULONG bytesWritten;
588 ICONDIR iconDir;
589 SIZE_T iconOffset;
590 int validEntries = 0;
591 LARGE_INTEGER zero;
593 for (i = 0; i < grpIconDir->idCount; i++)
594 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
595 icons = xmalloc(iconsSize);
596 iconDirEntries = xmalloc(grpIconDir->idCount*sizeof(ICONDIRENTRY));
597 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
598 if (FAILED(hr))
600 WINE_ERR("error creating icon stream\n");
601 goto end;
604 iconOffset = 0;
605 if (iconData16)
606 validEntries = populate_module16_icons(iconData16, grpIconDir, iconDirEntries, icons, &iconOffset);
607 else if (hModule)
608 validEntries = populate_module_icons(hModule, grpIconDir, iconDirEntries, icons, &iconOffset);
610 if (validEntries == 0)
612 WINE_ERR("no valid icon entries\n");
613 goto end;
616 iconDir.idReserved = 0;
617 iconDir.idType = 1;
618 iconDir.idCount = validEntries;
619 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
620 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
622 WINE_ERR("error 0x%08lX writing icon stream\n", hr);
623 goto end;
625 for (i = 0; i < validEntries; i++)
626 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
627 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
628 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
630 WINE_ERR("error 0x%08lX writing icon dir entries to stream\n", hr);
631 goto end;
633 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
634 if (FAILED(hr) || bytesWritten != iconOffset)
636 WINE_ERR("error 0x%08lX writing icon images to stream\n", hr);
637 goto end;
639 zero.QuadPart = 0;
640 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
642 end:
643 heap_free(icons);
644 heap_free(iconDirEntries);
645 if (FAILED(hr) && stream != NULL)
647 IStream_Release(stream);
648 stream = NULL;
650 return stream;
653 static HRESULT open_module16_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
655 HANDLE hFile = INVALID_HANDLE_VALUE;
656 HANDLE hFileMapping = NULL;
657 DWORD fileSize;
658 BYTE *fileBytes = NULL;
659 IMAGE_DOS_HEADER *dosHeader;
660 IMAGE_OS2_HEADER *neHeader;
661 BYTE *rsrcTab;
662 NE_TYPEINFO *iconGroupResources;
663 NE_TYPEINFO *iconResources;
664 NE_NAMEINFO *iconDirPtr;
665 GRPICONDIR *iconDir;
666 WORD alignmentShiftCount;
667 struct IconData16 iconData16;
668 HRESULT hr = E_FAIL;
670 hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
671 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
672 if (hFile == INVALID_HANDLE_VALUE)
674 WINE_WARN("opening %s failed with error %ld\n", wine_dbgstr_w(szFileName), GetLastError());
675 goto end;
678 hFileMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
679 if (hFileMapping == NULL)
681 WINE_WARN("CreateFileMapping failed, error %ld\n", GetLastError());
682 goto end;
685 fileSize = GetFileSize(hFile, NULL);
687 fileBytes = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
688 if (fileBytes == NULL)
690 WINE_WARN("MapViewOfFile failed, error %ld\n", GetLastError());
691 goto end;
694 dosHeader = (IMAGE_DOS_HEADER*)fileBytes;
695 if (sizeof(IMAGE_DOS_HEADER) >= fileSize || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
697 WINE_WARN("file too small for MZ header\n");
698 goto end;
701 neHeader = (IMAGE_OS2_HEADER*)(fileBytes + dosHeader->e_lfanew);
702 if ((((BYTE*)neHeader) + sizeof(IMAGE_OS2_HEADER)) > (fileBytes + fileSize) ||
703 neHeader->ne_magic != IMAGE_OS2_SIGNATURE)
705 WINE_WARN("file too small for NE header\n");
706 goto end;
709 rsrcTab = ((BYTE*)neHeader) + neHeader->ne_rsrctab;
710 if ((rsrcTab + 2) > (fileBytes + fileSize))
712 WINE_WARN("file too small for resource table\n");
713 goto end;
716 alignmentShiftCount = *(WORD*)rsrcTab;
717 rsrcTab += 2;
718 iconGroupResources = NULL;
719 iconResources = NULL;
720 for (;;)
722 NE_TYPEINFO *neTypeInfo = (NE_TYPEINFO*)rsrcTab;
723 if ((rsrcTab + sizeof(NE_TYPEINFO)) > (fileBytes + fileSize))
725 WINE_WARN("file too small for resource table\n");
726 goto end;
728 if (neTypeInfo->type_id == 0)
729 break;
730 else if (neTypeInfo->type_id == NE_RSCTYPE_GROUP_ICON)
731 iconGroupResources = neTypeInfo;
732 else if (neTypeInfo->type_id == NE_RSCTYPE_ICON)
733 iconResources = neTypeInfo;
734 rsrcTab += sizeof(NE_TYPEINFO) + neTypeInfo->count*sizeof(NE_NAMEINFO);
736 if (iconGroupResources == NULL)
738 WINE_WARN("no group icon resource type found\n");
739 goto end;
741 if (iconResources == NULL)
743 WINE_WARN("no icon resource type found\n");
744 goto end;
747 if (nIndex >= iconGroupResources->count)
749 WINE_WARN("icon index out of range\n");
750 goto end;
753 iconDirPtr = (NE_NAMEINFO*)(((BYTE*)iconGroupResources) + sizeof(NE_TYPEINFO) + nIndex*sizeof(NE_NAMEINFO));
754 if ((((BYTE*)iconDirPtr) + sizeof(NE_NAMEINFO)) > (fileBytes + fileSize))
756 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
757 goto end;
759 iconDir = (GRPICONDIR*)(fileBytes + (iconDirPtr->offset << alignmentShiftCount));
760 if ((((BYTE*)iconDir) + sizeof(GRPICONDIR) + iconDir->idCount*sizeof(GRPICONDIRENTRY)) > (fileBytes + fileSize))
762 WINE_WARN("file too small for GRPICONDIR\n");
763 goto end;
766 iconData16.fileBytes = fileBytes;
767 iconData16.fileSize = fileSize;
768 iconData16.iconResources = iconResources;
769 iconData16.alignmentShiftCount = alignmentShiftCount;
770 *ppStream = add_module_icons_to_stream(&iconData16, NULL, iconDir);
771 if (*ppStream)
772 hr = S_OK;
774 end:
775 if (hFile != INVALID_HANDLE_VALUE)
776 CloseHandle(hFile);
777 if (hFileMapping != NULL)
778 CloseHandle(hFileMapping);
779 if (fileBytes != NULL)
780 UnmapViewOfFile(fileBytes);
781 return hr;
784 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
786 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
788 if (!sEnumRes->nIndex--)
790 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
791 return FALSE;
793 else
794 return TRUE;
797 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
799 HMODULE hModule;
800 HRSRC hResInfo;
801 HGLOBAL hResData;
802 GRPICONDIR *pIconDir;
803 ENUMRESSTRUCT sEnumRes;
804 HRESULT hr = E_FAIL;
805 WCHAR fullPathW[MAX_PATH];
806 DWORD len;
808 len = SearchPathW(NULL, szFileName, L".exe", MAX_PATH, fullPathW, NULL);
809 if (len == 0 || len > MAX_PATH)
811 WINE_WARN("SearchPath failed\n");
812 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
815 hModule = LoadLibraryExW(fullPathW, 0, LOAD_LIBRARY_AS_DATAFILE);
816 if (!hModule)
818 if (GetLastError() == ERROR_BAD_EXE_FORMAT)
819 return open_module16_icon(fullPathW, nIndex, ppStream);
820 else
822 WINE_WARN("LoadLibraryExW (%s) failed, error %ld\n",
823 wine_dbgstr_w(fullPathW), GetLastError());
824 return HRESULT_FROM_WIN32(GetLastError());
828 if (nIndex < 0)
830 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
831 WINE_TRACE("FindResourceW (%s) called, return %p, error %ld\n",
832 wine_dbgstr_w(fullPathW), hResInfo, GetLastError());
834 else
836 hResInfo=NULL;
837 sEnumRes.pResInfo = &hResInfo;
838 sEnumRes.nIndex = nIndex;
839 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
840 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
841 sEnumRes.nIndex != -1)
843 WINE_TRACE("EnumResourceNamesW failed, error %ld\n", GetLastError());
847 if (hResInfo)
849 if ((hResData = LoadResource(hModule, hResInfo)))
851 if ((pIconDir = LockResource(hResData)))
853 *ppStream = add_module_icons_to_stream(0, hModule, pIconDir);
854 if (*ppStream)
855 hr = S_OK;
858 FreeResource(hResData);
861 else
863 WINE_WARN("found no icon\n");
864 FreeLibrary(hModule);
865 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
868 FreeLibrary(hModule);
869 return hr;
872 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
874 ICONDIR iconDir;
875 ULONG bytesRead;
876 HRESULT hr;
878 *ppIconDirEntries = NULL;
880 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
881 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
882 (iconDir.idReserved != 0) || (iconDir.idType != 1))
884 WINE_WARN("Invalid ico file format (hr=0x%08lX, bytesRead=%ld)\n", hr, bytesRead);
885 hr = E_FAIL;
886 goto end;
888 *numEntries = iconDir.idCount;
890 *ppIconDirEntries = xmalloc(sizeof(ICONDIRENTRY)*iconDir.idCount);
891 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
892 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
894 if (SUCCEEDED(hr)) hr = E_FAIL;
895 goto end;
898 end:
899 if (FAILED(hr))
900 heap_free(*ppIconDirEntries);
901 return hr;
904 static HRESULT validate_ico(IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
906 HRESULT hr;
908 hr = read_ico_direntries(*ppStream, ppIconDirEntries, numEntries);
909 if (SUCCEEDED(hr))
911 if (*numEntries)
912 return hr;
913 heap_free(*ppIconDirEntries);
914 *ppIconDirEntries = NULL;
916 IStream_Release(*ppStream);
917 *ppStream = NULL;
918 return E_FAIL;
921 static HRESULT write_native_icon(IStream *iconStream, ICONDIRENTRY *pIconDirEntry,
922 int numEntries, const WCHAR *icon_name)
924 int nMax = 0, nMaxBits = 0;
925 int nIndex = 0;
926 int i;
927 LARGE_INTEGER position;
928 HRESULT hr;
930 for (i = 0; i < numEntries; i++)
932 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
933 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
934 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
936 nIndex = i;
937 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
938 nMaxBits = pIconDirEntry[i].wBitCount;
941 WINE_TRACE("Selected: %d\n", nIndex);
943 position.QuadPart = 0;
944 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
945 if (FAILED(hr)) return hr;
946 return convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name);
949 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
951 HRESULT hr;
952 WCHAR *value = NULL;
953 DWORD size = 0;
954 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
955 if (SUCCEEDED(hr))
957 value = xmalloc(size * sizeof(WCHAR));
958 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
959 if (FAILED(hr))
961 heap_free(value);
962 value = NULL;
965 return value;
968 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
970 WCHAR *extension;
971 WCHAR *icon = NULL;
972 WCHAR *comma;
973 WCHAR *executable = NULL;
974 int index = 0;
975 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
977 extension = wcsrchr(szFileName, '.');
978 if (extension == NULL)
979 goto end;
981 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
982 if (icon)
984 comma = wcsrchr(icon, ',');
985 if (comma)
987 *comma = 0;
988 index = wcstol(comma + 1, NULL, 10);
990 hr = open_module_icon(icon, index, ppStream);
992 else
994 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, L"open");
995 if (executable)
996 hr = open_module_icon(executable, 0, ppStream);
999 end:
1000 heap_free(icon);
1001 heap_free(executable);
1002 return hr;
1005 static HRESULT open_default_icon(IStream **ppStream)
1007 return open_module_icon(L"user32", -(INT_PTR)IDI_WINLOGO, ppStream);
1010 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
1012 HRESULT hr;
1014 hr = open_module_icon(filename, index, ppStream);
1015 if (FAILED(hr))
1017 if(bWait && hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
1019 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1020 wine_dbgstr_w(filename));
1021 return hr;
1023 else
1025 /* This might be a raw .ico file */
1026 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
1029 if (SUCCEEDED(hr))
1030 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1032 if (FAILED(hr))
1034 hr = open_file_type_icon(filename, ppStream);
1035 if (SUCCEEDED(hr))
1036 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1038 if (FAILED(hr) && !bWait)
1040 hr = open_default_icon(ppStream);
1041 if (SUCCEEDED(hr))
1042 hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
1044 return hr;
1047 static WCHAR *compute_native_identifier(int exeIndex, LPCWSTR icoPathW, LPCWSTR filename)
1049 unsigned short crc;
1050 const WCHAR *basename, *ext;
1052 if (filename) return xwcsdup( filename );
1054 crc = crc16(icoPathW);
1055 basename = wcsrchr(icoPathW, '\\');
1056 if (basename == NULL) basename = icoPathW;
1057 else basename++;
1058 ext = wcsrchr(basename, '.');
1059 if (!ext) ext = basename + lstrlenW(basename);
1061 return heap_wprintf(L"%04X_%.*s.%d", crc, (int)(ext - basename), basename, exeIndex);
1064 static void refresh_icon_cache(const WCHAR *iconsDir)
1066 WCHAR buffer[MAX_PATH];
1068 /* The icon theme spec only requires the mtime on the "toplevel"
1069 * directory (whatever that is) to be changed for a refresh,
1070 * but on GNOME you have to create a file in that directory
1071 * instead. Creating a file also works on KDE, Xfce and LXDE.
1073 GetTempFileNameW( iconsDir, L"icn", 0, buffer );
1074 DeleteFileW( buffer );
1077 static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1078 int numEntries, int exeIndex, LPCWSTR icoPathW,
1079 const WCHAR *destFilename, WCHAR **nativeIdentifier)
1081 int i;
1082 WCHAR *iconsDir;
1083 HRESULT hr = S_OK;
1084 LARGE_INTEGER zero;
1086 *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW, destFilename);
1087 iconsDir = heap_wprintf(L"%s\\icons\\hicolor", xdg_data_dir);
1089 for (i = 0; i < numEntries; i++)
1091 int bestIndex = i;
1092 int j;
1093 BOOLEAN duplicate = FALSE;
1094 int w, h;
1095 WCHAR *iconDir;
1096 WCHAR *pngPath;
1098 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
1099 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
1101 for (j = 0; j < i; j++)
1103 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1104 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
1106 duplicate = TRUE;
1107 break;
1110 if (duplicate)
1111 continue;
1112 for (j = i + 1; j < numEntries; j++)
1114 if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
1115 iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1116 iconDirEntries[j].wBitCount >= iconDirEntries[bestIndex].wBitCount)
1118 bestIndex = j;
1121 WINE_TRACE("Selected: %d\n", bestIndex);
1123 w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
1124 h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
1125 iconDir = heap_wprintf(L"%s\\%dx%d\\apps", iconsDir, w, h);
1126 create_directories(iconDir);
1127 pngPath = heap_wprintf(L"%s\\%s.png", iconDir, *nativeIdentifier);
1128 zero.QuadPart = 0;
1129 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
1130 if (SUCCEEDED(hr))
1131 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder, pngPath);
1133 heap_free(iconDir);
1134 heap_free(pngPath);
1136 refresh_icon_cache(iconsDir);
1137 heap_free(iconsDir);
1138 return hr;
1141 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1142 static WCHAR *extract_icon(LPCWSTR icoPathW, int index, const WCHAR *destFilename, BOOL bWait)
1144 IStream *stream = NULL;
1145 ICONDIRENTRY *pIconDirEntries = NULL;
1146 int numEntries;
1147 HRESULT hr;
1148 WCHAR *nativeIdentifier = NULL;
1149 WCHAR fullPathW[MAX_PATH];
1150 DWORD len;
1152 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_w(destFilename));
1154 len = GetFullPathNameW(icoPathW, MAX_PATH, fullPathW, NULL);
1155 if (len == 0 || len > MAX_PATH)
1157 WINE_WARN("GetFullPathName failed\n");
1158 return NULL;
1161 hr = open_icon(fullPathW, index, bWait, &stream, &pIconDirEntries, &numEntries);
1162 if (FAILED(hr))
1164 WINE_WARN("opening icon %s index %d failed, hr=0x%08lX\n", wine_dbgstr_w(fullPathW), index, hr);
1165 goto end;
1167 hr = platform_write_icon(stream, pIconDirEntries, numEntries, index, fullPathW, destFilename, &nativeIdentifier);
1168 if (FAILED(hr))
1169 WINE_WARN("writing icon failed, error 0x%08lX\n", hr);
1171 end:
1172 if (stream)
1173 IStream_Release(stream);
1174 heap_free(pIconDirEntries);
1175 if (FAILED(hr))
1177 heap_free(nativeIdentifier);
1178 nativeIdentifier = NULL;
1180 return nativeIdentifier;
1183 static HKEY open_menus_reg_key(void)
1185 HKEY assocKey;
1186 DWORD ret;
1187 ret = RegCreateKeyW(HKEY_CURRENT_USER, L"Software\\Wine\\MenuFiles", &assocKey);
1188 if (ret == ERROR_SUCCESS)
1189 return assocKey;
1190 SetLastError(ret);
1191 return NULL;
1194 static DWORD register_menus_entry(const WCHAR *menu_file, const WCHAR *windows_file)
1196 HKEY hkey;
1197 DWORD ret;
1199 hkey = open_menus_reg_key();
1200 if (hkey)
1202 ret = RegSetValueExW(hkey, menu_file, 0, REG_SZ, (const BYTE*)windows_file,
1203 (lstrlenW(windows_file) + 1) * sizeof(WCHAR));
1204 RegCloseKey(hkey);
1206 else
1207 ret = GetLastError();
1208 return ret;
1211 /* This escapes reserved characters in .desktop files' Exec keys. */
1212 static LPSTR escape(LPCWSTR arg)
1214 int i, j;
1215 WCHAR *escaped_string;
1216 char *utf8_string;
1218 escaped_string = xmalloc((4 * lstrlenW(arg) + 1) * sizeof(WCHAR));
1219 for (i = j = 0; arg[i]; i++)
1221 switch (arg[i])
1223 case '\\':
1224 escaped_string[j++] = '\\';
1225 escaped_string[j++] = '\\';
1226 escaped_string[j++] = '\\';
1227 escaped_string[j++] = '\\';
1228 break;
1229 case ' ':
1230 case '\t':
1231 case '\n':
1232 case '"':
1233 case '\'':
1234 case '>':
1235 case '<':
1236 case '~':
1237 case '|':
1238 case '&':
1239 case ';':
1240 case '$':
1241 case '*':
1242 case '?':
1243 case '#':
1244 case '(':
1245 case ')':
1246 case '`':
1247 escaped_string[j++] = '\\';
1248 escaped_string[j++] = '\\';
1249 /* fall through */
1250 default:
1251 escaped_string[j++] = arg[i];
1252 break;
1255 escaped_string[j] = 0;
1256 utf8_string = wchars_to_utf8_chars(escaped_string);
1257 heap_free(escaped_string);
1258 return utf8_string;
1261 static BOOL write_desktop_entry(const WCHAR *link, const WCHAR *location, const WCHAR *linkname,
1262 const WCHAR *path, const WCHAR *args, const WCHAR *descr,
1263 const WCHAR *workdir, const WCHAR *icon, const WCHAR *wmclass)
1265 FILE *file;
1266 char *workdir_unix;
1267 int needs_chmod = FALSE;
1268 const WCHAR *name;
1269 const WCHAR *prefix = _wgetenv( L"WINECONFIGDIR" );
1271 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_w(link), wine_dbgstr_w(location),
1272 wine_dbgstr_w(linkname), wine_dbgstr_w(path), wine_dbgstr_w(args),
1273 wine_dbgstr_w(descr), wine_dbgstr_w(workdir), wine_dbgstr_w(icon),
1274 wine_dbgstr_w(wmclass));
1276 name = PathFindFileNameW( linkname );
1277 if (!location)
1279 location = heap_wprintf(L"%s\\%s.desktop", xdg_desktop_dir, name);
1280 needs_chmod = TRUE;
1283 file = _wfopen( location, L"wb" );
1284 if (file == NULL)
1285 return FALSE;
1287 fprintf(file, "[Desktop Entry]\n");
1288 fprintf(file, "Name=%s\n", wchars_to_utf8_chars(name));
1289 fprintf(file, "Exec=" );
1290 if (prefix)
1292 char *path = wine_get_unix_file_name( prefix );
1293 fprintf(file, "env WINEPREFIX=\"%s\" ", path);
1294 heap_free( path );
1296 fprintf(file, "wine %s", escape(path));
1297 if (args) fprintf(file, " %s", escape(args) );
1298 fputc( '\n', file );
1299 fprintf(file, "Type=Application\n");
1300 fprintf(file, "StartupNotify=true\n");
1301 if (descr && *descr)
1302 fprintf(file, "Comment=%s\n", wchars_to_utf8_chars(descr));
1303 if (workdir && *workdir && (workdir_unix = wine_get_unix_file_name(workdir)))
1304 fprintf(file, "Path=%s\n", workdir_unix);
1305 if (icon && *icon)
1306 fprintf(file, "Icon=%s\n", wchars_to_utf8_chars(icon));
1307 if (wmclass && *wmclass)
1308 fprintf(file, "StartupWMClass=%s\n", wchars_to_utf8_chars(wmclass));
1310 fclose(file);
1312 if (needs_chmod)
1314 const char *argv[] = { "chmod", "+x", wine_get_unix_file_name(location), NULL };
1315 __wine_unix_spawnvp( (char **)argv, FALSE );
1318 if (link)
1320 DWORD ret = register_menus_entry(location, link);
1321 if (ret != ERROR_SUCCESS)
1322 return FALSE;
1325 return TRUE;
1328 static BOOL write_directory_entry(const WCHAR *directory, const WCHAR *location)
1330 FILE *file;
1332 WINE_TRACE("(%s,%s)\n", wine_dbgstr_w(directory), wine_dbgstr_w(location));
1334 file = _wfopen( location, L"wb" );
1335 if (file == NULL)
1336 return FALSE;
1338 fprintf(file, "[Desktop Entry]\n");
1339 fprintf(file, "Type=Directory\n");
1340 if (wcscmp(directory, L"wine") == 0)
1342 fprintf(file, "Name=Wine\n");
1343 fprintf(file, "Icon=wine\n");
1345 else
1347 fprintf(file, "Name=%s\n", wchars_to_utf8_chars(directory));
1348 fprintf(file, "Icon=folder\n");
1351 fclose(file);
1352 return TRUE;
1355 static BOOL write_menu_file(const WCHAR *windows_link, const WCHAR *link)
1357 WCHAR tempfilename[MAX_PATH];
1358 FILE *tempfile = NULL;
1359 WCHAR *filename, *lastEntry, *menuPath;
1360 int i;
1361 int count = 0;
1362 BOOL ret = FALSE;
1364 WINE_TRACE("(%s)\n", wine_dbgstr_w(link));
1366 GetTempFileNameW( xdg_menu_dir, L"mnu", 0, tempfilename );
1367 if (!(tempfile = _wfopen( tempfilename, L"wb" ))) return FALSE;
1369 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1370 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1371 fprintf(tempfile, "<Menu>\n");
1372 fprintf(tempfile, " <Name>Applications</Name>\n");
1374 filename = heap_wprintf(L"wine\\%s.desktop", link);
1375 lastEntry = filename;
1376 for (i = 0; filename[i]; i++)
1378 if (filename[i] == '\\')
1380 WCHAR *dir_file_name;
1381 const char *prefix = count ? "" : "wine-";
1383 filename[i] = 0;
1384 fprintf(tempfile, " <Menu>\n");
1385 fprintf(tempfile, " <Name>%s%s</Name>\n",
1386 prefix, wchars_to_xml_text(filename));
1387 fprintf(tempfile, " <Directory>%s%s.directory</Directory>\n",
1388 prefix, wchars_to_xml_text(filename));
1389 dir_file_name = heap_wprintf(L"%s\\desktop-directories\\%s%s.directory",
1390 xdg_data_dir, count ? L"" : L"wine-", filename);
1391 if (GetFileAttributesW( dir_file_name ) == INVALID_FILE_ATTRIBUTES)
1392 write_directory_entry(lastEntry, dir_file_name);
1393 heap_free(dir_file_name);
1394 filename[i] = '-';
1395 lastEntry = &filename[i+1];
1396 ++count;
1399 filename[i] = 0;
1401 fprintf(tempfile, " <Include>\n");
1402 fprintf(tempfile, " <Filename>%s</Filename>\n", wchars_to_xml_text(filename));
1403 fprintf(tempfile, " </Include>\n");
1404 for (i = 0; i < count; i++)
1405 fprintf(tempfile, " </Menu>\n");
1406 fprintf(tempfile, "</Menu>\n");
1408 menuPath = heap_wprintf(L"%s\\%s", xdg_menu_dir, filename);
1409 lstrcpyW(menuPath + lstrlenW(menuPath) - lstrlenW(L".desktop"), L".menu");
1411 fclose(tempfile);
1412 ret = MoveFileExW( tempfilename, menuPath, MOVEFILE_REPLACE_EXISTING );
1413 if (ret)
1414 register_menus_entry(menuPath, windows_link);
1415 else
1416 DeleteFileW( tempfilename );
1417 heap_free(filename);
1418 heap_free(menuPath);
1419 return ret;
1422 static BOOL write_menu_entry(const WCHAR *windows_link, const WCHAR *link, const WCHAR *path, const WCHAR *args,
1423 const WCHAR *descr, const WCHAR *workdir, const WCHAR *icon, const WCHAR *wmclass)
1425 WCHAR *desktopPath;
1426 WCHAR *desktopDir;
1427 WCHAR *filename = NULL;
1428 BOOL ret = TRUE;
1430 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_w(windows_link), wine_dbgstr_w(link),
1431 wine_dbgstr_w(path), wine_dbgstr_w(args), wine_dbgstr_w(descr),
1432 wine_dbgstr_w(workdir), wine_dbgstr_w(icon), wine_dbgstr_w(wmclass));
1434 desktopPath = heap_wprintf(L"%s\\applications\\wine\\%s.desktop", xdg_data_dir, link);
1435 desktopDir = wcsrchr(desktopPath, '\\');
1436 *desktopDir = 0;
1437 if (!create_directories(desktopPath))
1439 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_w(desktopPath));
1440 ret = FALSE;
1441 goto end;
1443 *desktopDir = '\\';
1444 if (!write_desktop_entry(windows_link, desktopPath, link, path, args, descr, workdir, icon, wmclass))
1446 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_w(desktopPath));
1447 ret = FALSE;
1448 goto end;
1451 if (!write_menu_file(windows_link, link))
1453 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_w(filename));
1454 ret = FALSE;
1457 end:
1458 heap_free(desktopPath);
1459 heap_free(filename);
1460 return ret;
1463 /***********************************************************************
1464 * get_link_location
1466 * returns TRUE if successful
1467 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1468 * *relative will contain the address of a heap-allocated copy of the portion
1469 * of the filename that is within the specified location, in unix form
1471 static BOOL get_link_location( LPCWSTR linkfile, DWORD *loc, WCHAR **relative )
1473 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1474 DWORD len, i, filelen;
1475 const DWORD locations[] = {
1476 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1477 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1478 CSIDL_COMMON_STARTMENU };
1480 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1481 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1482 if (filelen==0 || filelen>MAX_PATH)
1483 return FALSE;
1485 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1487 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1488 * expand or our hardcoded list won't match.
1490 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1491 if (filelen==0 || filelen>MAX_PATH)
1492 return FALSE;
1494 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1496 for( i=0; i<ARRAY_SIZE( locations ); i++ )
1498 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1499 continue;
1501 len = lstrlenW(buffer);
1502 if (len >= MAX_PATH)
1503 continue; /* We've just trashed memory! Hopefully we are OK */
1505 if (len > filelen || filename[len]!='\\')
1506 continue;
1507 if (wcsnicmp( filename, buffer, len )) continue;
1509 /* return the remainder of the string and link type */
1510 *loc = locations[i];
1511 *relative = xwcsdup( filename + len + 1 );
1512 PathRemoveExtensionW( *relative );
1513 return TRUE;
1516 return FALSE;
1519 /* gets the target path directly or through MSI */
1520 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1521 LPWSTR szArgs, DWORD argsSize)
1523 IShellLinkDataList *dl = NULL;
1524 EXP_DARWIN_LINK *dar = NULL;
1525 HRESULT hr;
1527 szPath[0] = 0;
1528 szArgs[0] = 0;
1530 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1531 if (hr == S_OK && szPath[0])
1533 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1534 return hr;
1537 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1538 if (FAILED(hr))
1539 return hr;
1541 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1542 if (SUCCEEDED(hr))
1544 WCHAR* szCmdline;
1545 DWORD cmdSize;
1547 cmdSize=0;
1548 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1549 if (hr == ERROR_SUCCESS)
1551 cmdSize++;
1552 szCmdline = xmalloc(cmdSize*sizeof(WCHAR) );
1553 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1554 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1555 if (hr == ERROR_SUCCESS)
1557 WCHAR *s, *d;
1558 int bcount = 0;
1559 BOOL in_quotes = FALSE;
1561 /* Extract the application path */
1562 s=szCmdline;
1563 d=szPath;
1564 while (*s)
1566 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1568 /* skip the remaining spaces */
1569 do {
1570 s++;
1571 } while (*s==0x0009 || *s==0x0020);
1572 break;
1574 else if (*s==0x005c)
1576 /* '\\' */
1577 *d++=*s++;
1578 bcount++;
1580 else if (*s==0x0022)
1582 /* '"' */
1583 if ((bcount & 1)==0)
1585 /* Preceded by an even number of '\', this is
1586 * half that number of '\', plus a quote which
1587 * we erase.
1589 d-=bcount/2;
1590 in_quotes=!in_quotes;
1591 s++;
1593 else
1595 /* Preceded by an odd number of '\', this is
1596 * half that number of '\' followed by a '"'
1598 d=d-bcount/2-1;
1599 *d++='"';
1600 s++;
1602 bcount=0;
1604 else
1606 /* a regular character */
1607 *d++=*s++;
1608 bcount=0;
1610 if ((d-szPath) == pathSize)
1612 /* Keep processing the path till we get to the
1613 * arguments, but 'stand still'
1615 d--;
1618 /* Close the application path */
1619 *d=0;
1621 lstrcpynW(szArgs, s, argsSize);
1623 heap_free(szCmdline );
1625 LocalFree( dar );
1628 IShellLinkDataList_Release( dl );
1629 return hr;
1632 static WCHAR *slashes_to_minuses(const WCHAR *string)
1634 int i;
1635 WCHAR *ret = xwcsdup(string);
1637 for (i = 0; ret[i]; i++) if (ret[i] == '/') ret[i] = '-';
1638 return ret;
1641 static BOOL next_line(FILE *file, char **line, int *size)
1643 int pos = 0;
1644 char *cr;
1645 if (*line == NULL)
1647 *size = 4096;
1648 *line = xmalloc(*size);
1650 while (*line != NULL)
1652 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1654 heap_free(*line);
1655 *line = NULL;
1656 if (feof(file))
1657 return TRUE;
1658 return FALSE;
1660 pos = strlen(*line);
1661 cr = strchr(*line, '\n');
1662 if (cr == NULL)
1664 (*size) *= 2;
1665 *line = xrealloc(*line, *size);
1667 else
1669 *cr = 0;
1670 return TRUE;
1673 return FALSE;
1676 static BOOL add_mimes(const WCHAR *dir, struct list *mime_types)
1678 WCHAR *globs_filename;
1679 BOOL ret = TRUE;
1680 FILE *globs_file;
1682 globs_filename = heap_wprintf(L"%s\\mime\\globs", dir);
1683 globs_file = _wfopen( globs_filename, L"r" );
1684 if (globs_file) /* doesn't have to exist */
1686 char *line = NULL;
1687 int size = 0;
1688 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1690 char *pos;
1691 struct xdg_mime_type *mime_type_entry = NULL;
1692 if (line[0] != '#' && (pos = strchr(line, ':')))
1694 mime_type_entry = xmalloc(sizeof(struct xdg_mime_type));
1695 *pos = 0;
1696 mime_type_entry->mimeType = utf8_chars_to_wchars(line);
1697 mime_type_entry->glob = utf8_chars_to_wchars(pos + 1);
1698 list_add_tail(mime_types, &mime_type_entry->entry);
1701 heap_free(line);
1702 fclose(globs_file);
1704 heap_free(globs_filename);
1705 return ret;
1708 static void free_native_mime_types(struct list *native_mime_types)
1710 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1712 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1714 list_remove(&mime_type_entry->entry);
1715 heap_free(mime_type_entry->glob);
1716 heap_free(mime_type_entry->mimeType);
1717 heap_free(mime_type_entry);
1721 static BOOL build_native_mime_types(struct list *mime_types)
1723 WCHAR *dirs, *dir, *dos_name, *ctx, *p;
1724 BOOL ret;
1726 if (_wgetenv( L"XDG_DATA_DIRS" ))
1727 dirs = xwcsdup( _wgetenv( L"XDG_DATA_DIRS" ));
1728 else
1729 dirs = xwcsdup( L"/usr/local/share/:/usr/share/" );
1731 ret = add_mimes(xdg_data_dir, mime_types);
1732 if (ret)
1734 for (dir = wcstok( dirs, L":", &ctx ); dir; dir = wcstok( NULL, L":", &ctx ))
1736 dos_name = heap_wprintf( L"\\\\?\\unix%s", dir );
1737 for (p = dos_name; *p; p++) if (*p == '/') *p = '\\';
1738 if (p > dos_name + 9 && p[-1] == '\\') p[-1] = 0;
1739 ret = add_mimes(dos_name, mime_types);
1740 heap_free( dos_name );
1741 if (!ret)
1742 break;
1745 heap_free(dirs);
1747 if (!ret)
1748 free_native_mime_types(mime_types);
1749 return ret;
1752 static WCHAR *freedesktop_mime_type_for_extension(struct list *native_mime_types,
1753 const WCHAR *extensionW)
1755 struct xdg_mime_type *mime_type_entry;
1756 int matchLength = 0;
1757 const WCHAR* match = NULL;
1759 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1761 if (PathMatchSpecW( extensionW, mime_type_entry->glob ))
1763 if (match == NULL || matchLength < lstrlenW(mime_type_entry->glob))
1765 match = mime_type_entry->mimeType;
1766 matchLength = lstrlenW(mime_type_entry->glob);
1771 return match ? xwcsdup(match) : NULL;
1774 static WCHAR *reg_enum_keyW(HKEY key, DWORD index)
1776 WCHAR *subkey;
1777 DWORD size = 1024 * sizeof(WCHAR);
1778 LSTATUS ret;
1780 for (;;)
1782 subkey = xmalloc(size);
1783 ret = RegEnumKeyExW(key, index, subkey, &size, NULL, NULL, NULL, NULL);
1784 if (ret == ERROR_SUCCESS)
1786 return subkey;
1788 if (ret != ERROR_MORE_DATA)
1790 heap_free(subkey);
1791 return NULL;
1793 size *= 2;
1794 heap_free(subkey);
1798 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1800 DWORD size;
1801 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1803 WCHAR *ret = xmalloc(size);
1804 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1805 return ret;
1806 heap_free(ret);
1808 return NULL;
1811 static HKEY open_associations_reg_key(void)
1813 HKEY assocKey;
1814 if (RegCreateKeyW(HKEY_CURRENT_USER, L"Software\\Wine\\FileOpenAssociations", &assocKey) == ERROR_SUCCESS)
1815 return assocKey;
1816 return NULL;
1819 static BOOL has_association_changed(LPCWSTR extensionW, const WCHAR *mimeType, const WCHAR *progId,
1820 const WCHAR *appName, const WCHAR *openWithIcon)
1822 HKEY assocKey;
1823 BOOL ret;
1825 if ((assocKey = open_associations_reg_key()))
1827 WCHAR *value;
1829 ret = FALSE;
1831 value = reg_get_valW(assocKey, extensionW, L"MimeType");
1832 if (!value || wcscmp(value, mimeType))
1833 ret = TRUE;
1834 heap_free(value);
1836 value = reg_get_valW(assocKey, extensionW, L"ProgID");
1837 if (!value || wcscmp(value, progId))
1838 ret = TRUE;
1839 heap_free(value);
1841 value = reg_get_valW(assocKey, extensionW, L"AppName");
1842 if (!value || wcscmp(value, appName))
1843 ret = TRUE;
1844 heap_free(value);
1846 value = reg_get_valW(assocKey, extensionW, L"OpenWithIcon");
1847 if ((openWithIcon && !value) ||
1848 (!openWithIcon && value) ||
1849 (openWithIcon && value && wcscmp(value, openWithIcon)))
1850 ret = TRUE;
1851 heap_free(value);
1853 RegCloseKey(assocKey);
1855 else
1857 WINE_ERR("error opening associations registry key\n");
1858 ret = FALSE;
1860 return ret;
1863 static void update_association(LPCWSTR extension, const WCHAR *mimeType, const WCHAR *progId,
1864 const WCHAR *appName, const WCHAR *desktopFile, const WCHAR *openWithIcon)
1866 HKEY assocKey = NULL;
1867 HKEY subkey = NULL;
1869 assocKey = open_associations_reg_key();
1870 if (assocKey == NULL)
1872 WINE_ERR("could not open file associations key\n");
1873 goto done;
1876 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
1878 WINE_ERR("could not create extension subkey\n");
1879 goto done;
1882 RegSetValueExW(subkey, L"MimeType", 0, REG_SZ, (const BYTE*) mimeType, (lstrlenW(mimeType) + 1) * sizeof(WCHAR));
1883 RegSetValueExW(subkey, L"ProgID", 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1884 RegSetValueExW(subkey, L"AppName", 0, REG_SZ, (const BYTE*) appName, (lstrlenW(appName) + 1) * sizeof(WCHAR));
1885 RegSetValueExW(subkey, L"DesktopFile", 0, REG_SZ, (const BYTE*) desktopFile, (lstrlenW(desktopFile) + 1) * sizeof(WCHAR));
1886 if (openWithIcon)
1887 RegSetValueExW(subkey, L"OpenWithIcon", 0, REG_SZ, (const BYTE*) openWithIcon, (lstrlenW(openWithIcon) + 1) * sizeof(WCHAR));
1888 else
1889 RegDeleteValueW(subkey, L"OpenWithIcon");
1891 done:
1892 RegCloseKey(assocKey);
1893 RegCloseKey(subkey);
1896 static BOOL cleanup_associations(void)
1898 HKEY assocKey;
1899 BOOL hasChanged = FALSE;
1900 if ((assocKey = open_associations_reg_key()))
1902 int i = 0;
1903 for (;;)
1905 WCHAR *extensionW;
1906 WCHAR *command;
1908 if (!(extensionW = reg_enum_keyW(assocKey, i)))
1909 break;
1911 if (!(command = assoc_query(ASSOCSTR_COMMAND, extensionW, L"open")))
1913 WCHAR *desktopFile = reg_get_valW(assocKey, extensionW, L"DesktopFile");
1914 if (desktopFile)
1916 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
1917 DeleteFileW(desktopFile);
1919 RegDeleteKeyW(assocKey, extensionW);
1920 hasChanged = TRUE;
1921 heap_free(desktopFile);
1923 else
1925 i++;
1926 heap_free(command);
1928 heap_free(extensionW);
1930 RegCloseKey(assocKey);
1932 else
1933 WINE_ERR("could not open file associations key\n");
1934 return hasChanged;
1937 static BOOL write_freedesktop_mime_type_entry(const WCHAR *packages_dir, const WCHAR *dot_extension,
1938 const WCHAR *mime_type, const WCHAR *comment)
1940 BOOL ret = FALSE;
1941 WCHAR *filename;
1942 FILE *packageFile;
1944 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_w(mime_type),
1945 wine_dbgstr_w(dot_extension), wine_dbgstr_w(comment));
1947 filename = heap_wprintf(L"%s\\x-wine-extension-%s.xml", packages_dir, dot_extension + 1);
1948 packageFile = _wfopen( filename, L"wb" );
1949 if (packageFile)
1951 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1952 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1953 fprintf(packageFile, " <mime-type type=\"%s\">\n", wchars_to_xml_text(mime_type));
1954 fprintf(packageFile, " <glob pattern=\"*%s\"/>\n", wchars_to_xml_text(dot_extension));
1955 if (comment) fprintf(packageFile, " <comment>%s</comment>\n", wchars_to_xml_text(comment));
1956 fprintf(packageFile, " </mime-type>\n");
1957 fprintf(packageFile, "</mime-info>\n");
1958 ret = TRUE;
1959 fclose(packageFile);
1961 else
1962 WINE_ERR("error writing file %s\n", debugstr_w(filename));
1963 heap_free(filename);
1964 return ret;
1967 static BOOL is_extension_banned(LPCWSTR extension)
1969 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1970 if (!wcsicmp(extension, L".com") ||
1971 !wcsicmp(extension, L".exe") ||
1972 !wcsicmp(extension, L".msi"))
1973 return TRUE;
1974 return FALSE;
1977 static WCHAR *get_special_mime_type(LPCWSTR extension)
1979 if (!wcsicmp(extension, L".lnk"))
1980 return xwcsdup(L"application/x-ms-shortcut");
1981 return NULL;
1984 static BOOL write_freedesktop_association_entry(const WCHAR *desktopPath, const WCHAR *friendlyAppName,
1985 const WCHAR *mimeType, const WCHAR *progId,
1986 const WCHAR *openWithIcon)
1988 BOOL ret = FALSE;
1989 FILE *desktop;
1990 const WCHAR *prefix = _wgetenv( L"WINECONFIGDIR" );
1992 WINE_TRACE("friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
1993 wine_dbgstr_w(friendlyAppName), wine_dbgstr_w(mimeType),
1994 wine_dbgstr_w(progId), wine_dbgstr_w(openWithIcon), wine_dbgstr_w(desktopPath));
1996 desktop = _wfopen( desktopPath, L"wb" );
1997 if (desktop)
1999 fprintf(desktop, "[Desktop Entry]\n");
2000 fprintf(desktop, "Type=Application\n");
2001 fprintf(desktop, "Name=%s\n", wchars_to_utf8_chars(friendlyAppName));
2002 fprintf(desktop, "MimeType=%s;\n", wchars_to_utf8_chars(mimeType));
2003 if (prefix)
2005 char *path = wine_get_unix_file_name( prefix );
2006 fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", path, escape(progId));
2007 heap_free( path );
2009 else
2010 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", escape(progId));
2011 fprintf(desktop, "NoDisplay=true\n");
2012 fprintf(desktop, "StartupNotify=true\n");
2013 if (openWithIcon)
2014 fprintf(desktop, "Icon=%s\n", wchars_to_utf8_chars(openWithIcon));
2015 ret = TRUE;
2016 fclose(desktop);
2018 else
2019 WINE_ERR("error writing association file %s\n", wine_dbgstr_w(desktopPath));
2020 return ret;
2023 static BOOL generate_associations(const WCHAR *packages_dir, const WCHAR *applications_dir)
2025 struct wine_rb_tree mimeProgidTree = { winemenubuilder_rb_string_compare };
2026 struct list nativeMimeTypes = LIST_INIT(nativeMimeTypes);
2027 int i;
2028 BOOL hasChanged = FALSE;
2030 if (!build_native_mime_types(&nativeMimeTypes))
2032 WINE_ERR("could not build native MIME types\n");
2033 return FALSE;
2036 for (i = 0; ; i++)
2038 WCHAR *extensionW;
2040 if (!(extensionW = reg_enum_keyW(HKEY_CLASSES_ROOT, i)))
2041 break;
2043 if (extensionW[0] == '.' && !is_extension_banned(extensionW))
2045 WCHAR *commandW = NULL;
2046 WCHAR *executableW = NULL;
2047 WCHAR *openWithIcon = NULL;
2048 WCHAR *friendlyDocNameW = NULL;
2049 WCHAR *iconW = NULL;
2050 WCHAR *contentTypeW = NULL;
2051 WCHAR *mimeType = NULL;
2052 const WCHAR *friendlyAppName;
2053 WCHAR *progIdW = NULL;
2054 WCHAR *mimeProgId = NULL;
2055 struct rb_string_entry *entry;
2057 wcslwr(extensionW);
2058 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2060 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2062 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2063 if (contentTypeW)
2064 wcslwr(contentTypeW);
2066 mimeType = freedesktop_mime_type_for_extension(&nativeMimeTypes, extensionW);
2068 if (mimeType == NULL)
2070 if (contentTypeW != NULL && wcschr(contentTypeW, '/'))
2071 mimeType = xwcsdup(contentTypeW);
2072 else if (!(mimeType = get_special_mime_type(extensionW)))
2073 mimeType = heap_wprintf(L"application/x-wine-extension-%s", &extensionW[1]);
2075 /* GNOME seems to ignore the <icon> tag in MIME packages,
2076 * and the default name is more intuitive anyway.
2078 if (iconW)
2080 WCHAR *flattened_mime = slashes_to_minuses(mimeType);
2081 int index = 0;
2082 WCHAR *comma = wcsrchr(iconW, ',');
2083 if (comma)
2085 *comma = 0;
2086 index = wcstol(comma + 1, NULL, 10);
2088 extract_icon(iconW, index, flattened_mime, FALSE);
2089 heap_free(flattened_mime);
2092 write_freedesktop_mime_type_entry(packages_dir, extensionW, mimeType, friendlyDocNameW);
2093 hasChanged = TRUE;
2096 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, L"open");
2097 if (commandW == NULL)
2098 /* no command => no application is associated */
2099 goto end;
2101 executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, L"open");
2102 if (executableW)
2103 openWithIcon = compute_native_identifier(0, executableW, NULL);
2105 friendlyAppName = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, L"open");
2106 if (!friendlyAppName) friendlyAppName = L"A Wine application";
2108 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2109 if (!progIdW) goto end; /* no progID => not a file type association */
2111 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2112 mimeProgId = heap_wprintf(L"%s=>%s", mimeType, progIdW);
2113 if (wine_rb_get(&mimeProgidTree, mimeProgId))
2115 heap_free(mimeProgId);
2116 goto end;
2118 entry = xmalloc(sizeof(struct rb_string_entry));
2119 entry->string = mimeProgId;
2120 if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
2122 WINE_ERR("error updating rb tree\n");
2123 goto end;
2126 if (has_association_changed(extensionW, mimeType, progIdW, friendlyAppName, openWithIcon))
2128 WCHAR *desktopPath = heap_wprintf(L"%s\\wine-extension-%s.desktop",
2129 applications_dir, extensionW + 1 );
2130 if (write_freedesktop_association_entry(desktopPath, friendlyAppName, mimeType, progIdW, openWithIcon))
2132 hasChanged = TRUE;
2133 update_association(extensionW, mimeType, progIdW, friendlyAppName, desktopPath, openWithIcon);
2135 heap_free(desktopPath);
2138 if (hasChanged && openWithIcon) extract_icon(executableW, 0, openWithIcon, FALSE);
2140 end:
2141 heap_free(commandW);
2142 heap_free(executableW);
2143 heap_free(openWithIcon);
2144 heap_free(friendlyDocNameW);
2145 heap_free(iconW);
2146 heap_free(contentTypeW);
2147 heap_free(mimeType);
2148 heap_free(progIdW);
2150 heap_free(extensionW);
2153 wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2154 free_native_mime_types(&nativeMimeTypes);
2155 return hasChanged;
2158 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2160 WCHAR *icon_name, *link_name;
2161 WCHAR szTmp[INFOTIPSIZE];
2162 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2163 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH], szWMClass[MAX_PATH];
2164 int iIconId = 0, r = -1;
2165 DWORD csidl = -1;
2166 HANDLE hsem = NULL;
2168 if ( !link )
2170 WINE_ERR("Link name is null\n");
2171 return FALSE;
2174 if( !get_link_location( link, &csidl, &link_name ) )
2176 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2177 return TRUE;
2179 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2181 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2182 return TRUE;
2184 WINE_TRACE("Link : %s\n", wine_dbgstr_w(link_name));
2186 szTmp[0] = 0;
2187 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2188 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2189 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2191 szTmp[0] = 0;
2192 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2193 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2194 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2196 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2197 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2198 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2199 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2201 szTmp[0] = 0;
2202 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2203 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2204 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2206 szWMClass[0] = 0;
2208 if( !szPath[0] )
2210 LPITEMIDLIST pidl = NULL;
2211 IShellLinkW_GetIDList( sl, &pidl );
2212 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2213 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2216 /* extract the icon */
2217 if( szIconPath[0] )
2218 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2219 else
2220 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2222 /* fail - try once again after parent process exit */
2223 if( !icon_name )
2225 if (bWait)
2227 WINE_WARN("Unable to extract icon, deferring.\n");
2228 goto cleanup;
2230 WINE_ERR("failed to extract icon from %s\n",
2231 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2234 /* check the path */
2235 if( szPath[0] )
2237 /* FIXME: Use AppUserModelID if present. */
2238 WCHAR *p = PathFindFileNameW(szPath);
2240 if (p)
2242 lstrcpyW(szWMClass, p);
2243 CharLowerW(szWMClass);
2247 /* building multiple menus concurrently has race conditions */
2248 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2249 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2251 WINE_ERR("failed wait for semaphore\n");
2252 goto cleanup;
2255 if (in_desktop_dir(csidl))
2257 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY || !szPath[0])
2258 r = !write_desktop_entry(link, NULL, link_name, link, NULL,
2259 szDescription, szWorkDir, icon_name, szWMClass);
2260 else
2261 r = !write_desktop_entry(NULL, NULL, link_name, szPath, szArgs,
2262 szDescription, szWorkDir, icon_name, szWMClass);
2264 else
2265 r = !write_menu_entry(link, link_name, link, NULL, szDescription, szWorkDir, icon_name, szWMClass);
2267 ReleaseSemaphore( hsem, 1, NULL );
2269 cleanup:
2270 if (hsem) CloseHandle( hsem );
2271 heap_free(icon_name );
2272 heap_free(link_name );
2274 if (r && !bWait)
2275 WINE_ERR("failed to build the menu\n" );
2277 return ( r == 0 );
2280 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2282 WCHAR *link_name, *icon_name = NULL;
2283 DWORD csidl = -1;
2284 LPWSTR urlPath = NULL;
2285 HRESULT hr;
2286 HANDLE hSem = NULL;
2287 BOOL ret = TRUE;
2288 int r = -1;
2289 IPropertySetStorage *pPropSetStg;
2290 IPropertyStorage *pPropStg;
2291 PROPSPEC ps[2];
2292 PROPVARIANT pv[2];
2293 BOOL has_icon = FALSE;
2295 if ( !link )
2297 WINE_ERR("Link name is null\n");
2298 return TRUE;
2301 if( !get_link_location( link, &csidl, &link_name ) )
2303 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2304 return TRUE;
2306 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2308 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2309 ret = TRUE;
2310 goto cleanup;
2312 WINE_TRACE("Link : %s\n", wine_dbgstr_w(link_name));
2314 hr = url->lpVtbl->GetURL(url, &urlPath);
2315 if (FAILED(hr))
2317 ret = TRUE;
2318 goto cleanup;
2320 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2322 ps[0].ulKind = PRSPEC_PROPID;
2323 ps[0].u.propid = PID_IS_ICONFILE;
2324 ps[1].ulKind = PRSPEC_PROPID;
2325 ps[1].u.propid = PID_IS_ICONINDEX;
2327 hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
2328 if (SUCCEEDED(hr))
2330 hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
2331 if (SUCCEEDED(hr))
2333 hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
2334 if (SUCCEEDED(hr))
2336 if (pv[0].vt == VT_LPWSTR && pv[0].pwszVal && pv[0].pwszVal[0])
2338 has_icon = TRUE;
2339 icon_name = extract_icon( pv[0].pwszVal, pv[1].iVal, NULL, bWait );
2341 WINE_TRACE("URL icon path: %s icon index: %d icon name: %s\n", wine_dbgstr_w(pv[0].pwszVal), pv[1].iVal, debugstr_w(icon_name));
2343 PropVariantClear(&pv[0]);
2344 PropVariantClear(&pv[1]);
2346 IPropertyStorage_Release(pPropStg);
2348 IPropertySetStorage_Release(pPropSetStg);
2351 /* fail - try once again after parent process exit */
2352 if( has_icon && !icon_name )
2354 if (bWait)
2356 WINE_WARN("Unable to extract icon, deferring.\n");
2357 ret = FALSE;
2358 goto cleanup;
2360 WINE_ERR("failed to extract icon from %s\n",
2361 wine_dbgstr_w( pv[0].pwszVal ));
2364 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2365 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2367 WINE_ERR("failed wait for semaphore\n");
2368 goto cleanup;
2370 if (in_desktop_dir(csidl))
2371 r = !write_desktop_entry(NULL, NULL, link_name, L"start.exe", urlPath, NULL, NULL, icon_name, NULL);
2372 else
2373 r = !write_menu_entry(link, link_name, L"start.exe", urlPath, NULL, NULL, icon_name, NULL);
2374 ret = (r == 0);
2375 ReleaseSemaphore(hSem, 1, NULL);
2377 cleanup:
2378 if (hSem)
2379 CloseHandle(hSem);
2380 heap_free(icon_name );
2381 heap_free(link_name);
2382 CoTaskMemFree( urlPath );
2383 return ret;
2386 static BOOL WaitForParentProcess( void )
2388 PROCESSENTRY32 procentry;
2389 HANDLE hsnapshot = NULL, hprocess = NULL;
2390 DWORD ourpid = GetCurrentProcessId();
2391 BOOL ret = FALSE, rc;
2393 WINE_TRACE("Waiting for parent process\n");
2394 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2395 INVALID_HANDLE_VALUE)
2397 WINE_ERR("CreateToolhelp32Snapshot failed, error %ld\n", GetLastError());
2398 goto done;
2401 procentry.dwSize = sizeof(PROCESSENTRY32);
2402 rc = Process32First( hsnapshot, &procentry );
2403 while (rc)
2405 if (procentry.th32ProcessID == ourpid) break;
2406 rc = Process32Next( hsnapshot, &procentry );
2408 if (!rc)
2410 WINE_WARN("Unable to find current process id %ld when listing processes\n", ourpid);
2411 goto done;
2414 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2415 NULL)
2417 WINE_WARN("OpenProcess failed pid=%ld, error %ld\n", procentry.th32ParentProcessID,
2418 GetLastError());
2419 goto done;
2422 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2423 ret = TRUE;
2424 else
2425 WINE_ERR("Unable to wait for parent process, error %ld\n", GetLastError());
2427 done:
2428 if (hprocess) CloseHandle( hprocess );
2429 if (hsnapshot) CloseHandle( hsnapshot );
2430 return ret;
2433 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2435 IShellLinkW *sl;
2436 IPersistFile *pf;
2437 HRESULT r;
2438 WCHAR fullname[MAX_PATH];
2439 DWORD len;
2441 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2443 if( !linkname[0] )
2445 WINE_ERR("link name missing\n");
2446 return FALSE;
2449 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2450 if (len==0 || len>MAX_PATH)
2452 WINE_ERR("couldn't get full path of link file\n");
2453 return FALSE;
2456 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2457 &IID_IShellLinkW, (LPVOID *) &sl );
2458 if( FAILED( r ) )
2460 WINE_ERR("No IID_IShellLink\n");
2461 return FALSE;
2464 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2465 if( FAILED( r ) )
2467 WINE_ERR("No IID_IPersistFile\n");
2468 return FALSE;
2471 r = IPersistFile_Load( pf, fullname, STGM_READ );
2472 if( SUCCEEDED( r ) )
2474 /* If something fails (eg. Couldn't extract icon)
2475 * wait for parent process and try again
2477 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2479 WaitForParentProcess();
2480 InvokeShellLinker( sl, fullname, FALSE );
2483 else
2485 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2488 IPersistFile_Release( pf );
2489 IShellLinkW_Release( sl );
2491 return !r;
2494 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2496 IUniformResourceLocatorW *url;
2497 IPersistFile *pf;
2498 HRESULT r;
2499 WCHAR fullname[MAX_PATH];
2500 DWORD len;
2502 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2504 if( !urlname[0] )
2506 WINE_ERR("URL name missing\n");
2507 return FALSE;
2510 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2511 if (len==0 || len>MAX_PATH)
2513 WINE_ERR("couldn't get full path of URL file\n");
2514 return FALSE;
2517 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2518 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2519 if( FAILED( r ) )
2521 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2522 return FALSE;
2525 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2526 if( FAILED( r ) )
2528 WINE_ERR("No IID_IPersistFile\n");
2529 return FALSE;
2531 r = IPersistFile_Load( pf, fullname, STGM_READ );
2532 if( SUCCEEDED( r ) )
2534 /* If something fails (eg. Couldn't extract icon)
2535 * wait for parent process and try again
2537 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2539 WaitForParentProcess();
2540 InvokeShellLinkerForURL( url, fullname, FALSE );
2544 IPersistFile_Release( pf );
2545 url->lpVtbl->Release( url );
2547 return !r;
2550 static void RefreshFileTypeAssociations(void)
2552 HANDLE hSem = NULL;
2553 WCHAR *mime_dir;
2554 WCHAR *packages_dir;
2555 WCHAR *applications_dir;
2556 BOOL hasChanged;
2558 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2559 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2561 WINE_ERR("failed wait for semaphore\n");
2562 CloseHandle(hSem);
2563 return;
2566 mime_dir = heap_wprintf(L"%s\\mime", xdg_data_dir);
2567 packages_dir = heap_wprintf(L"%s\\packages", mime_dir);
2568 create_directories(packages_dir);
2570 applications_dir = heap_wprintf(L"%s\\applications", xdg_data_dir);
2571 create_directories(applications_dir);
2573 hasChanged = generate_associations(packages_dir, applications_dir);
2574 hasChanged |= cleanup_associations();
2575 if (hasChanged)
2577 const char *argv[3];
2579 argv[0] = "update-mime-database";
2580 argv[1] = wine_get_unix_file_name(mime_dir);
2581 argv[2] = NULL;
2582 __wine_unix_spawnvp( (char **)argv, FALSE );
2584 argv[0] = "update-desktop-database";
2585 argv[1] = wine_get_unix_file_name(applications_dir);
2586 __wine_unix_spawnvp( (char **)argv, FALSE );
2589 ReleaseSemaphore(hSem, 1, NULL);
2590 CloseHandle(hSem);
2591 heap_free(mime_dir);
2592 heap_free(packages_dir);
2593 heap_free(applications_dir);
2596 static void cleanup_menus(void)
2598 HKEY hkey;
2600 hkey = open_menus_reg_key();
2601 if (hkey)
2603 int i;
2604 LSTATUS lret = ERROR_SUCCESS;
2605 for (i = 0; lret == ERROR_SUCCESS; )
2607 WCHAR *value = NULL;
2608 WCHAR *data = NULL;
2609 DWORD valueSize = 4096;
2610 DWORD dataSize = 4096;
2611 while (1)
2613 value = xmalloc(valueSize * sizeof(WCHAR));
2614 data = xmalloc(dataSize * sizeof(WCHAR));
2615 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2616 if (lret != ERROR_MORE_DATA)
2617 break;
2618 valueSize *= 2;
2619 dataSize *= 2;
2620 heap_free(value);
2621 heap_free(data);
2622 value = data = NULL;
2624 if (lret == ERROR_SUCCESS)
2626 if (GetFileAttributesW( data ) == INVALID_FILE_ATTRIBUTES)
2628 WINE_TRACE("removing menu related file %s\n", debugstr_w(value));
2629 DeleteFileW( value );
2630 RegDeleteValueW(hkey, value);
2632 else
2633 i++;
2635 else if (lret != ERROR_NO_MORE_ITEMS)
2636 WINE_ERR("error %ld reading registry\n", lret);
2637 heap_free(value);
2638 heap_free(data);
2640 RegCloseKey(hkey);
2644 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
2646 char *utf8lnkPath = NULL;
2647 WCHAR *winLnkPath = NULL;
2648 IShellLinkW *shellLink = NULL;
2649 IPersistFile *persistFile = NULL;
2650 WCHAR szTmp[MAX_PATH];
2651 WCHAR szPath[MAX_PATH];
2652 WCHAR szArgs[INFOTIPSIZE];
2653 WCHAR szIconPath[MAX_PATH];
2654 int iconId;
2655 IStream *stream = NULL;
2656 ICONDIRENTRY *pIconDirEntries = NULL;
2657 int numEntries;
2658 HRESULT hr;
2660 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
2661 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
2662 if (winLnkPath == NULL)
2664 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
2665 goto end;
2668 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2669 &IID_IShellLinkW, (LPVOID*)&shellLink);
2670 if (FAILED(hr))
2672 WINE_ERR("could not create IShellLinkW, error 0x%08lX\n", hr);
2673 goto end;
2676 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
2677 if (FAILED(hr))
2679 WINE_ERR("could not query IPersistFile, error 0x%08lX\n", hr);
2680 goto end;
2683 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
2684 if (FAILED(hr))
2686 WINE_ERR("could not read .lnk, error 0x%08lX\n", hr);
2687 goto end;
2690 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2691 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2692 szTmp[0] = 0;
2693 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
2694 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2696 if(!szPath[0])
2698 LPITEMIDLIST pidl = NULL;
2699 IShellLinkW_GetIDList(shellLink, &pidl);
2700 if (pidl && SHGetPathFromIDListW(pidl, szPath))
2701 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2704 if (szIconPath[0])
2706 hr = open_icon(szIconPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
2707 if (SUCCEEDED(hr))
2708 hr = write_native_icon(stream, pIconDirEntries, numEntries, outputPath);
2710 else
2712 hr = open_icon(szPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
2713 if (SUCCEEDED(hr))
2714 hr = write_native_icon(stream, pIconDirEntries, numEntries, outputPath);
2717 end:
2718 heap_free(utf8lnkPath);
2719 heap_free(winLnkPath);
2720 if (shellLink != NULL)
2721 IShellLinkW_Release(shellLink);
2722 if (persistFile != NULL)
2723 IPersistFile_Release(persistFile);
2724 if (stream != NULL)
2725 IStream_Release(stream);
2726 heap_free(pIconDirEntries);
2729 static WCHAR *next_token( LPWSTR *p )
2731 LPWSTR token = NULL, t = *p;
2733 if( !t )
2734 return NULL;
2736 while( t && !token )
2738 switch( *t )
2740 case ' ':
2741 t++;
2742 continue;
2743 case '"':
2744 /* unquote the token */
2745 token = ++t;
2746 t = wcschr( token, '"' );
2747 if( t )
2748 *t++ = 0;
2749 break;
2750 case 0:
2751 t = NULL;
2752 break;
2753 default:
2754 token = t;
2755 t = wcschr( token, ' ' );
2756 if( t )
2757 *t++ = 0;
2758 break;
2761 *p = t;
2762 return token;
2765 static BOOL init_xdg(void)
2767 WCHAR *p;
2768 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, xdg_desktop_dir);
2770 if (FAILED(hr)) return FALSE;
2772 if ((p = _wgetenv( L"XDG_CONFIG_HOME" )))
2773 xdg_menu_dir = heap_wprintf( L"\\??\\unix%s/menus/applications-merged", p );
2774 else
2775 xdg_menu_dir = heap_wprintf( L"%s/.config/menus/applications-merged", _wgetenv(L"WINEHOMEDIR") );
2776 for (p = xdg_menu_dir; *p; p++) if (*p == '/') *p = '\\';
2777 xdg_menu_dir[1] = '\\'; /* change \??\ to \\?\ */
2778 create_directories(xdg_menu_dir);
2780 if ((p = _wgetenv( L"XDG_DATA_HOME" )))
2781 xdg_data_dir = heap_wprintf( L"\\??\\unix%s", p );
2782 else
2783 xdg_data_dir = heap_wprintf( L"%s/.local/share", _wgetenv(L"WINEHOMEDIR") );
2784 for (p = xdg_data_dir; *p; p++) if (*p == '/') *p = '\\';
2785 xdg_data_dir[1] = '\\'; /* change \??\ to \\?\ */
2787 p = heap_wprintf( L"%s\\desktop-directories", xdg_data_dir );
2788 create_directories(p);
2789 heap_free(p);
2790 return TRUE;
2793 static BOOL associations_enabled(void)
2795 BOOL ret = TRUE;
2796 HKEY hkey;
2797 BYTE buf[32];
2798 DWORD len;
2800 if ((hkey = open_associations_reg_key()))
2802 len = sizeof(buf);
2803 if (!RegQueryValueExA(hkey, "Enable", NULL, NULL, buf, &len))
2804 ret = IS_OPTION_TRUE(buf[0]);
2805 RegCloseKey( hkey );
2808 return ret;
2811 /***********************************************************************
2813 * wWinMain
2815 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
2817 LPWSTR token = NULL, p;
2818 BOOL bWait = FALSE;
2819 BOOL bURL = FALSE;
2820 HRESULT hr;
2821 int ret = 0;
2823 if (!init_xdg())
2824 return 1;
2826 hr = CoInitialize(NULL);
2827 if (FAILED(hr))
2829 WINE_ERR("could not initialize COM, error 0x%08lX\n", hr);
2830 return 1;
2833 for( p = cmdline; p && *p; )
2835 token = next_token( &p );
2836 if( !token )
2837 break;
2838 if( !wcscmp( token, L"-a" ) )
2840 if (associations_enabled())
2841 RefreshFileTypeAssociations();
2842 continue;
2844 if( !wcscmp( token, L"-r" ) )
2846 cleanup_menus();
2847 continue;
2849 if( !wcscmp( token, L"-w" ) )
2850 bWait = TRUE;
2851 else if ( !wcscmp( token, L"-u" ) )
2852 bURL = TRUE;
2853 else if ( !wcscmp( token, L"-t" ) )
2855 WCHAR *lnkFile = next_token( &p );
2856 if (lnkFile)
2858 WCHAR *outputFile = next_token( &p );
2859 if (outputFile)
2860 thumbnail_lnk(lnkFile, outputFile);
2863 else if( token[0] == '-' )
2865 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
2867 else
2869 BOOL bRet;
2871 if (bURL)
2872 bRet = Process_URL( token, bWait );
2873 else
2874 bRet = Process_Link( token, bWait );
2875 if (!bRet)
2877 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
2878 ret = 1;
2883 CoUninitialize();
2884 return ret;