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.
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
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
53 * Clean up fd.o menu icons and .directory files when the menu is deleted
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
61 * Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
62 * that write associations there won't associate (#17019).
72 #define NONAMELESSUNION
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"
121 GRPICONDIRENTRY idEntries
[1];
160 #define NE_RSCTYPE_ICON 0x8003
161 #define NE_RSCTYPE_GROUP_ICON 0x800e
178 struct rb_string_entry
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;
195 for (i
= 0; string
[i
] != 0; i
++)
198 for (j
= 0; j
< 16; c
>>= 1, j
++)
200 xor_poly
= (c
^ crc
) & 1;
209 static void *xmalloc( size_t size
)
211 void *ret
= HeapAlloc( GetProcessHeap(), 0, size
);
214 ERR( "out of memory\n" );
220 static void *xrealloc( void *ptr
, size_t size
)
222 if (!ptr
) return xmalloc( size
);
223 ptr
= HeapReAlloc( GetProcessHeap(), 0, ptr
, size
);
226 ERR( "out of memory\n" );
232 static WCHAR
*xwcsdup( const WCHAR
*str
)
236 if (!str
) return NULL
;
237 ret
= xmalloc( (lstrlenW(str
) + 1) * sizeof(WCHAR
) );
238 lstrcpyW( ret
, str
);
242 static void heap_free( void *ptr
)
244 HeapFree( GetProcessHeap(), 0, ptr
);
247 static WCHAR
* WINAPIV
heap_wprintf(const WCHAR
*format
, ...)
256 buffer
= xmalloc(size
* sizeof(WCHAR
));
257 va_start(args
, format
);
258 n
= _vsnwprintf(buffer
, size
, format
, args
);
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
);
284 static BOOL
create_directories(WCHAR
*directory
)
286 WCHAR
*p
= PathSkipRootW( directory
);
288 for ( ; p
&& *p
; p
++)
293 CreateDirectoryW( directory
, NULL
);
297 return CreateDirectoryW( directory
, NULL
) || GetLastError() == ERROR_ALREADY_EXISTS
;
300 static char* wchars_to_utf8_chars(LPCWSTR string
)
303 INT size
= WideCharToMultiByte(CP_UTF8
, 0, string
, -1, NULL
, 0, NULL
, NULL
);
305 WideCharToMultiByte(CP_UTF8
, 0, string
, -1, ret
, size
, NULL
, NULL
);
309 static WCHAR
* utf8_chars_to_wchars(LPCSTR string
)
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
);
318 static char *wchars_to_xml_text(const WCHAR
*string
)
321 char *text
= wchars_to_utf8_chars( string
);
322 char *ret
= xmalloc( 6 * strlen(text
) + 1 );
324 for (i
= pos
= 0; text
[i
]; i
++)
327 pos
+= sprintf(ret
+ pos
, "&");
328 else if (text
[i
] == '<')
329 pos
+= sprintf(ret
+ pos
, "<");
330 else if (text
[i
] == '>')
331 pos
+= sprintf(ret
+ pos
, ">");
332 else if (text
[i
] == '\'')
333 pos
+= sprintf(ret
+ pos
, "'");
334 else if (text
[i
] == '"')
335 pos
+= sprintf(ret
+ pos
, """);
337 ret
[pos
++] = text
[i
];
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
;
360 hr
= CoCreateInstance(&CLSID_WICImagingFactory
, NULL
, CLSCTX_INPROC_SERVER
,
361 &IID_IWICImagingFactory
, (void**)&factory
);
364 WINE_ERR("error 0x%08lX creating IWICImagingFactory\n", hr
);
367 hr
= IWICImagingFactory_CreateDecoderFromStream(factory
, icoFile
, NULL
,
368 WICDecodeMetadataCacheOnDemand
, &decoder
);
371 WINE_ERR("error 0x%08lX creating IWICBitmapDecoder\n", hr
);
374 hr
= CoCreateInstance(outputFormat
, NULL
, CLSCTX_INPROC_SERVER
,
375 &IID_IWICBitmapEncoder
, (void**)&encoder
);
378 WINE_ERR("error 0x%08lX creating bitmap encoder\n", hr
);
381 hr
= SHCreateStreamOnFileW(outputFileName
, STGM_CREATE
| STGM_WRITE
, &outputFile
);
384 WINE_ERR("error 0x%08lX creating output file %s\n", hr
, wine_dbgstr_w(outputFileName
));
387 hr
= IWICBitmapEncoder_Initialize(encoder
, outputFile
, WICBitmapEncoderNoCache
);
390 WINE_ERR("error 0x%08lX initializing encoder\n", hr
);
394 for (i
= 0; i
< numIndices
; i
++)
396 IWICBitmapFrameDecode
*sourceFrame
= NULL
;
397 IWICBitmapSource
*sourceBitmap
= NULL
;
398 IWICBitmapFrameEncode
*dstFrame
= NULL
;
399 IPropertyBag2
*options
= NULL
;
402 hr
= IWICBitmapDecoder_GetFrame(decoder
, indices
[i
], &sourceFrame
);
405 WINE_ERR("error 0x%08lX getting frame %d\n", hr
, indices
[i
]);
408 hr
= WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA
, (IWICBitmapSource
*)sourceFrame
, &sourceBitmap
);
411 WINE_ERR("error 0x%08lX converting bitmap to 32bppBGRA\n", hr
);
414 hr
= IWICBitmapEncoder_CreateNewFrame(encoder
, &dstFrame
, &options
);
417 WINE_ERR("error 0x%08lX creating encoder frame\n", hr
);
420 hr
= IWICBitmapFrameEncode_Initialize(dstFrame
, options
);
423 WINE_ERR("error 0x%08lX initializing encoder frame\n", hr
);
426 hr
= IWICBitmapSource_GetSize(sourceBitmap
, &width
, &height
);
429 WINE_ERR("error 0x%08lX getting source bitmap size\n", hr
);
432 hr
= IWICBitmapFrameEncode_SetSize(dstFrame
, width
, height
);
435 WINE_ERR("error 0x%08lX setting destination bitmap size\n", hr
);
438 hr
= IWICBitmapFrameEncode_SetResolution(dstFrame
, 96, 96);
441 WINE_ERR("error 0x%08lX setting destination bitmap resolution\n", hr
);
444 hr
= IWICBitmapFrameEncode_WriteSource(dstFrame
, sourceBitmap
, NULL
);
447 WINE_ERR("error 0x%08lX copying bitmaps\n", hr
);
450 hr
= IWICBitmapFrameEncode_Commit(dstFrame
);
453 WINE_ERR("error 0x%08lX committing frame\n", hr
);
458 IWICBitmapFrameDecode_Release(sourceFrame
);
460 IWICBitmapSource_Release(sourceBitmap
);
462 IWICBitmapFrameEncode_Release(dstFrame
);
464 IPropertyBag2_Release(options
);
467 hr
= IWICBitmapEncoder_Commit(encoder
);
470 WINE_ERR("error 0x%08lX committing encoder\n", hr
);
476 IWICImagingFactory_Release(factory
);
478 IWICBitmapDecoder_Release(decoder
);
480 IWICBitmapEncoder_Release(encoder
);
482 IStream_Release(outputFile
);
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
)
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");
511 if (iconInfo
->id
== (0x8000 | grpIconDir
->idEntries
[i
].nID
))
513 matchingIcon
= iconInfo
;
516 iconPtr
+= sizeof(NE_NAMEINFO
);
519 if (matchingIcon
== NULL
)
521 if (((matchingIcon
->offset
<< iconData16
->alignmentShiftCount
) + grpIconDir
->idEntries
[i
].dwBytesInRes
) > iconData16
->fileSize
)
523 WINE_WARN("file too small for icon contents\n");
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
;
536 memcpy(&icons
[*iconOffset
], &iconData16
->fileBytes
[matchingIcon
->offset
<< iconData16
->alignmentShiftCount
], grpIconDir
->idEntries
[i
].dwBytesInRes
);
537 *iconOffset
+= grpIconDir
->idEntries
[i
].dwBytesInRes
;
542 static int populate_module_icons(HMODULE hModule
, GRPICONDIR
*grpIconDir
, ICONDIRENTRY
*iconDirEntries
, BYTE
*icons
, SIZE_T
*iconOffset
)
545 int validEntries
= 0;
547 for (i
= 0; i
< grpIconDir
->idCount
; i
++)
550 LPCWSTR lpName
= MAKEINTRESOURCEW(grpIconDir
->idEntries
[i
].nID
);
551 if ((hResInfo
= FindResourceW(hModule
, lpName
, (LPCWSTR
)RT_ICON
)))
554 if ((hResData
= LoadResource(hModule
, hResInfo
)))
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
;
569 memcpy(&icons
[*iconOffset
], pIcon
, size
);
572 FreeResource(hResData
);
579 static IStream
*add_module_icons_to_stream(struct IconData16
*iconData16
, HMODULE hModule
, GRPICONDIR
*grpIconDir
)
582 SIZE_T iconsSize
= 0;
584 ICONDIRENTRY
*iconDirEntries
= NULL
;
585 IStream
*stream
= NULL
;
590 int validEntries
= 0;
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
);
600 WINE_ERR("error creating icon stream\n");
606 validEntries
= populate_module16_icons(iconData16
, grpIconDir
, iconDirEntries
, icons
, &iconOffset
);
608 validEntries
= populate_module_icons(hModule
, grpIconDir
, iconDirEntries
, icons
, &iconOffset
);
610 if (validEntries
== 0)
612 WINE_ERR("no valid icon entries\n");
616 iconDir
.idReserved
= 0;
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
);
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
);
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
);
640 hr
= IStream_Seek(stream
, zero
, STREAM_SEEK_SET
, NULL
);
644 heap_free(iconDirEntries
);
645 if (FAILED(hr
) && stream
!= NULL
)
647 IStream_Release(stream
);
653 static HRESULT
open_module16_icon(LPCWSTR szFileName
, int nIndex
, IStream
**ppStream
)
655 HANDLE hFile
= INVALID_HANDLE_VALUE
;
656 HANDLE hFileMapping
= NULL
;
658 BYTE
*fileBytes
= NULL
;
659 IMAGE_DOS_HEADER
*dosHeader
;
660 IMAGE_OS2_HEADER
*neHeader
;
662 NE_TYPEINFO
*iconGroupResources
;
663 NE_TYPEINFO
*iconResources
;
664 NE_NAMEINFO
*iconDirPtr
;
666 WORD alignmentShiftCount
;
667 struct IconData16 iconData16
;
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());
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());
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());
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");
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");
709 rsrcTab
= ((BYTE
*)neHeader
) + neHeader
->ne_rsrctab
;
710 if ((rsrcTab
+ 2) > (fileBytes
+ fileSize
))
712 WINE_WARN("file too small for resource table\n");
716 alignmentShiftCount
= *(WORD
*)rsrcTab
;
718 iconGroupResources
= NULL
;
719 iconResources
= NULL
;
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");
728 if (neTypeInfo
->type_id
== 0)
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");
741 if (iconResources
== NULL
)
743 WINE_WARN("no icon resource type found\n");
747 if (nIndex
>= iconGroupResources
->count
)
749 WINE_WARN("icon index out of range\n");
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");
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");
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
);
775 if (hFile
!= INVALID_HANDLE_VALUE
)
777 if (hFileMapping
!= NULL
)
778 CloseHandle(hFileMapping
);
779 if (fileBytes
!= NULL
)
780 UnmapViewOfFile(fileBytes
);
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
);
797 static HRESULT
open_module_icon(LPCWSTR szFileName
, int nIndex
, IStream
**ppStream
)
802 GRPICONDIR
*pIconDir
;
803 ENUMRESSTRUCT sEnumRes
;
805 WCHAR fullPathW
[MAX_PATH
];
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
);
818 if (GetLastError() == ERROR_BAD_EXE_FORMAT
)
819 return open_module16_icon(fullPathW
, nIndex
, ppStream
);
822 WINE_WARN("LoadLibraryExW (%s) failed, error %ld\n",
823 wine_dbgstr_w(fullPathW
), GetLastError());
824 return HRESULT_FROM_WIN32(GetLastError());
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());
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());
849 if ((hResData
= LoadResource(hModule
, hResInfo
)))
851 if ((pIconDir
= LockResource(hResData
)))
853 *ppStream
= add_module_icons_to_stream(0, hModule
, pIconDir
);
858 FreeResource(hResData
);
863 WINE_WARN("found no icon\n");
864 FreeLibrary(hModule
);
865 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND
);
868 FreeLibrary(hModule
);
872 static HRESULT
read_ico_direntries(IStream
*icoStream
, ICONDIRENTRY
**ppIconDirEntries
, int *numEntries
)
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
);
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
;
900 heap_free(*ppIconDirEntries
);
904 static HRESULT
validate_ico(IStream
**ppStream
, ICONDIRENTRY
**ppIconDirEntries
, int *numEntries
)
908 hr
= read_ico_direntries(*ppStream
, ppIconDirEntries
, numEntries
);
913 heap_free(*ppIconDirEntries
);
914 *ppIconDirEntries
= NULL
;
916 IStream_Release(*ppStream
);
921 static HRESULT
write_native_icon(IStream
*iconStream
, ICONDIRENTRY
*pIconDirEntry
,
922 int numEntries
, const WCHAR
*icon_name
)
924 int nMax
= 0, nMaxBits
= 0;
927 LARGE_INTEGER position
;
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
)
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
)
954 hr
= AssocQueryStringW(0, assocStr
, name
, extra
, NULL
, &size
);
957 value
= xmalloc(size
* sizeof(WCHAR
));
958 hr
= AssocQueryStringW(0, assocStr
, name
, extra
, value
, &size
);
968 static HRESULT
open_file_type_icon(LPCWSTR szFileName
, IStream
**ppStream
)
973 WCHAR
*executable
= NULL
;
975 HRESULT hr
= HRESULT_FROM_WIN32(ERROR_NOT_FOUND
);
977 extension
= wcsrchr(szFileName
, '.');
978 if (extension
== NULL
)
981 icon
= assoc_query(ASSOCSTR_DEFAULTICON
, extension
, NULL
);
984 comma
= wcsrchr(icon
, ',');
988 index
= wcstol(comma
+ 1, NULL
, 10);
990 hr
= open_module_icon(icon
, index
, ppStream
);
994 executable
= assoc_query(ASSOCSTR_EXECUTABLE
, extension
, L
"open");
996 hr
= open_module_icon(executable
, 0, ppStream
);
1001 heap_free(executable
);
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
)
1014 hr
= open_module_icon(filename
, index
, ppStream
);
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
));
1025 /* This might be a raw .ico file */
1026 hr
= SHCreateStreamOnFileW(filename
, STGM_READ
, ppStream
);
1030 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1034 hr
= open_file_type_icon(filename
, ppStream
);
1036 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1038 if (FAILED(hr
) && !bWait
)
1040 hr
= open_default_icon(ppStream
);
1042 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1047 static WCHAR
*compute_native_identifier(int exeIndex
, LPCWSTR icoPathW
, LPCWSTR filename
)
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
;
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
)
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
++)
1093 BOOLEAN duplicate
= FALSE
;
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
)
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
)
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
);
1129 hr
= IStream_Seek(icoStream
, zero
, STREAM_SEEK_SET
, NULL
);
1131 hr
= convert_to_native_icon(icoStream
, &bestIndex
, 1, &CLSID_WICPngEncoder
, pngPath
);
1136 refresh_icon_cache(iconsDir
);
1137 heap_free(iconsDir
);
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
;
1148 WCHAR
*nativeIdentifier
= NULL
;
1149 WCHAR fullPathW
[MAX_PATH
];
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");
1161 hr
= open_icon(fullPathW
, index
, bWait
, &stream
, &pIconDirEntries
, &numEntries
);
1164 WINE_WARN("opening icon %s index %d failed, hr=0x%08lX\n", wine_dbgstr_w(fullPathW
), index
, hr
);
1167 hr
= platform_write_icon(stream
, pIconDirEntries
, numEntries
, index
, fullPathW
, destFilename
, &nativeIdentifier
);
1169 WINE_WARN("writing icon failed, error 0x%08lX\n", hr
);
1173 IStream_Release(stream
);
1174 heap_free(pIconDirEntries
);
1177 heap_free(nativeIdentifier
);
1178 nativeIdentifier
= NULL
;
1180 return nativeIdentifier
;
1183 static HKEY
open_menus_reg_key(void)
1187 ret
= RegCreateKeyW(HKEY_CURRENT_USER
, L
"Software\\Wine\\MenuFiles", &assocKey
);
1188 if (ret
== ERROR_SUCCESS
)
1194 static DWORD
register_menus_entry(const WCHAR
*menu_file
, const WCHAR
*windows_file
)
1199 hkey
= open_menus_reg_key();
1202 ret
= RegSetValueExW(hkey
, menu_file
, 0, REG_SZ
, (const BYTE
*)windows_file
,
1203 (lstrlenW(windows_file
) + 1) * sizeof(WCHAR
));
1207 ret
= GetLastError();
1211 /* This escapes reserved characters in .desktop files' Exec keys. */
1212 static LPSTR
escape(LPCWSTR arg
)
1215 WCHAR
*escaped_string
;
1218 escaped_string
= xmalloc((4 * lstrlenW(arg
) + 1) * sizeof(WCHAR
));
1219 for (i
= j
= 0; arg
[i
]; i
++)
1224 escaped_string
[j
++] = '\\';
1225 escaped_string
[j
++] = '\\';
1226 escaped_string
[j
++] = '\\';
1227 escaped_string
[j
++] = '\\';
1247 escaped_string
[j
++] = '\\';
1248 escaped_string
[j
++] = '\\';
1251 escaped_string
[j
++] = arg
[i
];
1255 escaped_string
[j
] = 0;
1256 utf8_string
= wchars_to_utf8_chars(escaped_string
);
1257 heap_free(escaped_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
)
1267 int needs_chmod
= FALSE
;
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
);
1279 location
= heap_wprintf(L
"%s\\%s.desktop", xdg_desktop_dir
, name
);
1283 file
= _wfopen( location
, L
"wb" );
1287 fprintf(file
, "[Desktop Entry]\n");
1288 fprintf(file
, "Name=%s\n", wchars_to_utf8_chars(name
));
1289 fprintf(file
, "Exec=" );
1292 char *path
= wine_get_unix_file_name( prefix
);
1293 fprintf(file
, "env WINEPREFIX=\"%s\" ", 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
);
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
));
1314 const char *argv
[] = { "chmod", "+x", wine_get_unix_file_name(location
), NULL
};
1315 __wine_unix_spawnvp( (char **)argv
, FALSE
);
1320 DWORD ret
= register_menus_entry(location
, link
);
1321 if (ret
!= ERROR_SUCCESS
)
1328 static BOOL
write_directory_entry(const WCHAR
*directory
, const WCHAR
*location
)
1332 WINE_TRACE("(%s,%s)\n", wine_dbgstr_w(directory
), wine_dbgstr_w(location
));
1334 file
= _wfopen( location
, L
"wb" );
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");
1347 fprintf(file
, "Name=%s\n", wchars_to_utf8_chars(directory
));
1348 fprintf(file
, "Icon=folder\n");
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
;
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-";
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
);
1395 lastEntry
= &filename
[i
+1];
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");
1412 ret
= MoveFileExW( tempfilename
, menuPath
, MOVEFILE_REPLACE_EXISTING
);
1414 register_menus_entry(menuPath
, windows_link
);
1416 DeleteFileW( tempfilename
);
1417 heap_free(filename
);
1418 heap_free(menuPath
);
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
)
1427 WCHAR
*filename
= NULL
;
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
, '\\');
1437 if (!create_directories(desktopPath
))
1439 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_w(desktopPath
));
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
));
1451 if (!write_menu_file(windows_link
, link
))
1453 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_w(filename
));
1458 heap_free(desktopPath
);
1459 heap_free(filename
);
1463 /***********************************************************************
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
)
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
)
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
))
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
]!='\\')
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
);
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
;
1530 hr
= IShellLinkW_GetPath( sl
, szPath
, pathSize
, NULL
, SLGP_RAWPATH
);
1531 if (hr
== S_OK
&& szPath
[0])
1533 IShellLinkW_GetArguments( sl
, szArgs
, argsSize
);
1537 hr
= IShellLinkW_QueryInterface( sl
, &IID_IShellLinkDataList
, (LPVOID
*) &dl
);
1541 hr
= IShellLinkDataList_CopyDataBlock( dl
, EXP_DARWIN_ID_SIG
, (LPVOID
*) &dar
);
1548 hr
= CommandLineFromMsiDescriptor( dar
->szwDarwinID
, NULL
, &cmdSize
);
1549 if (hr
== ERROR_SUCCESS
)
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
)
1559 BOOL in_quotes
= FALSE
;
1561 /* Extract the application path */
1566 if ((*s
==0x0009 || *s
==0x0020) && !in_quotes
)
1568 /* skip the remaining spaces */
1571 } while (*s
==0x0009 || *s
==0x0020);
1574 else if (*s
==0x005c)
1580 else if (*s
==0x0022)
1583 if ((bcount
& 1)==0)
1585 /* Preceded by an even number of '\', this is
1586 * half that number of '\', plus a quote which
1590 in_quotes
=!in_quotes
;
1595 /* Preceded by an odd number of '\', this is
1596 * half that number of '\' followed by a '"'
1606 /* a regular character */
1610 if ((d
-szPath
) == pathSize
)
1612 /* Keep processing the path till we get to the
1613 * arguments, but 'stand still'
1618 /* Close the application path */
1621 lstrcpynW(szArgs
, s
, argsSize
);
1623 heap_free(szCmdline
);
1628 IShellLinkDataList_Release( dl
);
1632 static WCHAR
*slashes_to_minuses(const WCHAR
*string
)
1635 WCHAR
*ret
= xwcsdup(string
);
1637 for (i
= 0; ret
[i
]; i
++) if (ret
[i
] == '/') ret
[i
] = '-';
1641 static BOOL
next_line(FILE *file
, char **line
, int *size
)
1648 *line
= xmalloc(*size
);
1650 while (*line
!= NULL
)
1652 if (fgets(&(*line
)[pos
], *size
- pos
, file
) == NULL
)
1660 pos
= strlen(*line
);
1661 cr
= strchr(*line
, '\n');
1665 *line
= xrealloc(*line
, *size
);
1676 static BOOL
add_mimes(const WCHAR
*dir
, struct list
*mime_types
)
1678 WCHAR
*globs_filename
;
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 */
1688 while (ret
&& (ret
= next_line(globs_file
, &line
, &size
)) && line
)
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
));
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
);
1704 heap_free(globs_filename
);
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
;
1726 if (_wgetenv( L
"XDG_DATA_DIRS" ))
1727 dirs
= xwcsdup( _wgetenv( L
"XDG_DATA_DIRS" ));
1729 dirs
= xwcsdup( L
"/usr/local/share/:/usr/share/" );
1731 ret
= add_mimes(xdg_data_dir
, mime_types
);
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
);
1748 free_native_mime_types(mime_types
);
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
)
1777 DWORD size
= 1024 * sizeof(WCHAR
);
1782 subkey
= xmalloc(size
);
1783 ret
= RegEnumKeyExW(key
, index
, subkey
, &size
, NULL
, NULL
, NULL
, NULL
);
1784 if (ret
== ERROR_SUCCESS
)
1788 if (ret
!= ERROR_MORE_DATA
)
1798 static WCHAR
* reg_get_valW(HKEY key
, LPCWSTR subkey
, LPCWSTR name
)
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
)
1811 static HKEY
open_associations_reg_key(void)
1814 if (RegCreateKeyW(HKEY_CURRENT_USER
, L
"Software\\Wine\\FileOpenAssociations", &assocKey
) == ERROR_SUCCESS
)
1819 static BOOL
has_association_changed(LPCWSTR extensionW
, const WCHAR
*mimeType
, const WCHAR
*progId
,
1820 const WCHAR
*appName
, const WCHAR
*openWithIcon
)
1825 if ((assocKey
= open_associations_reg_key()))
1831 value
= reg_get_valW(assocKey
, extensionW
, L
"MimeType");
1832 if (!value
|| wcscmp(value
, mimeType
))
1836 value
= reg_get_valW(assocKey
, extensionW
, L
"ProgID");
1837 if (!value
|| wcscmp(value
, progId
))
1841 value
= reg_get_valW(assocKey
, extensionW
, L
"AppName");
1842 if (!value
|| wcscmp(value
, appName
))
1846 value
= reg_get_valW(assocKey
, extensionW
, L
"OpenWithIcon");
1847 if ((openWithIcon
&& !value
) ||
1848 (!openWithIcon
&& value
) ||
1849 (openWithIcon
&& value
&& wcscmp(value
, openWithIcon
)))
1853 RegCloseKey(assocKey
);
1857 WINE_ERR("error opening associations registry key\n");
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
;
1869 assocKey
= open_associations_reg_key();
1870 if (assocKey
== NULL
)
1872 WINE_ERR("could not open file associations key\n");
1876 if (RegCreateKeyW(assocKey
, extension
, &subkey
) != ERROR_SUCCESS
)
1878 WINE_ERR("could not create extension subkey\n");
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
));
1887 RegSetValueExW(subkey
, L
"OpenWithIcon", 0, REG_SZ
, (const BYTE
*) openWithIcon
, (lstrlenW(openWithIcon
) + 1) * sizeof(WCHAR
));
1889 RegDeleteValueW(subkey
, L
"OpenWithIcon");
1892 RegCloseKey(assocKey
);
1893 RegCloseKey(subkey
);
1896 static BOOL
cleanup_associations(void)
1899 BOOL hasChanged
= FALSE
;
1900 if ((assocKey
= open_associations_reg_key()))
1908 if (!(extensionW
= reg_enum_keyW(assocKey
, i
)))
1911 if (!(command
= assoc_query(ASSOCSTR_COMMAND
, extensionW
, L
"open")))
1913 WCHAR
*desktopFile
= reg_get_valW(assocKey
, extensionW
, L
"DesktopFile");
1916 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW
));
1917 DeleteFileW(desktopFile
);
1919 RegDeleteKeyW(assocKey
, extensionW
);
1921 heap_free(desktopFile
);
1928 heap_free(extensionW
);
1930 RegCloseKey(assocKey
);
1933 WINE_ERR("could not open file associations key\n");
1937 static BOOL
write_freedesktop_mime_type_entry(const WCHAR
*packages_dir
, const WCHAR
*dot_extension
,
1938 const WCHAR
*mime_type
, const WCHAR
*comment
)
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" );
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");
1959 fclose(packageFile
);
1962 WINE_ERR("error writing file %s\n", debugstr_w(filename
));
1963 heap_free(filename
);
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"))
1977 static WCHAR
*get_special_mime_type(LPCWSTR extension
)
1979 if (!wcsicmp(extension
, L
".lnk"))
1980 return xwcsdup(L
"application/x-ms-shortcut");
1984 static BOOL
write_freedesktop_association_entry(const WCHAR
*desktopPath
, const WCHAR
*friendlyAppName
,
1985 const WCHAR
*mimeType
, const WCHAR
*progId
,
1986 const WCHAR
*openWithIcon
)
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" );
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
));
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
));
2010 fprintf(desktop
, "Exec=wine start /ProgIDOpen %s %%f\n", escape(progId
));
2011 fprintf(desktop
, "NoDisplay=true\n");
2012 fprintf(desktop
, "StartupNotify=true\n");
2014 fprintf(desktop
, "Icon=%s\n", wchars_to_utf8_chars(openWithIcon
));
2019 WINE_ERR("error writing association file %s\n", wine_dbgstr_w(desktopPath
));
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
);
2028 BOOL hasChanged
= FALSE
;
2030 if (!build_native_mime_types(&nativeMimeTypes
))
2032 WINE_ERR("could not build native MIME types\n");
2040 if (!(extensionW
= reg_enum_keyW(HKEY_CLASSES_ROOT
, i
)))
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
;
2058 friendlyDocNameW
= assoc_query(ASSOCSTR_FRIENDLYDOCNAME
, extensionW
, NULL
);
2060 iconW
= assoc_query(ASSOCSTR_DEFAULTICON
, extensionW
, NULL
);
2062 contentTypeW
= assoc_query(ASSOCSTR_CONTENTTYPE
, extensionW
, NULL
);
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.
2080 WCHAR
*flattened_mime
= slashes_to_minuses(mimeType
);
2082 WCHAR
*comma
= wcsrchr(iconW
, ',');
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
);
2096 commandW
= assoc_query(ASSOCSTR_COMMAND
, extensionW
, L
"open");
2097 if (commandW
== NULL
)
2098 /* no command => no application is associated */
2101 executableW
= assoc_query(ASSOCSTR_EXECUTABLE
, extensionW
, L
"open");
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
);
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");
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
))
2133 update_association(extensionW
, mimeType
, progIdW
, friendlyAppName
, desktopPath
, openWithIcon
);
2135 heap_free(desktopPath
);
2138 if (hasChanged
&& openWithIcon
) extract_icon(executableW
, 0, openWithIcon
, FALSE
);
2141 heap_free(commandW
);
2142 heap_free(executableW
);
2143 heap_free(openWithIcon
);
2144 heap_free(friendlyDocNameW
);
2146 heap_free(contentTypeW
);
2147 heap_free(mimeType
);
2150 heap_free(extensionW
);
2153 wine_rb_destroy(&mimeProgidTree
, winemenubuilder_rb_destroy
, NULL
);
2154 free_native_mime_types(&nativeMimeTypes
);
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;
2170 WINE_ERR("Link name is null\n");
2174 if( !get_link_location( link
, &csidl
, &link_name
) )
2176 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link
));
2179 if (!in_desktop_dir(csidl
) && !in_startmenu(csidl
))
2181 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2184 WINE_TRACE("Link : %s\n", wine_dbgstr_w(link_name
));
2187 IShellLinkW_GetWorkingDirectory( sl
, szTmp
, MAX_PATH
);
2188 ExpandEnvironmentStringsW(szTmp
, szWorkDir
, MAX_PATH
);
2189 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir
));
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
));
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
) );
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 */
2218 icon_name
= extract_icon( szIconPath
, iIconId
, NULL
, bWait
);
2220 icon_name
= extract_icon( szPath
, iIconId
, NULL
, bWait
);
2222 /* fail - try once again after parent process exit */
2227 WINE_WARN("Unable to extract icon, deferring.\n");
2230 WINE_ERR("failed to extract icon from %s\n",
2231 wine_dbgstr_w( szIconPath
[0] ? szIconPath
: szPath
));
2234 /* check the path */
2237 /* FIXME: Use AppUserModelID if present. */
2238 WCHAR
*p
= PathFindFileNameW(szPath
);
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");
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
);
2261 r
= !write_desktop_entry(NULL
, NULL
, link_name
, szPath
, szArgs
,
2262 szDescription
, szWorkDir
, icon_name
, szWMClass
);
2265 r
= !write_menu_entry(link
, link_name
, link
, NULL
, szDescription
, szWorkDir
, icon_name
, szWMClass
);
2267 ReleaseSemaphore( hsem
, 1, NULL
);
2270 if (hsem
) CloseHandle( hsem
);
2271 heap_free(icon_name
);
2272 heap_free(link_name
);
2275 WINE_ERR("failed to build the menu\n" );
2280 static BOOL
InvokeShellLinkerForURL( IUniformResourceLocatorW
*url
, LPCWSTR link
, BOOL bWait
)
2282 WCHAR
*link_name
, *icon_name
= NULL
;
2284 LPWSTR urlPath
= NULL
;
2289 IPropertySetStorage
*pPropSetStg
;
2290 IPropertyStorage
*pPropStg
;
2293 BOOL has_icon
= FALSE
;
2297 WINE_ERR("Link name is null\n");
2301 if( !get_link_location( link
, &csidl
, &link_name
) )
2303 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link
));
2306 if (!in_desktop_dir(csidl
) && !in_startmenu(csidl
))
2308 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2312 WINE_TRACE("Link : %s\n", wine_dbgstr_w(link_name
));
2314 hr
= url
->lpVtbl
->GetURL(url
, &urlPath
);
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
);
2330 hr
= IPropertySetStorage_Open(pPropSetStg
, &FMTID_Intshcut
, STGM_READ
| STGM_SHARE_EXCLUSIVE
, &pPropStg
);
2333 hr
= IPropertyStorage_ReadMultiple(pPropStg
, 2, ps
, pv
);
2336 if (pv
[0].vt
== VT_LPWSTR
&& pv
[0].pwszVal
&& pv
[0].pwszVal
[0])
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
)
2356 WINE_WARN("Unable to extract icon, deferring.\n");
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");
2370 if (in_desktop_dir(csidl
))
2371 r
= !write_desktop_entry(NULL
, NULL
, link_name
, L
"start.exe", urlPath
, NULL
, NULL
, icon_name
, NULL
);
2373 r
= !write_menu_entry(link
, link_name
, L
"start.exe", urlPath
, NULL
, NULL
, icon_name
, NULL
);
2375 ReleaseSemaphore(hSem
, 1, NULL
);
2380 heap_free(icon_name
);
2381 heap_free(link_name
);
2382 CoTaskMemFree( urlPath
);
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());
2401 procentry
.dwSize
= sizeof(PROCESSENTRY32
);
2402 rc
= Process32First( hsnapshot
, &procentry
);
2405 if (procentry
.th32ProcessID
== ourpid
) break;
2406 rc
= Process32Next( hsnapshot
, &procentry
);
2410 WINE_WARN("Unable to find current process id %ld when listing processes\n", ourpid
);
2414 if ((hprocess
= OpenProcess( SYNCHRONIZE
, FALSE
, procentry
.th32ParentProcessID
)) ==
2417 WINE_WARN("OpenProcess failed pid=%ld, error %ld\n", procentry
.th32ParentProcessID
,
2422 if (MsgWaitForMultipleObjects( 1, &hprocess
, FALSE
, INFINITE
, QS_ALLINPUT
) == WAIT_OBJECT_0
)
2425 WINE_ERR("Unable to wait for parent process, error %ld\n", GetLastError());
2428 if (hprocess
) CloseHandle( hprocess
);
2429 if (hsnapshot
) CloseHandle( hsnapshot
);
2433 static BOOL
Process_Link( LPCWSTR linkname
, BOOL bWait
)
2438 WCHAR fullname
[MAX_PATH
];
2441 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname
), bWait
);
2445 WINE_ERR("link name missing\n");
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");
2456 r
= CoCreateInstance( &CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
2457 &IID_IShellLinkW
, (LPVOID
*) &sl
);
2460 WINE_ERR("No IID_IShellLink\n");
2464 r
= IShellLinkW_QueryInterface( sl
, &IID_IPersistFile
, (LPVOID
*) &pf
);
2467 WINE_ERR("No IID_IPersistFile\n");
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
);
2485 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname
));
2488 IPersistFile_Release( pf
);
2489 IShellLinkW_Release( sl
);
2494 static BOOL
Process_URL( LPCWSTR urlname
, BOOL bWait
)
2496 IUniformResourceLocatorW
*url
;
2499 WCHAR fullname
[MAX_PATH
];
2502 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname
), bWait
);
2506 WINE_ERR("URL name missing\n");
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");
2517 r
= CoCreateInstance( &CLSID_InternetShortcut
, NULL
, CLSCTX_INPROC_SERVER
,
2518 &IID_IUniformResourceLocatorW
, (LPVOID
*) &url
);
2521 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2525 r
= url
->lpVtbl
->QueryInterface( url
, &IID_IPersistFile
, (LPVOID
*) &pf
);
2528 WINE_ERR("No IID_IPersistFile\n");
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
);
2550 static void RefreshFileTypeAssociations(void)
2554 WCHAR
*packages_dir
;
2555 WCHAR
*applications_dir
;
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");
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();
2577 const char *argv
[3];
2579 argv
[0] = "update-mime-database";
2580 argv
[1] = wine_get_unix_file_name(mime_dir
);
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
);
2591 heap_free(mime_dir
);
2592 heap_free(packages_dir
);
2593 heap_free(applications_dir
);
2596 static void cleanup_menus(void)
2600 hkey
= open_menus_reg_key();
2604 LSTATUS lret
= ERROR_SUCCESS
;
2605 for (i
= 0; lret
== ERROR_SUCCESS
; )
2607 WCHAR
*value
= NULL
;
2609 DWORD valueSize
= 4096;
2610 DWORD dataSize
= 4096;
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
)
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
);
2635 else if (lret
!= ERROR_NO_MORE_ITEMS
)
2636 WINE_ERR("error %ld reading registry\n", lret
);
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
];
2655 IStream
*stream
= NULL
;
2656 ICONDIRENTRY
*pIconDirEntries
= NULL
;
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
);
2668 hr
= CoCreateInstance(&CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
2669 &IID_IShellLinkW
, (LPVOID
*)&shellLink
);
2672 WINE_ERR("could not create IShellLinkW, error 0x%08lX\n", hr
);
2676 hr
= IShellLinkW_QueryInterface(shellLink
, &IID_IPersistFile
, (LPVOID
)&persistFile
);
2679 WINE_ERR("could not query IPersistFile, error 0x%08lX\n", hr
);
2683 hr
= IPersistFile_Load(persistFile
, winLnkPath
, STGM_READ
);
2686 WINE_ERR("could not read .lnk, error 0x%08lX\n", hr
);
2690 get_cmdline(shellLink
, szTmp
, MAX_PATH
, szArgs
, INFOTIPSIZE
);
2691 ExpandEnvironmentStringsW(szTmp
, szPath
, MAX_PATH
);
2693 IShellLinkW_GetIconLocation(shellLink
, szTmp
, MAX_PATH
, &iconId
);
2694 ExpandEnvironmentStringsW(szTmp
, szIconPath
, MAX_PATH
);
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
));
2706 hr
= open_icon(szIconPath
, iconId
, FALSE
, &stream
, &pIconDirEntries
, &numEntries
);
2708 hr
= write_native_icon(stream
, pIconDirEntries
, numEntries
, outputPath
);
2712 hr
= open_icon(szPath
, iconId
, FALSE
, &stream
, &pIconDirEntries
, &numEntries
);
2714 hr
= write_native_icon(stream
, pIconDirEntries
, numEntries
, outputPath
);
2718 heap_free(utf8lnkPath
);
2719 heap_free(winLnkPath
);
2720 if (shellLink
!= NULL
)
2721 IShellLinkW_Release(shellLink
);
2722 if (persistFile
!= NULL
)
2723 IPersistFile_Release(persistFile
);
2725 IStream_Release(stream
);
2726 heap_free(pIconDirEntries
);
2729 static WCHAR
*next_token( LPWSTR
*p
)
2731 LPWSTR token
= NULL
, t
= *p
;
2736 while( t
&& !token
)
2744 /* unquote the token */
2746 t
= wcschr( token
, '"' );
2755 t
= wcschr( token
, ' ' );
2765 static BOOL
init_xdg(void)
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
);
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
);
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
);
2793 static BOOL
associations_enabled(void)
2800 if ((hkey
= open_associations_reg_key()))
2803 if (!RegQueryValueExA(hkey
, "Enable", NULL
, NULL
, buf
, &len
))
2804 ret
= IS_OPTION_TRUE(buf
[0]);
2805 RegCloseKey( hkey
);
2811 /***********************************************************************
2815 int PASCAL
wWinMain (HINSTANCE hInstance
, HINSTANCE prev
, LPWSTR cmdline
, int show
)
2817 LPWSTR token
= NULL
, p
;
2826 hr
= CoInitialize(NULL
);
2829 WINE_ERR("could not initialize COM, error 0x%08lX\n", hr
);
2833 for( p
= cmdline
; p
&& *p
; )
2835 token
= next_token( &p
);
2838 if( !wcscmp( token
, L
"-a" ) )
2840 if (associations_enabled())
2841 RefreshFileTypeAssociations();
2844 if( !wcscmp( token
, L
"-r" ) )
2849 if( !wcscmp( token
, L
"-w" ) )
2851 else if ( !wcscmp( token
, L
"-u" ) )
2853 else if ( !wcscmp( token
, L
"-t" ) )
2855 WCHAR
*lnkFile
= next_token( &p
);
2858 WCHAR
*outputFile
= next_token( &p
);
2860 thumbnail_lnk(lnkFile
, outputFile
);
2863 else if( token
[0] == '-' )
2865 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token
) );
2872 bRet
= Process_URL( token
, bWait
);
2874 bRet
= Process_Link( token
, bWait
);
2877 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token
) );