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).
66 #include "wine/port.h"
81 #define NONAMELESSUNION
94 #include "wine/unicode.h"
95 #include "wine/debug.h"
96 #include "wine/library.h"
97 #include "wine/list.h"
98 #include "wine/rbtree.h"
100 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder
);
102 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
103 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
104 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
105 (csidl)==CSIDL_COMMON_STARTMENU)
107 /* link file formats */
109 #include "pshpack1.h"
128 GRPICONDIRENTRY idEntries
[1];
167 #define NE_RSCTYPE_ICON 0x8003
168 #define NE_RSCTYPE_GROUP_ICON 0x800e
186 struct rb_string_entry
189 struct wine_rb_entry entry
;
192 DEFINE_GUID(CLSID_WICIcnsEncoder
, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
194 static char *xdg_config_dir
;
195 static char *xdg_data_dir
;
196 static char *xdg_desktop_dir
;
199 /* Utility routines */
200 static unsigned short crc16(const char* string
)
202 unsigned short crc
= 0;
205 for (i
= 0; string
[i
] != 0; i
++)
208 for (j
= 0; j
< 8; c
>>= 1, j
++)
210 xor_poly
= (c
^ crc
) & 1;
219 static char *strdupA( const char *str
)
223 if (!str
) return NULL
;
224 if ((ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 ))) strcpy( ret
, str
);
228 static char* heap_printf(const char *format
, ...)
237 buffer
= HeapAlloc(GetProcessHeap(), 0, size
);
240 va_start(args
, format
);
241 n
= vsnprintf(buffer
, size
, format
, args
);
249 HeapFree(GetProcessHeap(), 0, buffer
);
252 if (!buffer
) return NULL
;
253 ret
= HeapReAlloc(GetProcessHeap(), 0, buffer
, strlen(buffer
) + 1 );
254 if (!ret
) ret
= buffer
;
258 static int winemenubuilder_rb_string_compare(const void *key
, const struct wine_rb_entry
*entry
)
260 const struct rb_string_entry
*t
= WINE_RB_ENTRY_VALUE(entry
, const struct rb_string_entry
, entry
);
262 return strcmp((char*)key
, t
->string
);
265 static void winemenubuilder_rb_destroy(struct wine_rb_entry
*entry
, void *context
)
267 struct rb_string_entry
*t
= WINE_RB_ENTRY_VALUE(entry
, struct rb_string_entry
, entry
);
268 HeapFree(GetProcessHeap(), 0, t
->string
);
269 HeapFree(GetProcessHeap(), 0, t
);
272 static void write_xml_text(FILE *file
, const char *text
)
275 for (i
= 0; text
[i
]; i
++)
278 fputs("&", file
);
279 else if (text
[i
] == '<')
281 else if (text
[i
] == '>')
283 else if (text
[i
] == '\'')
284 fputs("'", file
);
285 else if (text
[i
] == '"')
286 fputs(""", file
);
288 fputc(text
[i
], file
);
292 static BOOL
create_directories(char *directory
)
297 for (i
= 0; directory
[i
]; i
++)
299 if (i
> 0 && directory
[i
] == '/')
302 mkdir(directory
, 0777);
306 if (mkdir(directory
, 0777) && errno
!= EEXIST
)
312 static char* wchars_to_utf8_chars(LPCWSTR string
)
315 INT size
= WideCharToMultiByte(CP_UTF8
, 0, string
, -1, NULL
, 0, NULL
, NULL
);
316 ret
= HeapAlloc(GetProcessHeap(), 0, size
);
318 WideCharToMultiByte(CP_UTF8
, 0, string
, -1, ret
, size
, NULL
, NULL
);
322 static char* wchars_to_unix_chars(LPCWSTR string
)
325 INT size
= WideCharToMultiByte(CP_UNIXCP
, 0, string
, -1, NULL
, 0, NULL
, NULL
);
326 ret
= HeapAlloc(GetProcessHeap(), 0, size
);
328 WideCharToMultiByte(CP_UNIXCP
, 0, string
, -1, ret
, size
, NULL
, NULL
);
332 static WCHAR
* utf8_chars_to_wchars(LPCSTR string
)
335 INT size
= MultiByteToWideChar(CP_UTF8
, 0, string
, -1, NULL
, 0);
336 ret
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
338 MultiByteToWideChar(CP_UTF8
, 0, string
, -1, ret
, size
);
342 /* Icon extraction routines
344 * FIXME: should use PrivateExtractIcons and friends
345 * FIXME: should not use stdio
348 static HRESULT
convert_to_native_icon(IStream
*icoFile
, int *indices
, int numIndices
,
349 const CLSID
*outputFormat
, const char *outputFileName
, LPCWSTR commentW
)
351 WCHAR
*dosOutputFileName
= NULL
;
352 IWICImagingFactory
*factory
= NULL
;
353 IWICBitmapDecoder
*decoder
= NULL
;
354 IWICBitmapEncoder
*encoder
= NULL
;
355 IWICBitmapScaler
*scaler
= NULL
;
356 IStream
*outputFile
= NULL
;
360 dosOutputFileName
= wine_get_dos_file_name(outputFileName
);
361 if (dosOutputFileName
== NULL
)
363 WINE_ERR("error converting %s to DOS file name\n", outputFileName
);
366 hr
= CoCreateInstance(&CLSID_WICImagingFactory
, NULL
, CLSCTX_INPROC_SERVER
,
367 &IID_IWICImagingFactory
, (void**)&factory
);
370 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr
);
373 hr
= IWICImagingFactory_CreateDecoderFromStream(factory
, icoFile
, NULL
,
374 WICDecodeMetadataCacheOnDemand
, &decoder
);
377 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr
);
380 if (IsEqualCLSID(outputFormat
,&CLSID_WICIcnsEncoder
))
382 hr
= IWICImagingFactory_CreateBitmapScaler(factory
, &scaler
);
385 WINE_WARN("error 0x%08X creating IWICBitmapScaler\n", hr
);
388 hr
= CoCreateInstance(outputFormat
, NULL
, CLSCTX_INPROC_SERVER
,
389 &IID_IWICBitmapEncoder
, (void**)&encoder
);
392 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr
);
395 hr
= SHCreateStreamOnFileW(dosOutputFileName
, STGM_CREATE
| STGM_WRITE
, &outputFile
);
398 WINE_ERR("error 0x%08X creating output file %s\n", hr
, wine_dbgstr_w(dosOutputFileName
));
401 hr
= IWICBitmapEncoder_Initialize(encoder
, outputFile
, GENERIC_WRITE
);
404 WINE_ERR("error 0x%08X initializing encoder\n", hr
);
408 for (i
= 0; i
< numIndices
; i
++)
410 IWICBitmapFrameDecode
*sourceFrame
= NULL
;
411 IWICBitmapSource
*sourceBitmap
= NULL
;
412 IWICBitmapFrameEncode
*dstFrame
= NULL
;
413 IPropertyBag2
*options
= NULL
;
416 hr
= IWICBitmapDecoder_GetFrame(decoder
, indices
[i
], &sourceFrame
);
419 WINE_ERR("error 0x%08X getting frame %d\n", hr
, indices
[i
]);
422 hr
= WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA
, (IWICBitmapSource
*)sourceFrame
, &sourceBitmap
);
425 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr
);
430 IWICBitmapSource_GetSize(sourceBitmap
, &width
, &height
);
431 if (width
== 64) /* Classic Mode */
433 hr
= IWICBitmapScaler_Initialize( scaler
, sourceBitmap
, 128, 128,
434 WICBitmapInterpolationModeNearestNeighbor
);
436 WINE_ERR("error 0x%08X scaling bitmap\n", hr
);
439 IWICBitmapSource_Release(sourceBitmap
);
440 IWICBitmapScaler_QueryInterface(scaler
, &IID_IWICBitmapSource
, (LPVOID
)&sourceBitmap
);
444 hr
= IWICBitmapEncoder_CreateNewFrame(encoder
, &dstFrame
, &options
);
447 WINE_ERR("error 0x%08X creating encoder frame\n", hr
);
450 hr
= IWICBitmapFrameEncode_Initialize(dstFrame
, options
);
453 WINE_ERR("error 0x%08X initializing encoder frame\n", hr
);
456 hr
= IWICBitmapSource_GetSize(sourceBitmap
, &width
, &height
);
459 WINE_ERR("error 0x%08X getting source bitmap size\n", hr
);
462 hr
= IWICBitmapFrameEncode_SetSize(dstFrame
, width
, height
);
465 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr
);
468 hr
= IWICBitmapFrameEncode_SetResolution(dstFrame
, 96, 96);
471 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr
);
474 hr
= IWICBitmapFrameEncode_WriteSource(dstFrame
, sourceBitmap
, NULL
);
477 WINE_ERR("error 0x%08X copying bitmaps\n", hr
);
480 hr
= IWICBitmapFrameEncode_Commit(dstFrame
);
483 WINE_ERR("error 0x%08X committing frame\n", hr
);
488 IWICBitmapFrameDecode_Release(sourceFrame
);
490 IWICBitmapSource_Release(sourceBitmap
);
492 IWICBitmapFrameEncode_Release(dstFrame
);
494 IPropertyBag2_Release(options
);
497 hr
= IWICBitmapEncoder_Commit(encoder
);
500 WINE_ERR("error 0x%08X committing encoder\n", hr
);
505 HeapFree(GetProcessHeap(), 0, dosOutputFileName
);
507 IWICImagingFactory_Release(factory
);
509 IWICBitmapDecoder_Release(decoder
);
511 IWICBitmapScaler_Release(scaler
);
513 IWICBitmapEncoder_Release(encoder
);
515 IStream_Release(outputFile
);
522 NE_TYPEINFO
*iconResources
;
523 WORD alignmentShiftCount
;
526 static int populate_module16_icons(struct IconData16
*iconData16
, GRPICONDIR
*grpIconDir
, ICONDIRENTRY
*iconDirEntries
, BYTE
*icons
, SIZE_T
*iconOffset
)
529 int validEntries
= 0;
531 for (i
= 0; i
< grpIconDir
->idCount
; i
++)
533 BYTE
*iconPtr
= (BYTE
*)iconData16
->iconResources
;
534 NE_NAMEINFO
*matchingIcon
= NULL
;
535 iconPtr
+= sizeof(NE_TYPEINFO
);
536 for (j
= 0; j
< iconData16
->iconResources
->count
; j
++)
538 NE_NAMEINFO
*iconInfo
= (NE_NAMEINFO
*)iconPtr
;
539 if ((((BYTE
*)iconPtr
) + sizeof(NE_NAMEINFO
)) > (iconData16
->fileBytes
+ iconData16
->fileSize
))
541 WINE_WARN("file too small for icon NE_NAMEINFO\n");
544 if (iconInfo
->id
== (0x8000 | grpIconDir
->idEntries
[i
].nID
))
546 matchingIcon
= iconInfo
;
549 iconPtr
+= sizeof(NE_NAMEINFO
);
552 if (matchingIcon
== NULL
)
554 if (((matchingIcon
->offset
<< iconData16
->alignmentShiftCount
) + grpIconDir
->idEntries
[i
].dwBytesInRes
) > iconData16
->fileSize
)
556 WINE_WARN("file too small for icon contents\n");
560 iconDirEntries
[validEntries
].bWidth
= grpIconDir
->idEntries
[i
].bWidth
;
561 iconDirEntries
[validEntries
].bHeight
= grpIconDir
->idEntries
[i
].bHeight
;
562 iconDirEntries
[validEntries
].bColorCount
= grpIconDir
->idEntries
[i
].bColorCount
;
563 iconDirEntries
[validEntries
].bReserved
= grpIconDir
->idEntries
[i
].bReserved
;
564 iconDirEntries
[validEntries
].wPlanes
= grpIconDir
->idEntries
[i
].wPlanes
;
565 iconDirEntries
[validEntries
].wBitCount
= grpIconDir
->idEntries
[i
].wBitCount
;
566 iconDirEntries
[validEntries
].dwBytesInRes
= grpIconDir
->idEntries
[i
].dwBytesInRes
;
567 iconDirEntries
[validEntries
].dwImageOffset
= *iconOffset
;
569 memcpy(&icons
[*iconOffset
], &iconData16
->fileBytes
[matchingIcon
->offset
<< iconData16
->alignmentShiftCount
], grpIconDir
->idEntries
[i
].dwBytesInRes
);
570 *iconOffset
+= grpIconDir
->idEntries
[i
].dwBytesInRes
;
575 static int populate_module_icons(HMODULE hModule
, GRPICONDIR
*grpIconDir
, ICONDIRENTRY
*iconDirEntries
, BYTE
*icons
, SIZE_T
*iconOffset
)
578 int validEntries
= 0;
580 for (i
= 0; i
< grpIconDir
->idCount
; i
++)
583 LPCWSTR lpName
= MAKEINTRESOURCEW(grpIconDir
->idEntries
[i
].nID
);
584 if ((hResInfo
= FindResourceW(hModule
, lpName
, (LPCWSTR
)RT_ICON
)))
587 if ((hResData
= LoadResource(hModule
, hResInfo
)))
590 DWORD size
= min( grpIconDir
->idEntries
[i
].dwBytesInRes
, ((IMAGE_RESOURCE_DATA_ENTRY
*)hResInfo
)->Size
);
591 if ((pIcon
= LockResource(hResData
)))
593 iconDirEntries
[validEntries
].bWidth
= grpIconDir
->idEntries
[i
].bWidth
;
594 iconDirEntries
[validEntries
].bHeight
= grpIconDir
->idEntries
[i
].bHeight
;
595 iconDirEntries
[validEntries
].bColorCount
= grpIconDir
->idEntries
[i
].bColorCount
;
596 iconDirEntries
[validEntries
].bReserved
= grpIconDir
->idEntries
[i
].bReserved
;
597 iconDirEntries
[validEntries
].wPlanes
= grpIconDir
->idEntries
[i
].wPlanes
;
598 iconDirEntries
[validEntries
].wBitCount
= grpIconDir
->idEntries
[i
].wBitCount
;
599 iconDirEntries
[validEntries
].dwBytesInRes
= size
;
600 iconDirEntries
[validEntries
].dwImageOffset
= *iconOffset
;
602 memcpy(&icons
[*iconOffset
], pIcon
, size
);
605 FreeResource(hResData
);
612 static IStream
*add_module_icons_to_stream(struct IconData16
*iconData16
, HMODULE hModule
, GRPICONDIR
*grpIconDir
)
615 SIZE_T iconsSize
= 0;
617 ICONDIRENTRY
*iconDirEntries
= NULL
;
618 IStream
*stream
= NULL
;
623 int validEntries
= 0;
626 for (i
= 0; i
< grpIconDir
->idCount
; i
++)
627 iconsSize
+= grpIconDir
->idEntries
[i
].dwBytesInRes
;
628 icons
= HeapAlloc(GetProcessHeap(), 0, iconsSize
);
631 WINE_ERR("out of memory allocating icon\n");
635 iconDirEntries
= HeapAlloc(GetProcessHeap(), 0, grpIconDir
->idCount
*sizeof(ICONDIRENTRY
));
636 if (iconDirEntries
== NULL
)
638 WINE_ERR("out of memory allocating icon dir entries\n");
642 hr
= CreateStreamOnHGlobal(NULL
, TRUE
, &stream
);
645 WINE_ERR("error creating icon stream\n");
651 validEntries
= populate_module16_icons(iconData16
, grpIconDir
, iconDirEntries
, icons
, &iconOffset
);
653 validEntries
= populate_module_icons(hModule
, grpIconDir
, iconDirEntries
, icons
, &iconOffset
);
655 if (validEntries
== 0)
657 WINE_ERR("no valid icon entries\n");
661 iconDir
.idReserved
= 0;
663 iconDir
.idCount
= validEntries
;
664 hr
= IStream_Write(stream
, &iconDir
, sizeof(iconDir
), &bytesWritten
);
665 if (FAILED(hr
) || bytesWritten
!= sizeof(iconDir
))
667 WINE_ERR("error 0x%08X writing icon stream\n", hr
);
670 for (i
= 0; i
< validEntries
; i
++)
671 iconDirEntries
[i
].dwImageOffset
+= sizeof(ICONDIR
) + validEntries
*sizeof(ICONDIRENTRY
);
672 hr
= IStream_Write(stream
, iconDirEntries
, validEntries
*sizeof(ICONDIRENTRY
), &bytesWritten
);
673 if (FAILED(hr
) || bytesWritten
!= validEntries
*sizeof(ICONDIRENTRY
))
675 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr
);
678 hr
= IStream_Write(stream
, icons
, iconOffset
, &bytesWritten
);
679 if (FAILED(hr
) || bytesWritten
!= iconOffset
)
681 WINE_ERR("error 0x%08X writing icon images to stream\n", hr
);
685 hr
= IStream_Seek(stream
, zero
, STREAM_SEEK_SET
, NULL
);
688 HeapFree(GetProcessHeap(), 0, icons
);
689 HeapFree(GetProcessHeap(), 0, iconDirEntries
);
690 if (FAILED(hr
) && stream
!= NULL
)
692 IStream_Release(stream
);
698 static HRESULT
open_module16_icon(LPCWSTR szFileName
, int nIndex
, IStream
**ppStream
)
700 HANDLE hFile
= INVALID_HANDLE_VALUE
;
701 HANDLE hFileMapping
= NULL
;
703 BYTE
*fileBytes
= NULL
;
704 IMAGE_DOS_HEADER
*dosHeader
;
705 IMAGE_OS2_HEADER
*neHeader
;
707 NE_TYPEINFO
*iconGroupResources
;
708 NE_TYPEINFO
*iconResources
;
709 NE_NAMEINFO
*iconDirPtr
;
711 WORD alignmentShiftCount
;
712 struct IconData16 iconData16
;
715 hFile
= CreateFileW(szFileName
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
,
716 OPEN_EXISTING
, FILE_FLAG_RANDOM_ACCESS
, NULL
);
717 if (hFile
== INVALID_HANDLE_VALUE
)
719 WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName
), GetLastError());
723 hFileMapping
= CreateFileMappingW(hFile
, NULL
, PAGE_READONLY
| SEC_COMMIT
, 0, 0, NULL
);
724 if (hFileMapping
== NULL
)
726 WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
730 fileSize
= GetFileSize(hFile
, NULL
);
732 fileBytes
= MapViewOfFile(hFileMapping
, FILE_MAP_READ
, 0, 0, 0);
733 if (fileBytes
== NULL
)
735 WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
739 dosHeader
= (IMAGE_DOS_HEADER
*)fileBytes
;
740 if (sizeof(IMAGE_DOS_HEADER
) >= fileSize
|| dosHeader
->e_magic
!= IMAGE_DOS_SIGNATURE
)
742 WINE_WARN("file too small for MZ header\n");
746 neHeader
= (IMAGE_OS2_HEADER
*)(fileBytes
+ dosHeader
->e_lfanew
);
747 if ((((BYTE
*)neHeader
) + sizeof(IMAGE_OS2_HEADER
)) > (fileBytes
+ fileSize
) ||
748 neHeader
->ne_magic
!= IMAGE_OS2_SIGNATURE
)
750 WINE_WARN("file too small for NE header\n");
754 rsrcTab
= ((BYTE
*)neHeader
) + neHeader
->ne_rsrctab
;
755 if ((rsrcTab
+ 2) > (fileBytes
+ fileSize
))
757 WINE_WARN("file too small for resource table\n");
761 alignmentShiftCount
= *(WORD
*)rsrcTab
;
763 iconGroupResources
= NULL
;
764 iconResources
= NULL
;
767 NE_TYPEINFO
*neTypeInfo
= (NE_TYPEINFO
*)rsrcTab
;
768 if ((rsrcTab
+ sizeof(NE_TYPEINFO
)) > (fileBytes
+ fileSize
))
770 WINE_WARN("file too small for resource table\n");
773 if (neTypeInfo
->type_id
== 0)
775 else if (neTypeInfo
->type_id
== NE_RSCTYPE_GROUP_ICON
)
776 iconGroupResources
= neTypeInfo
;
777 else if (neTypeInfo
->type_id
== NE_RSCTYPE_ICON
)
778 iconResources
= neTypeInfo
;
779 rsrcTab
+= sizeof(NE_TYPEINFO
) + neTypeInfo
->count
*sizeof(NE_NAMEINFO
);
781 if (iconGroupResources
== NULL
)
783 WINE_WARN("no group icon resource type found\n");
786 if (iconResources
== NULL
)
788 WINE_WARN("no icon resource type found\n");
792 if (nIndex
>= iconGroupResources
->count
)
794 WINE_WARN("icon index out of range\n");
798 iconDirPtr
= (NE_NAMEINFO
*)(((BYTE
*)iconGroupResources
) + sizeof(NE_TYPEINFO
) + nIndex
*sizeof(NE_NAMEINFO
));
799 if ((((BYTE
*)iconDirPtr
) + sizeof(NE_NAMEINFO
)) > (fileBytes
+ fileSize
))
801 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
804 iconDir
= (GRPICONDIR
*)(fileBytes
+ (iconDirPtr
->offset
<< alignmentShiftCount
));
805 if ((((BYTE
*)iconDir
) + sizeof(GRPICONDIR
) + iconDir
->idCount
*sizeof(GRPICONDIRENTRY
)) > (fileBytes
+ fileSize
))
807 WINE_WARN("file too small for GRPICONDIR\n");
811 iconData16
.fileBytes
= fileBytes
;
812 iconData16
.fileSize
= fileSize
;
813 iconData16
.iconResources
= iconResources
;
814 iconData16
.alignmentShiftCount
= alignmentShiftCount
;
815 *ppStream
= add_module_icons_to_stream(&iconData16
, NULL
, iconDir
);
820 if (hFile
!= INVALID_HANDLE_VALUE
)
822 if (hFileMapping
!= NULL
)
823 CloseHandle(hFileMapping
);
824 if (fileBytes
!= NULL
)
825 UnmapViewOfFile(fileBytes
);
829 static BOOL CALLBACK
EnumResNameProc(HMODULE hModule
, LPCWSTR lpszType
, LPWSTR lpszName
, LONG_PTR lParam
)
831 ENUMRESSTRUCT
*sEnumRes
= (ENUMRESSTRUCT
*) lParam
;
833 if (!sEnumRes
->nIndex
--)
835 *sEnumRes
->pResInfo
= FindResourceW(hModule
, lpszName
, (LPCWSTR
)RT_GROUP_ICON
);
842 static HRESULT
open_module_icon(LPCWSTR szFileName
, int nIndex
, IStream
**ppStream
)
847 GRPICONDIR
*pIconDir
;
848 ENUMRESSTRUCT sEnumRes
;
851 hModule
= LoadLibraryExW(szFileName
, 0, LOAD_LIBRARY_AS_DATAFILE
);
854 if (GetLastError() == ERROR_BAD_EXE_FORMAT
)
855 return open_module16_icon(szFileName
, nIndex
, ppStream
);
858 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
859 wine_dbgstr_w(szFileName
), GetLastError());
860 return HRESULT_FROM_WIN32(GetLastError());
866 hResInfo
= FindResourceW(hModule
, MAKEINTRESOURCEW(-nIndex
), (LPCWSTR
)RT_GROUP_ICON
);
867 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
868 wine_dbgstr_w(szFileName
), hResInfo
, GetLastError());
873 sEnumRes
.pResInfo
= &hResInfo
;
874 sEnumRes
.nIndex
= nIndex
;
875 if (!EnumResourceNamesW(hModule
, (LPCWSTR
)RT_GROUP_ICON
,
876 EnumResNameProc
, (LONG_PTR
)&sEnumRes
) &&
877 sEnumRes
.nIndex
!= -1)
879 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
885 if ((hResData
= LoadResource(hModule
, hResInfo
)))
887 if ((pIconDir
= LockResource(hResData
)))
889 *ppStream
= add_module_icons_to_stream(0, hModule
, pIconDir
);
894 FreeResource(hResData
);
899 WINE_WARN("found no icon\n");
900 FreeLibrary(hModule
);
901 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND
);
904 FreeLibrary(hModule
);
908 static HRESULT
read_ico_direntries(IStream
*icoStream
, ICONDIRENTRY
**ppIconDirEntries
, int *numEntries
)
914 *ppIconDirEntries
= NULL
;
916 hr
= IStream_Read(icoStream
, &iconDir
, sizeof(ICONDIR
), &bytesRead
);
917 if (FAILED(hr
) || bytesRead
!= sizeof(ICONDIR
) ||
918 (iconDir
.idReserved
!= 0) || (iconDir
.idType
!= 1))
920 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr
, bytesRead
);
924 *numEntries
= iconDir
.idCount
;
926 if ((*ppIconDirEntries
= HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY
)*iconDir
.idCount
)) == NULL
)
931 hr
= IStream_Read(icoStream
, *ppIconDirEntries
, sizeof(ICONDIRENTRY
)*iconDir
.idCount
, &bytesRead
);
932 if (FAILED(hr
) || bytesRead
!= sizeof(ICONDIRENTRY
)*iconDir
.idCount
)
934 if (SUCCEEDED(hr
)) hr
= E_FAIL
;
940 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries
);
944 static HRESULT
validate_ico(IStream
**ppStream
, ICONDIRENTRY
**ppIconDirEntries
, int *numEntries
)
948 hr
= read_ico_direntries(*ppStream
, ppIconDirEntries
, numEntries
);
953 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries
);
954 *ppIconDirEntries
= NULL
;
956 IStream_Release(*ppStream
);
961 static HRESULT
write_native_icon(IStream
*iconStream
, ICONDIRENTRY
*pIconDirEntry
,
962 int numEntries
, const char *icon_name
, LPCWSTR szFileName
)
964 int nMax
= 0, nMaxBits
= 0;
967 LARGE_INTEGER position
;
970 for (i
= 0; i
< numEntries
; i
++)
972 WINE_TRACE("[%d]: %d x %d @ %d\n", i
, pIconDirEntry
[i
].bWidth
, pIconDirEntry
[i
].bHeight
, pIconDirEntry
[i
].wBitCount
);
973 if (pIconDirEntry
[i
].wBitCount
>= nMaxBits
&&
974 (pIconDirEntry
[i
].bHeight
* pIconDirEntry
[i
].bWidth
) >= nMax
)
977 nMax
= pIconDirEntry
[i
].bHeight
* pIconDirEntry
[i
].bWidth
;
978 nMaxBits
= pIconDirEntry
[i
].wBitCount
;
981 WINE_TRACE("Selected: %d\n", nIndex
);
983 position
.QuadPart
= 0;
984 hr
= IStream_Seek(iconStream
, position
, STREAM_SEEK_SET
, NULL
);
985 if (FAILED(hr
)) return hr
;
986 return convert_to_native_icon(iconStream
, &nIndex
, 1, &CLSID_WICPngEncoder
, icon_name
, szFileName
);
989 static WCHAR
* assoc_query(ASSOCSTR assocStr
, LPCWSTR name
, LPCWSTR extra
)
994 hr
= AssocQueryStringW(0, assocStr
, name
, extra
, NULL
, &size
);
997 value
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
1000 hr
= AssocQueryStringW(0, assocStr
, name
, extra
, value
, &size
);
1003 HeapFree(GetProcessHeap(), 0, value
);
1011 static HRESULT
open_file_type_icon(LPCWSTR szFileName
, IStream
**ppStream
)
1013 static const WCHAR openW
[] = {'o','p','e','n',0};
1017 WCHAR
*executable
= NULL
;
1019 HRESULT hr
= HRESULT_FROM_WIN32(ERROR_NOT_FOUND
);
1021 extension
= strrchrW(szFileName
, '.');
1022 if (extension
== NULL
)
1025 icon
= assoc_query(ASSOCSTR_DEFAULTICON
, extension
, NULL
);
1028 comma
= strrchrW(icon
, ',');
1032 index
= atoiW(comma
+ 1);
1034 hr
= open_module_icon(icon
, index
, ppStream
);
1038 executable
= assoc_query(ASSOCSTR_EXECUTABLE
, extension
, openW
);
1040 hr
= open_module_icon(executable
, 0, ppStream
);
1044 HeapFree(GetProcessHeap(), 0, icon
);
1045 HeapFree(GetProcessHeap(), 0, executable
);
1049 static HRESULT
open_default_icon(IStream
**ppStream
)
1051 static const WCHAR user32W
[] = {'u','s','e','r','3','2',0};
1053 return open_module_icon(user32W
, -(INT_PTR
)IDI_WINLOGO
, ppStream
);
1056 static HRESULT
open_icon(LPCWSTR filename
, int index
, BOOL bWait
, IStream
**ppStream
, ICONDIRENTRY
**ppIconDirEntries
, int *numEntries
)
1060 hr
= open_module_icon(filename
, index
, ppStream
);
1063 if(bWait
&& hr
== HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND
))
1065 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1066 wine_dbgstr_w(filename
));
1071 /* This might be a raw .ico file */
1072 hr
= SHCreateStreamOnFileW(filename
, STGM_READ
, ppStream
);
1076 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1080 hr
= open_file_type_icon(filename
, ppStream
);
1082 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1084 if (FAILED(hr
) && !bWait
)
1086 hr
= open_default_icon(ppStream
);
1088 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1093 static char* compute_native_identifier(int exeIndex
, LPCWSTR icoPathW
)
1095 char* nativeIdentifier
;
1098 char *basename
, *ext
;
1100 icoPathA
= wchars_to_utf8_chars(icoPathW
);
1101 if (icoPathA
== NULL
)
1104 crc
= crc16(icoPathA
);
1105 basename
= strrchr(icoPathA
, '\\');
1106 if (basename
== NULL
)
1107 basename
= icoPathA
;
1113 ext
= strrchr(basename
, '.');
1117 nativeIdentifier
= heap_printf("%04X_%s.%d", crc
, basename
, exeIndex
);
1118 HeapFree(GetProcessHeap(), 0, icoPathA
);
1119 return nativeIdentifier
;
1123 #define ICNS_SLOTS 6
1125 static inline int size_to_slot(int size
)
1132 case 64: return -2; /* Classic Mode */
1141 #define CLASSIC_SLOT 3
1143 static HRESULT
platform_write_icon(IStream
*icoStream
, ICONDIRENTRY
*iconDirEntries
,
1144 int numEntries
, int exeIndex
, LPCWSTR icoPathW
,
1145 const char *destFilename
, char **nativeIdentifier
)
1152 int indexes
[ICNS_SLOTS
];
1155 char *icnsPath
= NULL
;
1159 for (i
= 0; i
< ICNS_SLOTS
; i
++)
1162 best
[i
].maxBits
= 0;
1164 for (i
= 0; i
< numEntries
; i
++)
1167 int width
= iconDirEntries
[i
].bWidth
? iconDirEntries
[i
].bWidth
: 256;
1168 int height
= iconDirEntries
[i
].bHeight
? iconDirEntries
[i
].bHeight
: 256;
1169 BOOL scaled
= FALSE
;
1171 WINE_TRACE("[%d]: %d x %d @ %d\n", i
, width
, height
, iconDirEntries
[i
].wBitCount
);
1172 if (height
!= width
)
1174 slot
= size_to_slot(width
);
1178 slot
= CLASSIC_SLOT
;
1182 if (scaled
&& best
[slot
].maxBits
&& !best
[slot
].scaled
)
1183 continue; /* don't replace unscaled with scaled */
1184 if (iconDirEntries
[i
].wBitCount
>= best
[slot
].maxBits
|| (!scaled
&& best
[slot
].scaled
))
1186 best
[slot
].index
= i
;
1187 best
[slot
].maxBits
= iconDirEntries
[i
].wBitCount
;
1188 best
[slot
].scaled
= scaled
;
1191 /* remove the scaled icon if a larger unscaled icon exists */
1192 if (best
[CLASSIC_SLOT
].scaled
)
1194 for (i
= CLASSIC_SLOT
+1; i
< ICNS_SLOTS
; i
++)
1195 if (best
[i
].index
>= 0 && !best
[i
].scaled
)
1197 best
[CLASSIC_SLOT
].index
= -1;
1203 for (i
= 0; i
< ICNS_SLOTS
; i
++)
1205 if (best
[i
].index
>= 0)
1207 indexes
[numEntries
] = best
[i
].index
;
1213 *nativeIdentifier
= heap_printf("%s", destFilename
);
1215 *nativeIdentifier
= compute_native_identifier(exeIndex
, icoPathW
);
1216 if (*nativeIdentifier
== NULL
)
1221 if (!(tmpdir
= getenv("TMPDIR"))) tmpdir
= "/tmp";
1222 icnsPath
= heap_printf("%s/%s.icns", tmpdir
, *nativeIdentifier
);
1223 if (icnsPath
== NULL
)
1226 WINE_WARN("out of memory creating ICNS path\n");
1230 hr
= IStream_Seek(icoStream
, zero
, STREAM_SEEK_SET
, NULL
);
1233 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr
);
1236 hr
= convert_to_native_icon(icoStream
, indexes
, numEntries
, &CLSID_WICIcnsEncoder
,
1237 icnsPath
, icoPathW
);
1240 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
1241 wine_dbgstr_w(icoPathW
), wine_dbgstr_a(icnsPath
), hr
);
1246 HeapFree(GetProcessHeap(), 0, icnsPath
);
1250 static void refresh_icon_cache(const char *iconsDir
)
1252 /* The icon theme spec only requires the mtime on the "toplevel"
1253 * directory (whatever that is) to be changed for a refresh,
1254 * but on GNOME you have to create a file in that directory
1255 * instead. Creating a file also works on KDE, Xfce and LXDE.
1257 char *filename
= heap_printf("%s/.wine-refresh-XXXXXX", iconsDir
);
1258 if (filename
!= NULL
)
1260 int fd
= mkstemps(filename
, 0);
1266 HeapFree(GetProcessHeap(), 0, filename
);
1270 static HRESULT
platform_write_icon(IStream
*icoStream
, ICONDIRENTRY
*iconDirEntries
,
1271 int numEntries
, int exeIndex
, LPCWSTR icoPathW
,
1272 const char *destFilename
, char **nativeIdentifier
)
1275 char *iconsDir
= NULL
;
1280 *nativeIdentifier
= heap_printf("%s", destFilename
);
1282 *nativeIdentifier
= compute_native_identifier(exeIndex
, icoPathW
);
1283 if (*nativeIdentifier
== NULL
)
1288 iconsDir
= heap_printf("%s/icons/hicolor", xdg_data_dir
);
1289 if (iconsDir
== NULL
)
1295 for (i
= 0; i
< numEntries
; i
++)
1299 BOOLEAN duplicate
= FALSE
;
1301 char *iconDir
= NULL
;
1302 char *pngPath
= NULL
;
1304 WINE_TRACE("[%d]: %d x %d @ %d\n", i
, iconDirEntries
[i
].bWidth
,
1305 iconDirEntries
[i
].bHeight
, iconDirEntries
[i
].wBitCount
);
1307 for (j
= 0; j
< i
; j
++)
1309 if (iconDirEntries
[j
].bWidth
== iconDirEntries
[i
].bWidth
&&
1310 iconDirEntries
[j
].bHeight
== iconDirEntries
[i
].bHeight
)
1318 for (j
= i
+ 1; j
< numEntries
; j
++)
1320 if (iconDirEntries
[j
].bWidth
== iconDirEntries
[i
].bWidth
&&
1321 iconDirEntries
[j
].bHeight
== iconDirEntries
[i
].bHeight
&&
1322 iconDirEntries
[j
].wBitCount
>= iconDirEntries
[bestIndex
].wBitCount
)
1327 WINE_TRACE("Selected: %d\n", bestIndex
);
1329 w
= iconDirEntries
[bestIndex
].bWidth
? iconDirEntries
[bestIndex
].bWidth
: 256;
1330 h
= iconDirEntries
[bestIndex
].bHeight
? iconDirEntries
[bestIndex
].bHeight
: 256;
1331 iconDir
= heap_printf("%s/%dx%d/apps", iconsDir
, w
, h
);
1332 if (iconDir
== NULL
)
1337 create_directories(iconDir
);
1338 pngPath
= heap_printf("%s/%s.png", iconDir
, *nativeIdentifier
);
1339 if (pngPath
== NULL
)
1345 hr
= IStream_Seek(icoStream
, zero
, STREAM_SEEK_SET
, NULL
);
1348 hr
= convert_to_native_icon(icoStream
, &bestIndex
, 1, &CLSID_WICPngEncoder
,
1352 HeapFree(GetProcessHeap(), 0, iconDir
);
1353 HeapFree(GetProcessHeap(), 0, pngPath
);
1355 refresh_icon_cache(iconsDir
);
1358 HeapFree(GetProcessHeap(), 0, iconsDir
);
1361 #endif /* defined(__APPLE__) */
1363 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1364 static char *extract_icon(LPCWSTR icoPathW
, int index
, const char *destFilename
, BOOL bWait
)
1366 IStream
*stream
= NULL
;
1367 ICONDIRENTRY
*pIconDirEntries
= NULL
;
1370 char *nativeIdentifier
= NULL
;
1372 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW
), index
, wine_dbgstr_a(destFilename
));
1374 hr
= open_icon(icoPathW
, index
, bWait
, &stream
, &pIconDirEntries
, &numEntries
);
1377 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW
), index
, hr
);
1380 hr
= platform_write_icon(stream
, pIconDirEntries
, numEntries
, index
, icoPathW
, destFilename
, &nativeIdentifier
);
1382 WINE_WARN("writing icon failed, error 0x%08X\n", hr
);
1386 IStream_Release(stream
);
1387 HeapFree(GetProcessHeap(), 0, pIconDirEntries
);
1390 HeapFree(GetProcessHeap(), 0, nativeIdentifier
);
1391 nativeIdentifier
= NULL
;
1393 return nativeIdentifier
;
1396 static HKEY
open_menus_reg_key(void)
1398 static const WCHAR Software_Wine_FileOpenMenuFilesW
[] = {
1399 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1402 ret
= RegCreateKeyW(HKEY_CURRENT_USER
, Software_Wine_FileOpenMenuFilesW
, &assocKey
);
1403 if (ret
== ERROR_SUCCESS
)
1409 static DWORD
register_menus_entry(const char *unix_file
, const char *windows_file
)
1412 WCHAR
*windows_fileW
;
1416 size
= MultiByteToWideChar(CP_UNIXCP
, 0, unix_file
, -1, NULL
, 0);
1417 unix_fileW
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
1420 MultiByteToWideChar(CP_UNIXCP
, 0, unix_file
, -1, unix_fileW
, size
);
1421 size
= MultiByteToWideChar(CP_UNIXCP
, 0, windows_file
, -1, NULL
, 0);
1422 windows_fileW
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
1426 MultiByteToWideChar(CP_UNIXCP
, 0, windows_file
, -1, windows_fileW
, size
);
1427 hkey
= open_menus_reg_key();
1430 ret
= RegSetValueExW(hkey
, unix_fileW
, 0, REG_SZ
, (const BYTE
*)windows_fileW
,
1431 (strlenW(windows_fileW
) + 1) * sizeof(WCHAR
));
1435 ret
= GetLastError();
1436 HeapFree(GetProcessHeap(), 0, windows_fileW
);
1439 ret
= ERROR_NOT_ENOUGH_MEMORY
;
1440 HeapFree(GetProcessHeap(), 0, unix_fileW
);
1443 ret
= ERROR_NOT_ENOUGH_MEMORY
;
1447 static BOOL
write_desktop_entry(const char *unix_link
, const char *location
, const char *linkname
,
1448 const char *path
, const char *args
, const char *descr
,
1449 const char *workdir
, const char *icon
)
1453 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link
), wine_dbgstr_a(location
),
1454 wine_dbgstr_a(linkname
), wine_dbgstr_a(path
), wine_dbgstr_a(args
),
1455 wine_dbgstr_a(descr
), wine_dbgstr_a(workdir
), wine_dbgstr_a(icon
));
1457 file
= fopen(location
, "w");
1461 fprintf(file
, "[Desktop Entry]\n");
1462 fprintf(file
, "Name=%s\n", linkname
);
1463 fprintf(file
, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1464 wine_get_config_dir(), path
, args
);
1465 fprintf(file
, "Type=Application\n");
1466 fprintf(file
, "StartupNotify=true\n");
1467 if (descr
&& lstrlenA(descr
))
1468 fprintf(file
, "Comment=%s\n", descr
);
1469 if (workdir
&& lstrlenA(workdir
))
1470 fprintf(file
, "Path=%s\n", workdir
);
1471 if (icon
&& lstrlenA(icon
))
1472 fprintf(file
, "Icon=%s\n", icon
);
1478 DWORD ret
= register_menus_entry(location
, unix_link
);
1479 if (ret
!= ERROR_SUCCESS
)
1486 static BOOL
write_directory_entry(const char *directory
, const char *location
)
1490 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory
), wine_dbgstr_a(location
));
1492 file
= fopen(location
, "w");
1496 fprintf(file
, "[Desktop Entry]\n");
1497 fprintf(file
, "Type=Directory\n");
1498 if (strcmp(directory
, "wine") == 0)
1500 fprintf(file
, "Name=Wine\n");
1501 fprintf(file
, "Icon=wine\n");
1505 fprintf(file
, "Name=%s\n", directory
);
1506 fprintf(file
, "Icon=folder\n");
1513 static BOOL
write_menu_file(const char *unix_link
, const char *filename
)
1516 FILE *tempfile
= NULL
;
1519 char *menuPath
= NULL
;
1524 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename
));
1528 tempfilename
= heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir
);
1531 int tempfd
= mkstemps(tempfilename
, 0);
1534 tempfile
= fdopen(tempfd
, "w");
1540 else if (errno
== EEXIST
)
1542 HeapFree(GetProcessHeap(), 0, tempfilename
);
1545 HeapFree(GetProcessHeap(), 0, tempfilename
);
1550 fprintf(tempfile
, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1551 fprintf(tempfile
, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1552 fprintf(tempfile
, "<Menu>\n");
1553 fprintf(tempfile
, " <Name>Applications</Name>\n");
1555 name
= HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename
) + 1);
1556 if (name
== NULL
) goto end
;
1558 for (i
= 0; filename
[i
]; i
++)
1560 name
[i
] = filename
[i
];
1561 if (filename
[i
] == '/')
1563 char *dir_file_name
;
1566 fprintf(tempfile
, " <Menu>\n");
1567 fprintf(tempfile
, " <Name>%s", count
? "" : "wine-");
1568 write_xml_text(tempfile
, name
);
1569 fprintf(tempfile
, "</Name>\n");
1570 fprintf(tempfile
, " <Directory>%s", count
? "" : "wine-");
1571 write_xml_text(tempfile
, name
);
1572 fprintf(tempfile
, ".directory</Directory>\n");
1573 dir_file_name
= heap_printf("%s/desktop-directories/%s%s.directory",
1574 xdg_data_dir
, count
? "" : "wine-", name
);
1577 if (stat(dir_file_name
, &st
) != 0 && errno
== ENOENT
)
1578 write_directory_entry(lastEntry
, dir_file_name
);
1579 HeapFree(GetProcessHeap(), 0, dir_file_name
);
1582 lastEntry
= &name
[i
+1];
1588 fprintf(tempfile
, " <Include>\n");
1589 fprintf(tempfile
, " <Filename>");
1590 write_xml_text(tempfile
, name
);
1591 fprintf(tempfile
, "</Filename>\n");
1592 fprintf(tempfile
, " </Include>\n");
1593 for (i
= 0; i
< count
; i
++)
1594 fprintf(tempfile
, " </Menu>\n");
1595 fprintf(tempfile
, "</Menu>\n");
1597 menuPath
= heap_printf("%s/%s", xdg_config_dir
, name
);
1598 if (menuPath
== NULL
) goto end
;
1599 strcpy(menuPath
+ strlen(menuPath
) - strlen(".desktop"), ".menu");
1606 ret
= (rename(tempfilename
, menuPath
) == 0);
1607 if (!ret
&& tempfilename
)
1608 remove(tempfilename
);
1609 HeapFree(GetProcessHeap(), 0, tempfilename
);
1611 register_menus_entry(menuPath
, unix_link
);
1612 HeapFree(GetProcessHeap(), 0, name
);
1613 HeapFree(GetProcessHeap(), 0, menuPath
);
1617 static BOOL
write_menu_entry(const char *unix_link
, const char *link
, const char *path
, const char *args
,
1618 const char *descr
, const char *workdir
, const char *icon
)
1620 const char *linkname
;
1621 char *desktopPath
= NULL
;
1623 char *filename
= NULL
;
1626 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link
), wine_dbgstr_a(link
),
1627 wine_dbgstr_a(path
), wine_dbgstr_a(args
), wine_dbgstr_a(descr
),
1628 wine_dbgstr_a(workdir
), wine_dbgstr_a(icon
));
1630 linkname
= strrchr(link
, '/');
1631 if (linkname
== NULL
)
1636 desktopPath
= heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir
, link
);
1639 WINE_WARN("out of memory creating menu entry\n");
1643 desktopDir
= strrchr(desktopPath
, '/');
1645 if (!create_directories(desktopPath
))
1647 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath
));
1652 if (!write_desktop_entry(unix_link
, desktopPath
, linkname
, path
, args
, descr
, workdir
, icon
))
1654 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath
));
1659 filename
= heap_printf("wine/%s.desktop", link
);
1660 if (!filename
|| !write_menu_file(unix_link
, filename
))
1662 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename
));
1667 HeapFree(GetProcessHeap(), 0, desktopPath
);
1668 HeapFree(GetProcessHeap(), 0, filename
);
1672 /* This escapes reserved characters in .desktop files' Exec keys. */
1673 static LPSTR
escape(LPCWSTR arg
)
1676 WCHAR
*escaped_string
;
1679 escaped_string
= HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg
) + 1) * sizeof(WCHAR
));
1680 if (escaped_string
== NULL
) return NULL
;
1681 for (i
= j
= 0; arg
[i
]; i
++)
1686 escaped_string
[j
++] = '\\';
1687 escaped_string
[j
++] = '\\';
1688 escaped_string
[j
++] = '\\';
1689 escaped_string
[j
++] = '\\';
1709 escaped_string
[j
++] = '\\';
1710 escaped_string
[j
++] = '\\';
1713 escaped_string
[j
++] = arg
[i
];
1717 escaped_string
[j
] = 0;
1719 utf8_string
= wchars_to_utf8_chars(escaped_string
);
1720 if (utf8_string
== NULL
)
1722 WINE_ERR("out of memory\n");
1727 HeapFree(GetProcessHeap(), 0, escaped_string
);
1731 /* Return a heap-allocated copy of the unix format difference between the two
1732 * Windows-format paths.
1733 * locn is the owning location
1734 * link is within locn
1736 static char *relative_path( LPCWSTR link
, LPCWSTR locn
)
1738 char *unix_locn
, *unix_link
;
1739 char *relative
= NULL
;
1741 unix_locn
= wine_get_unix_file_name(locn
);
1742 unix_link
= wine_get_unix_file_name(link
);
1743 if (unix_locn
&& unix_link
)
1745 size_t len_unix_locn
, len_unix_link
;
1746 len_unix_locn
= strlen (unix_locn
);
1747 len_unix_link
= strlen (unix_link
);
1748 if (len_unix_locn
< len_unix_link
&& memcmp (unix_locn
, unix_link
, len_unix_locn
) == 0 && unix_link
[len_unix_locn
] == '/')
1751 char *p
= strrchr (unix_link
+ len_unix_locn
, '/');
1752 p
= strrchr (p
, '.');
1756 len_unix_link
= p
- unix_link
;
1758 len_rel
= len_unix_link
- len_unix_locn
;
1759 relative
= HeapAlloc(GetProcessHeap(), 0, len_rel
);
1762 memcpy (relative
, unix_link
+ len_unix_locn
+ 1, len_rel
);
1767 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link
), wine_dbgstr_w(locn
));
1768 HeapFree(GetProcessHeap(), 0, unix_locn
);
1769 HeapFree(GetProcessHeap(), 0, unix_link
);
1773 /***********************************************************************
1777 * returns TRUE if successful
1778 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1779 * *relative will contain the address of a heap-allocated copy of the portion
1780 * of the filename that is within the specified location, in unix form
1782 static BOOL
GetLinkLocation( LPCWSTR linkfile
, DWORD
*loc
, char **relative
)
1784 WCHAR filename
[MAX_PATH
], shortfilename
[MAX_PATH
], buffer
[MAX_PATH
];
1785 DWORD len
, i
, r
, filelen
;
1786 const DWORD locations
[] = {
1787 CSIDL_STARTUP
, CSIDL_DESKTOPDIRECTORY
, CSIDL_STARTMENU
,
1788 CSIDL_COMMON_STARTUP
, CSIDL_COMMON_DESKTOPDIRECTORY
,
1789 CSIDL_COMMON_STARTMENU
};
1791 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile
));
1792 filelen
=GetFullPathNameW( linkfile
, MAX_PATH
, shortfilename
, NULL
);
1793 if (filelen
==0 || filelen
>MAX_PATH
)
1796 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename
));
1798 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1799 * expand or our hardcoded list won't match.
1801 filelen
=GetLongPathNameW(shortfilename
, filename
, MAX_PATH
);
1802 if (filelen
==0 || filelen
>MAX_PATH
)
1805 WINE_TRACE("%s\n", wine_dbgstr_w(filename
));
1807 for( i
=0; i
<sizeof(locations
)/sizeof(locations
[0]); i
++ )
1809 if (!SHGetSpecialFolderPathW( 0, buffer
, locations
[i
], FALSE
))
1812 len
= lstrlenW(buffer
);
1813 if (len
>= MAX_PATH
)
1814 continue; /* We've just trashed memory! Hopefully we are OK */
1816 if (len
> filelen
|| filename
[len
]!='\\')
1818 /* do a lstrcmpinW */
1820 r
= lstrcmpiW( filename
, buffer
);
1821 filename
[len
] = '\\';
1825 /* return the remainder of the string and link type */
1826 *loc
= locations
[i
];
1827 *relative
= relative_path (filename
, buffer
);
1828 return (*relative
!= NULL
);
1834 /* gets the target path directly or through MSI */
1835 static HRESULT
get_cmdline( IShellLinkW
*sl
, LPWSTR szPath
, DWORD pathSize
,
1836 LPWSTR szArgs
, DWORD argsSize
)
1838 IShellLinkDataList
*dl
= NULL
;
1839 EXP_DARWIN_LINK
*dar
= NULL
;
1845 hr
= IShellLinkW_GetPath( sl
, szPath
, pathSize
, NULL
, SLGP_RAWPATH
);
1846 if (hr
== S_OK
&& szPath
[0])
1848 IShellLinkW_GetArguments( sl
, szArgs
, argsSize
);
1852 hr
= IShellLinkW_QueryInterface( sl
, &IID_IShellLinkDataList
, (LPVOID
*) &dl
);
1856 hr
= IShellLinkDataList_CopyDataBlock( dl
, EXP_DARWIN_ID_SIG
, (LPVOID
*) &dar
);
1863 hr
= CommandLineFromMsiDescriptor( dar
->szwDarwinID
, NULL
, &cmdSize
);
1864 if (hr
== ERROR_SUCCESS
)
1867 szCmdline
= HeapAlloc( GetProcessHeap(), 0, cmdSize
*sizeof(WCHAR
) );
1868 hr
= CommandLineFromMsiDescriptor( dar
->szwDarwinID
, szCmdline
, &cmdSize
);
1869 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline
));
1870 if (hr
== ERROR_SUCCESS
)
1874 BOOL in_quotes
= FALSE
;
1876 /* Extract the application path */
1881 if ((*s
==0x0009 || *s
==0x0020) && !in_quotes
)
1883 /* skip the remaining spaces */
1886 } while (*s
==0x0009 || *s
==0x0020);
1889 else if (*s
==0x005c)
1895 else if (*s
==0x0022)
1898 if ((bcount
& 1)==0)
1900 /* Preceded by an even number of '\', this is
1901 * half that number of '\', plus a quote which
1905 in_quotes
=!in_quotes
;
1910 /* Preceded by an odd number of '\', this is
1911 * half that number of '\' followed by a '"'
1921 /* a regular character */
1925 if ((d
-szPath
) == pathSize
)
1927 /* Keep processing the path till we get to the
1928 * arguments, but 'stand still'
1933 /* Close the application path */
1936 lstrcpynW(szArgs
, s
, argsSize
);
1938 HeapFree( GetProcessHeap(), 0, szCmdline
);
1943 IShellLinkDataList_Release( dl
);
1947 static char *slashes_to_minuses(const char *string
)
1950 char *ret
= HeapAlloc(GetProcessHeap(), 0, lstrlenA(string
) + 1);
1953 for (i
= 0; string
[i
]; i
++)
1955 if (string
[i
] == '/')
1966 static BOOL
next_line(FILE *file
, char **line
, int *size
)
1973 *line
= HeapAlloc(GetProcessHeap(), 0, *size
);
1975 while (*line
!= NULL
)
1977 if (fgets(&(*line
)[pos
], *size
- pos
, file
) == NULL
)
1979 HeapFree(GetProcessHeap(), 0, *line
);
1985 pos
= strlen(*line
);
1986 cr
= strchr(*line
, '\n');
1991 line2
= HeapReAlloc(GetProcessHeap(), 0, *line
, *size
);
1996 HeapFree(GetProcessHeap(), 0, *line
);
2009 static BOOL
add_mimes(const char *xdg_data_dir
, struct list
*mime_types
)
2011 char *globs_filename
= NULL
;
2013 globs_filename
= heap_printf("%s/mime/globs", xdg_data_dir
);
2016 FILE *globs_file
= fopen(globs_filename
, "r");
2017 if (globs_file
) /* doesn't have to exist */
2021 while (ret
&& (ret
= next_line(globs_file
, &line
, &size
)) && line
)
2024 struct xdg_mime_type
*mime_type_entry
= NULL
;
2025 if (line
[0] != '#' && (pos
= strchr(line
, ':')))
2027 mime_type_entry
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type
));
2028 if (mime_type_entry
)
2031 mime_type_entry
->mimeType
= strdupA(line
);
2032 mime_type_entry
->glob
= strdupA(pos
+ 1);
2033 mime_type_entry
->lower_glob
= strdupA(pos
+ 1);
2034 if (mime_type_entry
->lower_glob
)
2037 for (l
= mime_type_entry
->lower_glob
; *l
; l
++)
2040 if (mime_type_entry
->mimeType
&& mime_type_entry
->glob
&& mime_type_entry
->lower_glob
)
2041 list_add_tail(mime_types
, &mime_type_entry
->entry
);
2044 HeapFree(GetProcessHeap(), 0, mime_type_entry
->mimeType
);
2045 HeapFree(GetProcessHeap(), 0, mime_type_entry
->glob
);
2046 HeapFree(GetProcessHeap(), 0, mime_type_entry
->lower_glob
);
2047 HeapFree(GetProcessHeap(), 0, mime_type_entry
);
2055 HeapFree(GetProcessHeap(), 0, line
);
2058 HeapFree(GetProcessHeap(), 0, globs_filename
);
2065 static void free_native_mime_types(struct list
*native_mime_types
)
2067 struct xdg_mime_type
*mime_type_entry
, *mime_type_entry2
;
2069 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry
, mime_type_entry2
, native_mime_types
, struct xdg_mime_type
, entry
)
2071 list_remove(&mime_type_entry
->entry
);
2072 HeapFree(GetProcessHeap(), 0, mime_type_entry
->glob
);
2073 HeapFree(GetProcessHeap(), 0, mime_type_entry
->lower_glob
);
2074 HeapFree(GetProcessHeap(), 0, mime_type_entry
->mimeType
);
2075 HeapFree(GetProcessHeap(), 0, mime_type_entry
);
2079 static BOOL
build_native_mime_types(const char *xdg_data_home
, struct list
*mime_types
)
2081 char *xdg_data_dirs
;
2084 xdg_data_dirs
= getenv("XDG_DATA_DIRS");
2085 if (xdg_data_dirs
== NULL
)
2086 xdg_data_dirs
= heap_printf("/usr/local/share/:/usr/share/");
2088 xdg_data_dirs
= strdupA(xdg_data_dirs
);
2095 ret
= add_mimes(xdg_data_home
, mime_types
);
2098 for (begin
= xdg_data_dirs
; (end
= strchr(begin
, ':')); begin
= end
+ 1)
2101 ret
= add_mimes(begin
, mime_types
);
2107 ret
= add_mimes(begin
, mime_types
);
2109 HeapFree(GetProcessHeap(), 0, xdg_data_dirs
);
2114 free_native_mime_types(mime_types
);
2118 static BOOL
match_glob(struct list
*native_mime_types
, const char *extension
,
2119 int ignoreGlobCase
, char **match
)
2122 struct xdg_mime_type
*mime_type_entry
;
2123 int matchLength
= 0;
2127 LIST_FOR_EACH_ENTRY(mime_type_entry
, native_mime_types
, struct xdg_mime_type
, entry
)
2129 const char *glob
= ignoreGlobCase
? mime_type_entry
->lower_glob
: mime_type_entry
->glob
;
2130 if (fnmatch(glob
, extension
, 0) == 0)
2132 if (*match
== NULL
|| matchLength
< strlen(glob
))
2134 *match
= mime_type_entry
->mimeType
;
2135 matchLength
= strlen(glob
);
2142 *match
= strdupA(*match
);
2152 static BOOL
freedesktop_mime_type_for_extension(struct list
*native_mime_types
,
2153 const char *extensionA
,
2157 WCHAR
*lower_extensionW
;
2159 BOOL ret
= match_glob(native_mime_types
, extensionA
, 0, mime_type
);
2160 if (ret
== FALSE
|| *mime_type
!= NULL
)
2162 len
= strlenW(extensionW
);
2163 lower_extensionW
= HeapAlloc(GetProcessHeap(), 0, (len
+ 1)*sizeof(WCHAR
));
2164 if (lower_extensionW
)
2166 char *lower_extensionA
;
2167 memcpy(lower_extensionW
, extensionW
, (len
+ 1)*sizeof(WCHAR
));
2168 strlwrW(lower_extensionW
);
2169 lower_extensionA
= wchars_to_utf8_chars(lower_extensionW
);
2170 if (lower_extensionA
)
2172 ret
= match_glob(native_mime_types
, lower_extensionA
, 1, mime_type
);
2173 HeapFree(GetProcessHeap(), 0, lower_extensionA
);
2178 WINE_FIXME("out of memory\n");
2180 HeapFree(GetProcessHeap(), 0, lower_extensionW
);
2185 WINE_FIXME("out of memory\n");
2190 static WCHAR
* reg_get_valW(HKEY key
, LPCWSTR subkey
, LPCWSTR name
)
2193 if (RegGetValueW(key
, subkey
, name
, RRF_RT_REG_SZ
, NULL
, NULL
, &size
) == ERROR_SUCCESS
)
2195 WCHAR
*ret
= HeapAlloc(GetProcessHeap(), 0, size
);
2198 if (RegGetValueW(key
, subkey
, name
, RRF_RT_REG_SZ
, NULL
, ret
, &size
) == ERROR_SUCCESS
)
2201 HeapFree(GetProcessHeap(), 0, ret
);
2206 static CHAR
* reg_get_val_utf8(HKEY key
, LPCWSTR subkey
, LPCWSTR name
)
2208 WCHAR
*valW
= reg_get_valW(key
, subkey
, name
);
2211 char *val
= wchars_to_utf8_chars(valW
);
2212 HeapFree(GetProcessHeap(), 0, valW
);
2218 static HKEY
open_associations_reg_key(void)
2220 static const WCHAR Software_Wine_FileOpenAssociationsW
[] = {
2221 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','F','i','l','e','O','p','e','n','A','s','s','o','c','i','a','t','i','o','n','s',0};
2223 if (RegCreateKeyW(HKEY_CURRENT_USER
, Software_Wine_FileOpenAssociationsW
, &assocKey
) == ERROR_SUCCESS
)
2228 static BOOL
has_association_changed(LPCWSTR extensionW
, LPCSTR mimeType
, LPCWSTR progId
,
2229 LPCSTR appName
, LPCSTR openWithIcon
)
2231 static const WCHAR ProgIDW
[] = {'P','r','o','g','I','D',0};
2232 static const WCHAR MimeTypeW
[] = {'M','i','m','e','T','y','p','e',0};
2233 static const WCHAR AppNameW
[] = {'A','p','p','N','a','m','e',0};
2234 static const WCHAR OpenWithIconW
[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2238 if ((assocKey
= open_associations_reg_key()))
2245 valueA
= reg_get_val_utf8(assocKey
, extensionW
, MimeTypeW
);
2246 if (!valueA
|| lstrcmpA(valueA
, mimeType
))
2248 HeapFree(GetProcessHeap(), 0, valueA
);
2250 value
= reg_get_valW(assocKey
, extensionW
, ProgIDW
);
2251 if (!value
|| strcmpW(value
, progId
))
2253 HeapFree(GetProcessHeap(), 0, value
);
2255 valueA
= reg_get_val_utf8(assocKey
, extensionW
, AppNameW
);
2256 if (!valueA
|| lstrcmpA(valueA
, appName
))
2258 HeapFree(GetProcessHeap(), 0, valueA
);
2260 valueA
= reg_get_val_utf8(assocKey
, extensionW
, OpenWithIconW
);
2261 if ((openWithIcon
&& !valueA
) ||
2262 (!openWithIcon
&& valueA
) ||
2263 (openWithIcon
&& valueA
&& lstrcmpA(valueA
, openWithIcon
)))
2265 HeapFree(GetProcessHeap(), 0, valueA
);
2267 RegCloseKey(assocKey
);
2271 WINE_ERR("error opening associations registry key\n");
2277 static void update_association(LPCWSTR extension
, LPCSTR mimeType
, LPCWSTR progId
,
2278 LPCSTR appName
, LPCSTR desktopFile
, LPCSTR openWithIcon
)
2280 static const WCHAR ProgIDW
[] = {'P','r','o','g','I','D',0};
2281 static const WCHAR MimeTypeW
[] = {'M','i','m','e','T','y','p','e',0};
2282 static const WCHAR AppNameW
[] = {'A','p','p','N','a','m','e',0};
2283 static const WCHAR DesktopFileW
[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2284 static const WCHAR OpenWithIconW
[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2285 HKEY assocKey
= NULL
;
2287 WCHAR
*mimeTypeW
= NULL
;
2288 WCHAR
*appNameW
= NULL
;
2289 WCHAR
*desktopFileW
= NULL
;
2290 WCHAR
*openWithIconW
= NULL
;
2292 assocKey
= open_associations_reg_key();
2293 if (assocKey
== NULL
)
2295 WINE_ERR("could not open file associations key\n");
2299 if (RegCreateKeyW(assocKey
, extension
, &subkey
) != ERROR_SUCCESS
)
2301 WINE_ERR("could not create extension subkey\n");
2305 mimeTypeW
= utf8_chars_to_wchars(mimeType
);
2306 if (mimeTypeW
== NULL
)
2308 WINE_ERR("out of memory\n");
2312 appNameW
= utf8_chars_to_wchars(appName
);
2313 if (appNameW
== NULL
)
2315 WINE_ERR("out of memory\n");
2319 desktopFileW
= utf8_chars_to_wchars(desktopFile
);
2320 if (desktopFileW
== NULL
)
2322 WINE_ERR("out of memory\n");
2328 openWithIconW
= utf8_chars_to_wchars(openWithIcon
);
2329 if (openWithIconW
== NULL
)
2331 WINE_ERR("out of memory\n");
2336 RegSetValueExW(subkey
, MimeTypeW
, 0, REG_SZ
, (const BYTE
*) mimeTypeW
, (lstrlenW(mimeTypeW
) + 1) * sizeof(WCHAR
));
2337 RegSetValueExW(subkey
, ProgIDW
, 0, REG_SZ
, (const BYTE
*) progId
, (lstrlenW(progId
) + 1) * sizeof(WCHAR
));
2338 RegSetValueExW(subkey
, AppNameW
, 0, REG_SZ
, (const BYTE
*) appNameW
, (lstrlenW(appNameW
) + 1) * sizeof(WCHAR
));
2339 RegSetValueExW(subkey
, DesktopFileW
, 0, REG_SZ
, (const BYTE
*) desktopFileW
, (lstrlenW(desktopFileW
) + 1) * sizeof(WCHAR
));
2341 RegSetValueExW(subkey
, OpenWithIconW
, 0, REG_SZ
, (const BYTE
*) openWithIconW
, (lstrlenW(openWithIconW
) + 1) * sizeof(WCHAR
));
2343 RegDeleteValueW(subkey
, OpenWithIconW
);
2346 RegCloseKey(assocKey
);
2347 RegCloseKey(subkey
);
2348 HeapFree(GetProcessHeap(), 0, mimeTypeW
);
2349 HeapFree(GetProcessHeap(), 0, appNameW
);
2350 HeapFree(GetProcessHeap(), 0, desktopFileW
);
2351 HeapFree(GetProcessHeap(), 0, openWithIconW
);
2354 static BOOL
cleanup_associations(void)
2356 static const WCHAR openW
[] = {'o','p','e','n',0};
2357 static const WCHAR DesktopFileW
[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2359 BOOL hasChanged
= FALSE
;
2360 if ((assocKey
= open_associations_reg_key()))
2366 WCHAR
*extensionW
= NULL
;
2372 HeapFree(GetProcessHeap(), 0, extensionW
);
2373 extensionW
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
2374 if (extensionW
== NULL
)
2376 WINE_ERR("out of memory\n");
2377 ret
= ERROR_OUTOFMEMORY
;
2380 ret
= RegEnumKeyExW(assocKey
, i
, extensionW
, &size
, NULL
, NULL
, NULL
, NULL
);
2382 } while (ret
== ERROR_MORE_DATA
);
2384 if (ret
== ERROR_SUCCESS
)
2387 command
= assoc_query(ASSOCSTR_COMMAND
, extensionW
, openW
);
2388 if (command
== NULL
)
2390 char *desktopFile
= reg_get_val_utf8(assocKey
, extensionW
, DesktopFileW
);
2393 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW
));
2394 remove(desktopFile
);
2396 RegDeleteKeyW(assocKey
, extensionW
);
2398 HeapFree(GetProcessHeap(), 0, desktopFile
);
2402 HeapFree(GetProcessHeap(), 0, command
);
2406 if (ret
!= ERROR_NO_MORE_ITEMS
)
2407 WINE_ERR("error %d while reading registry\n", ret
);
2410 HeapFree(GetProcessHeap(), 0, extensionW
);
2412 RegCloseKey(assocKey
);
2415 WINE_ERR("could not open file associations key\n");
2419 static BOOL
write_freedesktop_mime_type_entry(const char *packages_dir
, const char *dot_extension
,
2420 const char *mime_type
, const char *comment
)
2425 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type
),
2426 wine_dbgstr_a(dot_extension
), wine_dbgstr_a(comment
));
2428 filename
= heap_printf("%s/x-wine-extension-%s.xml", packages_dir
, &dot_extension
[1]);
2431 FILE *packageFile
= fopen(filename
, "w");
2434 fprintf(packageFile
, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2435 fprintf(packageFile
, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2436 fprintf(packageFile
, " <mime-type type=\"");
2437 write_xml_text(packageFile
, mime_type
);
2438 fprintf(packageFile
, "\">\n");
2439 fprintf(packageFile
, " <glob pattern=\"*");
2440 write_xml_text(packageFile
, dot_extension
);
2441 fprintf(packageFile
, "\"/>\n");
2444 fprintf(packageFile
, " <comment>");
2445 write_xml_text(packageFile
, comment
);
2446 fprintf(packageFile
, "</comment>\n");
2448 fprintf(packageFile
, " </mime-type>\n");
2449 fprintf(packageFile
, "</mime-info>\n");
2451 fclose(packageFile
);
2454 WINE_ERR("error writing file %s\n", filename
);
2455 HeapFree(GetProcessHeap(), 0, filename
);
2458 WINE_ERR("out of memory\n");
2462 static BOOL
is_extension_blacklisted(LPCWSTR extension
)
2464 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2465 static const WCHAR comW
[] = {'.','c','o','m',0};
2466 static const WCHAR exeW
[] = {'.','e','x','e',0};
2467 static const WCHAR msiW
[] = {'.','m','s','i',0};
2469 if (!strcmpiW(extension
, comW
) ||
2470 !strcmpiW(extension
, exeW
) ||
2471 !strcmpiW(extension
, msiW
))
2476 static const char* get_special_mime_type(LPCWSTR extension
)
2478 static const WCHAR lnkW
[] = {'.','l','n','k',0};
2479 if (!strcmpiW(extension
, lnkW
))
2480 return "application/x-ms-shortcut";
2484 static BOOL
write_freedesktop_association_entry(const char *desktopPath
, const char *dot_extension
,
2485 const char *friendlyAppName
, const char *mimeType
,
2486 const char *progId
, const char *openWithIcon
)
2491 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2492 wine_dbgstr_a(dot_extension
), wine_dbgstr_a(friendlyAppName
), wine_dbgstr_a(mimeType
),
2493 wine_dbgstr_a(progId
), wine_dbgstr_a(openWithIcon
), wine_dbgstr_a(desktopPath
));
2495 desktop
= fopen(desktopPath
, "w");
2498 fprintf(desktop
, "[Desktop Entry]\n");
2499 fprintf(desktop
, "Type=Application\n");
2500 fprintf(desktop
, "Name=%s\n", friendlyAppName
);
2501 fprintf(desktop
, "MimeType=%s;\n", mimeType
);
2502 fprintf(desktop
, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId
);
2503 fprintf(desktop
, "NoDisplay=true\n");
2504 fprintf(desktop
, "StartupNotify=true\n");
2506 fprintf(desktop
, "Icon=%s\n", openWithIcon
);
2511 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath
));
2515 static BOOL
generate_associations(const char *xdg_data_home
, const char *packages_dir
, const char *applications_dir
)
2517 static const WCHAR openW
[] = {'o','p','e','n',0};
2518 struct wine_rb_tree mimeProgidTree
= { winemenubuilder_rb_string_compare
};
2519 struct list nativeMimeTypes
= LIST_INIT(nativeMimeTypes
);
2522 BOOL hasChanged
= FALSE
;
2524 if (!build_native_mime_types(xdg_data_home
, &nativeMimeTypes
))
2526 WINE_ERR("could not build native MIME types\n");
2532 WCHAR
*extensionW
= NULL
;
2537 HeapFree(GetProcessHeap(), 0, extensionW
);
2538 extensionW
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
2539 if (extensionW
== NULL
)
2541 WINE_ERR("out of memory\n");
2542 ret
= ERROR_OUTOFMEMORY
;
2545 ret
= RegEnumKeyExW(HKEY_CLASSES_ROOT
, i
, extensionW
, &size
, NULL
, NULL
, NULL
, NULL
);
2547 } while (ret
== ERROR_MORE_DATA
);
2549 if (ret
== ERROR_SUCCESS
&& extensionW
[0] == '.' && !is_extension_blacklisted(extensionW
))
2551 char *extensionA
= NULL
;
2552 WCHAR
*commandW
= NULL
;
2553 WCHAR
*executableW
= NULL
;
2554 char *openWithIconA
= NULL
;
2555 WCHAR
*friendlyDocNameW
= NULL
;
2556 char *friendlyDocNameA
= NULL
;
2557 WCHAR
*iconW
= NULL
;
2559 WCHAR
*contentTypeW
= NULL
;
2560 char *mimeTypeA
= NULL
;
2561 WCHAR
*friendlyAppNameW
= NULL
;
2562 char *friendlyAppNameA
= NULL
;
2563 WCHAR
*progIdW
= NULL
;
2564 char *progIdA
= NULL
;
2565 char *mimeProgId
= NULL
;
2567 extensionA
= wchars_to_utf8_chars(strlwrW(extensionW
));
2568 if (extensionA
== NULL
)
2570 WINE_ERR("out of memory\n");
2574 friendlyDocNameW
= assoc_query(ASSOCSTR_FRIENDLYDOCNAME
, extensionW
, NULL
);
2575 if (friendlyDocNameW
)
2577 friendlyDocNameA
= wchars_to_utf8_chars(friendlyDocNameW
);
2578 if (friendlyDocNameA
== NULL
)
2580 WINE_ERR("out of memory\n");
2585 iconW
= assoc_query(ASSOCSTR_DEFAULTICON
, extensionW
, NULL
);
2587 contentTypeW
= assoc_query(ASSOCSTR_CONTENTTYPE
, extensionW
, NULL
);
2589 strlwrW(contentTypeW
);
2591 if (!freedesktop_mime_type_for_extension(&nativeMimeTypes
, extensionA
, extensionW
, &mimeTypeA
))
2594 if (mimeTypeA
== NULL
)
2596 if (contentTypeW
!= NULL
&& strchrW(contentTypeW
, '/'))
2597 mimeTypeA
= wchars_to_utf8_chars(contentTypeW
);
2598 else if ((get_special_mime_type(extensionW
)))
2599 mimeTypeA
= strdupA(get_special_mime_type(extensionW
));
2601 mimeTypeA
= heap_printf("application/x-wine-extension-%s", &extensionA
[1]);
2603 if (mimeTypeA
!= NULL
)
2605 /* GNOME seems to ignore the <icon> tag in MIME packages,
2606 * and the default name is more intuitive anyway.
2610 char *flattened_mime
= slashes_to_minuses(mimeTypeA
);
2614 WCHAR
*comma
= strrchrW(iconW
, ',');
2618 index
= atoiW(comma
+ 1);
2620 iconA
= extract_icon(iconW
, index
, flattened_mime
, FALSE
);
2621 HeapFree(GetProcessHeap(), 0, flattened_mime
);
2625 write_freedesktop_mime_type_entry(packages_dir
, extensionA
, mimeTypeA
, friendlyDocNameA
);
2630 WINE_FIXME("out of memory\n");
2635 commandW
= assoc_query(ASSOCSTR_COMMAND
, extensionW
, openW
);
2636 if (commandW
== NULL
)
2637 /* no command => no application is associated */
2640 executableW
= assoc_query(ASSOCSTR_EXECUTABLE
, extensionW
, openW
);
2642 openWithIconA
= extract_icon(executableW
, 0, NULL
, FALSE
);
2644 friendlyAppNameW
= assoc_query(ASSOCSTR_FRIENDLYAPPNAME
, extensionW
, openW
);
2645 if (friendlyAppNameW
)
2647 friendlyAppNameA
= wchars_to_utf8_chars(friendlyAppNameW
);
2648 if (friendlyAppNameA
== NULL
)
2650 WINE_ERR("out of memory\n");
2656 friendlyAppNameA
= heap_printf("A Wine application");
2657 if (friendlyAppNameA
== NULL
)
2659 WINE_ERR("out of memory\n");
2664 progIdW
= reg_get_valW(HKEY_CLASSES_ROOT
, extensionW
, NULL
);
2667 progIdA
= escape(progIdW
);
2668 if (progIdA
== NULL
)
2670 WINE_ERR("out of memory\n");
2675 goto end
; /* no progID => not a file type association */
2677 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2678 mimeProgId
= heap_printf("%s=>%s", mimeTypeA
, progIdA
);
2681 struct rb_string_entry
*entry
;
2682 if (wine_rb_get(&mimeProgidTree
, mimeProgId
))
2684 HeapFree(GetProcessHeap(), 0, mimeProgId
);
2687 entry
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry
));
2690 WINE_ERR("out of memory allocating rb_string_entry\n");
2693 entry
->string
= mimeProgId
;
2694 if (wine_rb_put(&mimeProgidTree
, mimeProgId
, &entry
->entry
))
2696 WINE_ERR("error updating rb tree\n");
2701 if (has_association_changed(extensionW
, mimeTypeA
, progIdW
, friendlyAppNameA
, openWithIconA
))
2703 char *desktopPath
= heap_printf("%s/wine-extension-%s.desktop", applications_dir
, &extensionA
[1]);
2706 if (write_freedesktop_association_entry(desktopPath
, extensionA
, friendlyAppNameA
, mimeTypeA
, progIdA
, openWithIconA
))
2709 update_association(extensionW
, mimeTypeA
, progIdW
, friendlyAppNameA
, desktopPath
, openWithIconA
);
2711 HeapFree(GetProcessHeap(), 0, desktopPath
);
2716 HeapFree(GetProcessHeap(), 0, extensionA
);
2717 HeapFree(GetProcessHeap(), 0, commandW
);
2718 HeapFree(GetProcessHeap(), 0, executableW
);
2719 HeapFree(GetProcessHeap(), 0, openWithIconA
);
2720 HeapFree(GetProcessHeap(), 0, friendlyDocNameW
);
2721 HeapFree(GetProcessHeap(), 0, friendlyDocNameA
);
2722 HeapFree(GetProcessHeap(), 0, iconW
);
2723 HeapFree(GetProcessHeap(), 0, iconA
);
2724 HeapFree(GetProcessHeap(), 0, contentTypeW
);
2725 HeapFree(GetProcessHeap(), 0, mimeTypeA
);
2726 HeapFree(GetProcessHeap(), 0, friendlyAppNameW
);
2727 HeapFree(GetProcessHeap(), 0, friendlyAppNameA
);
2728 HeapFree(GetProcessHeap(), 0, progIdW
);
2729 HeapFree(GetProcessHeap(), 0, progIdA
);
2731 HeapFree(GetProcessHeap(), 0, extensionW
);
2732 if (ret
!= ERROR_SUCCESS
)
2736 wine_rb_destroy(&mimeProgidTree
, winemenubuilder_rb_destroy
, NULL
);
2737 free_native_mime_types(&nativeMimeTypes
);
2741 static char *get_start_exe_path(void)
2743 static const WCHAR startW
[] = {'\\','c','o','m','m','a','n','d',
2744 '\\','s','t','a','r','t','.','e','x','e',0};
2745 WCHAR start_path
[MAX_PATH
];
2746 GetWindowsDirectoryW(start_path
, MAX_PATH
);
2747 lstrcatW(start_path
, startW
);
2748 return escape(start_path
);
2751 static char* escape_unix_link_arg(LPCSTR unix_link
)
2754 WCHAR
*unix_linkW
= utf8_chars_to_wchars(unix_link
);
2757 char *escaped_lnk
= escape(unix_linkW
);
2760 ret
= heap_printf("/Unix %s", escaped_lnk
);
2761 HeapFree(GetProcessHeap(), 0, escaped_lnk
);
2763 HeapFree(GetProcessHeap(), 0, unix_linkW
);
2768 static BOOL
InvokeShellLinker( IShellLinkW
*sl
, LPCWSTR link
, BOOL bWait
)
2770 static const WCHAR startW
[] = {'\\','c','o','m','m','a','n','d',
2771 '\\','s','t','a','r','t','.','e','x','e',0};
2772 char *link_name
= NULL
, *icon_name
= NULL
, *work_dir
= NULL
;
2773 char *escaped_path
= NULL
, *escaped_args
= NULL
, *description
= NULL
;
2774 WCHAR szTmp
[INFOTIPSIZE
];
2775 WCHAR szDescription
[INFOTIPSIZE
], szPath
[MAX_PATH
], szWorkDir
[MAX_PATH
];
2776 WCHAR szArgs
[INFOTIPSIZE
], szIconPath
[MAX_PATH
];
2777 int iIconId
= 0, r
= -1;
2780 char *unix_link
= NULL
;
2781 char *start_path
= NULL
;
2785 WINE_ERR("Link name is null\n");
2789 if( !GetLinkLocation( link
, &csidl
, &link_name
) )
2791 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link
));
2794 if (!in_desktop_dir(csidl
) && !in_startmenu(csidl
))
2796 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2799 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name
));
2802 IShellLinkW_GetWorkingDirectory( sl
, szTmp
, MAX_PATH
);
2803 ExpandEnvironmentStringsW(szTmp
, szWorkDir
, MAX_PATH
);
2804 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir
));
2807 IShellLinkW_GetDescription( sl
, szTmp
, INFOTIPSIZE
);
2808 ExpandEnvironmentStringsW(szTmp
, szDescription
, INFOTIPSIZE
);
2809 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription
));
2811 get_cmdline( sl
, szTmp
, MAX_PATH
, szArgs
, INFOTIPSIZE
);
2812 ExpandEnvironmentStringsW(szTmp
, szPath
, MAX_PATH
);
2813 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath
));
2814 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs
));
2817 IShellLinkW_GetIconLocation( sl
, szTmp
, MAX_PATH
, &iIconId
);
2818 ExpandEnvironmentStringsW(szTmp
, szIconPath
, MAX_PATH
);
2819 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath
) );
2823 LPITEMIDLIST pidl
= NULL
;
2824 IShellLinkW_GetIDList( sl
, &pidl
);
2825 if( pidl
&& SHGetPathFromIDListW( pidl
, szPath
) )
2826 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath
));
2829 /* extract the icon */
2831 icon_name
= extract_icon( szIconPath
, iIconId
, NULL
, bWait
);
2833 icon_name
= extract_icon( szPath
, iIconId
, NULL
, bWait
);
2835 /* fail - try once again after parent process exit */
2840 WINE_WARN("Unable to extract icon, deferring.\n");
2843 WINE_ERR("failed to extract icon from %s\n",
2844 wine_dbgstr_w( szIconPath
[0] ? szIconPath
: szPath
));
2847 unix_link
= wine_get_unix_file_name(link
);
2848 if (unix_link
== NULL
)
2850 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link
));
2854 /* check the path */
2857 static const WCHAR exeW
[] = {'.','e','x','e',0};
2860 /* check for .exe extension */
2861 if (!(p
= strrchrW( szPath
, '.' )) ||
2862 strchrW( p
, '\\' ) || strchrW( p
, '/' ) ||
2863 lstrcmpiW( p
, exeW
))
2865 /* Not .exe - use 'start.exe' to launch this file */
2866 p
= szArgs
+ lstrlenW(szPath
) + 2;
2870 memmove( p
+1, szArgs
, min( (lstrlenW(szArgs
) + 1) * sizeof(szArgs
[0]),
2871 sizeof(szArgs
) - (p
+ 1 - szArgs
) * sizeof(szArgs
[0]) ) );
2877 lstrcpyW(szArgs
+ 1, szPath
);
2880 GetWindowsDirectoryW(szPath
, MAX_PATH
);
2881 lstrcatW(szPath
, startW
);
2884 /* convert app working dir */
2886 work_dir
= wine_get_unix_file_name( szWorkDir
);
2890 /* if there's no path... try run the link itself */
2891 lstrcpynW(szArgs
, link
, MAX_PATH
);
2892 GetWindowsDirectoryW(szPath
, MAX_PATH
);
2893 lstrcatW(szPath
, startW
);
2896 /* escape the path and parameters */
2897 escaped_path
= escape(szPath
);
2898 escaped_args
= escape(szArgs
);
2899 description
= wchars_to_utf8_chars(szDescription
);
2900 if (escaped_path
== NULL
|| escaped_args
== NULL
|| description
== NULL
)
2902 WINE_ERR("out of memory allocating/escaping parameters\n");
2906 start_path
= get_start_exe_path();
2907 if (start_path
== NULL
)
2909 WINE_ERR("out of memory\n");
2913 /* building multiple menus concurrently has race conditions */
2914 hsem
= CreateSemaphoreA( NULL
, 1, 1, "winemenubuilder_semaphore");
2915 if( WAIT_OBJECT_0
!= MsgWaitForMultipleObjects( 1, &hsem
, FALSE
, INFINITE
, QS_ALLINPUT
) )
2917 WINE_ERR("failed wait for semaphore\n");
2921 if (in_desktop_dir(csidl
))
2924 const char *lastEntry
;
2925 lastEntry
= strrchr(link_name
, '/');
2926 if (lastEntry
== NULL
)
2927 lastEntry
= link_name
;
2930 location
= heap_printf("%s/%s.desktop", xdg_desktop_dir
, lastEntry
);
2933 if (csidl
== CSIDL_COMMON_DESKTOPDIRECTORY
)
2935 char *link_arg
= escape_unix_link_arg(unix_link
);
2938 r
= !write_desktop_entry(unix_link
, location
, lastEntry
,
2939 start_path
, link_arg
, description
, work_dir
, icon_name
);
2940 HeapFree(GetProcessHeap(), 0, link_arg
);
2944 r
= !write_desktop_entry(NULL
, location
, lastEntry
, escaped_path
, escaped_args
, description
, work_dir
, icon_name
);
2946 chmod(location
, 0755);
2947 HeapFree(GetProcessHeap(), 0, location
);
2952 char *link_arg
= escape_unix_link_arg(unix_link
);
2955 r
= !write_menu_entry(unix_link
, link_name
, start_path
, link_arg
, description
, work_dir
, icon_name
);
2956 HeapFree(GetProcessHeap(), 0, link_arg
);
2960 ReleaseSemaphore( hsem
, 1, NULL
);
2963 if (hsem
) CloseHandle( hsem
);
2964 HeapFree( GetProcessHeap(), 0, icon_name
);
2965 HeapFree( GetProcessHeap(), 0, work_dir
);
2966 HeapFree( GetProcessHeap(), 0, link_name
);
2967 HeapFree( GetProcessHeap(), 0, escaped_args
);
2968 HeapFree( GetProcessHeap(), 0, escaped_path
);
2969 HeapFree( GetProcessHeap(), 0, description
);
2970 HeapFree( GetProcessHeap(), 0, unix_link
);
2971 HeapFree( GetProcessHeap(), 0, start_path
);
2974 WINE_ERR("failed to build the menu\n" );
2979 static BOOL
InvokeShellLinkerForURL( IUniformResourceLocatorW
*url
, LPCWSTR link
, BOOL bWait
)
2981 char *link_name
= NULL
, *icon_name
= NULL
;
2983 LPWSTR urlPath
= NULL
;
2984 char *escaped_urlPath
= NULL
;
2989 char *unix_link
= NULL
;
2990 IPropertySetStorage
*pPropSetStg
;
2991 IPropertyStorage
*pPropStg
;
2994 char *start_path
= NULL
;
2995 BOOL has_icon
= FALSE
;
2999 WINE_ERR("Link name is null\n");
3003 if( !GetLinkLocation( link
, &csidl
, &link_name
) )
3005 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link
));
3008 if (!in_desktop_dir(csidl
) && !in_startmenu(csidl
))
3010 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3014 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name
));
3016 hr
= url
->lpVtbl
->GetURL(url
, &urlPath
);
3022 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath
));
3024 unix_link
= wine_get_unix_file_name(link
);
3025 if (unix_link
== NULL
)
3027 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link
));
3031 escaped_urlPath
= escape(urlPath
);
3032 if (escaped_urlPath
== NULL
)
3034 WINE_ERR("couldn't escape url, out of memory\n");
3038 start_path
= get_start_exe_path();
3039 if (start_path
== NULL
)
3041 WINE_ERR("out of memory\n");
3045 ps
[0].ulKind
= PRSPEC_PROPID
;
3046 ps
[0].u
.propid
= PID_IS_ICONFILE
;
3047 ps
[1].ulKind
= PRSPEC_PROPID
;
3048 ps
[1].u
.propid
= PID_IS_ICONINDEX
;
3050 hr
= url
->lpVtbl
->QueryInterface(url
, &IID_IPropertySetStorage
, (void **) &pPropSetStg
);
3053 hr
= IPropertySetStorage_Open(pPropSetStg
, &FMTID_Intshcut
, STGM_READ
| STGM_SHARE_EXCLUSIVE
, &pPropStg
);
3056 hr
= IPropertyStorage_ReadMultiple(pPropStg
, 2, ps
, pv
);
3059 if (pv
[0].vt
== VT_LPWSTR
&& pv
[0].u
.pwszVal
&& pv
[0].u
.pwszVal
[0])
3062 icon_name
= extract_icon( pv
[0].u
.pwszVal
, pv
[1].u
.iVal
, NULL
, bWait
);
3064 WINE_TRACE("URL icon path: %s icon index: %d icon name: %s\n", wine_dbgstr_w(pv
[0].u
.pwszVal
), pv
[1].u
.iVal
, icon_name
);
3066 PropVariantClear(&pv
[0]);
3067 PropVariantClear(&pv
[1]);
3069 IPropertyStorage_Release(pPropStg
);
3071 IPropertySetStorage_Release(pPropSetStg
);
3074 /* fail - try once again after parent process exit */
3075 if( has_icon
&& !icon_name
)
3079 WINE_WARN("Unable to extract icon, deferring.\n");
3083 WINE_ERR("failed to extract icon from %s\n",
3084 wine_dbgstr_w( pv
[0].u
.pwszVal
));
3087 hSem
= CreateSemaphoreA( NULL
, 1, 1, "winemenubuilder_semaphore");
3088 if( WAIT_OBJECT_0
!= MsgWaitForMultipleObjects( 1, &hSem
, FALSE
, INFINITE
, QS_ALLINPUT
) )
3090 WINE_ERR("failed wait for semaphore\n");
3093 if (in_desktop_dir(csidl
))
3096 const char *lastEntry
;
3097 lastEntry
= strrchr(link_name
, '/');
3098 if (lastEntry
== NULL
)
3099 lastEntry
= link_name
;
3102 location
= heap_printf("%s/%s.desktop", xdg_desktop_dir
, lastEntry
);
3105 r
= !write_desktop_entry(NULL
, location
, lastEntry
, start_path
, escaped_urlPath
, NULL
, NULL
, icon_name
);
3107 chmod(location
, 0755);
3108 HeapFree(GetProcessHeap(), 0, location
);
3112 r
= !write_menu_entry(unix_link
, link_name
, start_path
, escaped_urlPath
, NULL
, NULL
, icon_name
);
3114 ReleaseSemaphore(hSem
, 1, NULL
);
3119 HeapFree( GetProcessHeap(), 0, icon_name
);
3120 HeapFree(GetProcessHeap(), 0, link_name
);
3121 CoTaskMemFree( urlPath
);
3122 HeapFree(GetProcessHeap(), 0, escaped_urlPath
);
3123 HeapFree(GetProcessHeap(), 0, unix_link
);
3127 static BOOL
WaitForParentProcess( void )
3129 PROCESSENTRY32 procentry
;
3130 HANDLE hsnapshot
= NULL
, hprocess
= NULL
;
3131 DWORD ourpid
= GetCurrentProcessId();
3132 BOOL ret
= FALSE
, rc
;
3134 WINE_TRACE("Waiting for parent process\n");
3135 if ((hsnapshot
= CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS
, 0 )) ==
3136 INVALID_HANDLE_VALUE
)
3138 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3142 procentry
.dwSize
= sizeof(PROCESSENTRY32
);
3143 rc
= Process32First( hsnapshot
, &procentry
);
3146 if (procentry
.th32ProcessID
== ourpid
) break;
3147 rc
= Process32Next( hsnapshot
, &procentry
);
3151 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid
);
3155 if ((hprocess
= OpenProcess( SYNCHRONIZE
, FALSE
, procentry
.th32ParentProcessID
)) ==
3158 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry
.th32ParentProcessID
,
3163 if (MsgWaitForMultipleObjects( 1, &hprocess
, FALSE
, INFINITE
, QS_ALLINPUT
) == WAIT_OBJECT_0
)
3166 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3169 if (hprocess
) CloseHandle( hprocess
);
3170 if (hsnapshot
) CloseHandle( hsnapshot
);
3174 static BOOL
Process_Link( LPCWSTR linkname
, BOOL bWait
)
3179 WCHAR fullname
[MAX_PATH
];
3182 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname
), bWait
);
3186 WINE_ERR("link name missing\n");
3190 len
=GetFullPathNameW( linkname
, MAX_PATH
, fullname
, NULL
);
3191 if (len
==0 || len
>MAX_PATH
)
3193 WINE_ERR("couldn't get full path of link file\n");
3197 r
= CoCreateInstance( &CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
3198 &IID_IShellLinkW
, (LPVOID
*) &sl
);
3201 WINE_ERR("No IID_IShellLink\n");
3205 r
= IShellLinkW_QueryInterface( sl
, &IID_IPersistFile
, (LPVOID
*) &pf
);
3208 WINE_ERR("No IID_IPersistFile\n");
3212 r
= IPersistFile_Load( pf
, fullname
, STGM_READ
);
3213 if( SUCCEEDED( r
) )
3215 /* If something fails (eg. Couldn't extract icon)
3216 * wait for parent process and try again
3218 if( ! InvokeShellLinker( sl
, fullname
, bWait
) && bWait
)
3220 WaitForParentProcess();
3221 InvokeShellLinker( sl
, fullname
, FALSE
);
3226 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname
));
3229 IPersistFile_Release( pf
);
3230 IShellLinkW_Release( sl
);
3235 static BOOL
Process_URL( LPCWSTR urlname
, BOOL bWait
)
3237 IUniformResourceLocatorW
*url
;
3240 WCHAR fullname
[MAX_PATH
];
3243 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname
), bWait
);
3247 WINE_ERR("URL name missing\n");
3251 len
=GetFullPathNameW( urlname
, MAX_PATH
, fullname
, NULL
);
3252 if (len
==0 || len
>MAX_PATH
)
3254 WINE_ERR("couldn't get full path of URL file\n");
3258 r
= CoCreateInstance( &CLSID_InternetShortcut
, NULL
, CLSCTX_INPROC_SERVER
,
3259 &IID_IUniformResourceLocatorW
, (LPVOID
*) &url
);
3262 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3266 r
= url
->lpVtbl
->QueryInterface( url
, &IID_IPersistFile
, (LPVOID
*) &pf
);
3269 WINE_ERR("No IID_IPersistFile\n");
3272 r
= IPersistFile_Load( pf
, fullname
, STGM_READ
);
3273 if( SUCCEEDED( r
) )
3275 /* If something fails (eg. Couldn't extract icon)
3276 * wait for parent process and try again
3278 if( ! InvokeShellLinkerForURL( url
, fullname
, bWait
) && bWait
)
3280 WaitForParentProcess();
3281 InvokeShellLinkerForURL( url
, fullname
, FALSE
);
3285 IPersistFile_Release( pf
);
3286 url
->lpVtbl
->Release( url
);
3291 static void RefreshFileTypeAssociations(void)
3294 char *mime_dir
= NULL
;
3295 char *packages_dir
= NULL
;
3296 char *applications_dir
= NULL
;
3299 hSem
= CreateSemaphoreA( NULL
, 1, 1, "winemenubuilder_semaphore");
3300 if( WAIT_OBJECT_0
!= MsgWaitForMultipleObjects( 1, &hSem
, FALSE
, INFINITE
, QS_ALLINPUT
) )
3302 WINE_ERR("failed wait for semaphore\n");
3308 mime_dir
= heap_printf("%s/mime", xdg_data_dir
);
3309 if (mime_dir
== NULL
)
3311 WINE_ERR("out of memory\n");
3314 create_directories(mime_dir
);
3316 packages_dir
= heap_printf("%s/packages", mime_dir
);
3317 if (packages_dir
== NULL
)
3319 WINE_ERR("out of memory\n");
3322 create_directories(packages_dir
);
3324 applications_dir
= heap_printf("%s/applications", xdg_data_dir
);
3325 if (applications_dir
== NULL
)
3327 WINE_ERR("out of memory\n");
3330 create_directories(applications_dir
);
3332 hasChanged
= generate_associations(xdg_data_dir
, packages_dir
, applications_dir
);
3333 hasChanged
|= cleanup_associations();
3336 const char *argv
[3];
3338 argv
[0] = "update-mime-database";
3341 _spawnvp( _P_DETACH
, argv
[0], argv
);
3343 argv
[0] = "update-desktop-database";
3344 argv
[1] = applications_dir
;
3345 _spawnvp( _P_DETACH
, argv
[0], argv
);
3351 ReleaseSemaphore(hSem
, 1, NULL
);
3354 HeapFree(GetProcessHeap(), 0, mime_dir
);
3355 HeapFree(GetProcessHeap(), 0, packages_dir
);
3356 HeapFree(GetProcessHeap(), 0, applications_dir
);
3359 static void cleanup_menus(void)
3363 hkey
= open_menus_reg_key();
3367 LSTATUS lret
= ERROR_SUCCESS
;
3368 for (i
= 0; lret
== ERROR_SUCCESS
; )
3370 WCHAR
*value
= NULL
;
3372 DWORD valueSize
= 4096;
3373 DWORD dataSize
= 4096;
3376 lret
= ERROR_OUTOFMEMORY
;
3377 value
= HeapAlloc(GetProcessHeap(), 0, valueSize
* sizeof(WCHAR
));
3380 data
= HeapAlloc(GetProcessHeap(), 0, dataSize
* sizeof(WCHAR
));
3383 lret
= RegEnumValueW(hkey
, i
, value
, &valueSize
, NULL
, NULL
, (BYTE
*)data
, &dataSize
);
3384 if (lret
!= ERROR_MORE_DATA
)
3388 HeapFree(GetProcessHeap(), 0, value
);
3389 HeapFree(GetProcessHeap(), 0, data
);
3390 value
= data
= NULL
;
3392 if (lret
== ERROR_SUCCESS
)
3396 unix_file
= wchars_to_unix_chars(value
);
3397 windows_file
= wchars_to_unix_chars(data
);
3398 if (unix_file
!= NULL
&& windows_file
!= NULL
)
3400 struct stat filestats
;
3401 if (stat(windows_file
, &filestats
) < 0 && errno
== ENOENT
)
3403 WINE_TRACE("removing menu related file %s\n", unix_file
);
3405 RegDeleteValueW(hkey
, value
);
3412 WINE_ERR("out of memory enumerating menus\n");
3413 lret
= ERROR_OUTOFMEMORY
;
3415 HeapFree(GetProcessHeap(), 0, unix_file
);
3416 HeapFree(GetProcessHeap(), 0, windows_file
);
3418 else if (lret
!= ERROR_NO_MORE_ITEMS
)
3419 WINE_ERR("error %d reading registry\n", lret
);
3420 HeapFree(GetProcessHeap(), 0, value
);
3421 HeapFree(GetProcessHeap(), 0, data
);
3426 WINE_ERR("error opening registry key, menu cleanup failed\n");
3429 static void thumbnail_lnk(LPCWSTR lnkPath
, LPCWSTR outputPath
)
3431 char *utf8lnkPath
= NULL
;
3432 char *utf8OutputPath
= NULL
;
3433 WCHAR
*winLnkPath
= NULL
;
3434 IShellLinkW
*shellLink
= NULL
;
3435 IPersistFile
*persistFile
= NULL
;
3436 WCHAR szTmp
[MAX_PATH
];
3437 WCHAR szPath
[MAX_PATH
];
3438 WCHAR szArgs
[INFOTIPSIZE
];
3439 WCHAR szIconPath
[MAX_PATH
];
3441 IStream
*stream
= NULL
;
3442 ICONDIRENTRY
*pIconDirEntries
= NULL
;
3446 utf8lnkPath
= wchars_to_utf8_chars(lnkPath
);
3447 if (utf8lnkPath
== NULL
)
3449 WINE_ERR("out of memory converting paths\n");
3453 utf8OutputPath
= wchars_to_utf8_chars(outputPath
);
3454 if (utf8OutputPath
== NULL
)
3456 WINE_ERR("out of memory converting paths\n");
3460 winLnkPath
= wine_get_dos_file_name(utf8lnkPath
);
3461 if (winLnkPath
== NULL
)
3463 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath
);
3467 hr
= CoCreateInstance(&CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
3468 &IID_IShellLinkW
, (LPVOID
*)&shellLink
);
3471 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr
);
3475 hr
= IShellLinkW_QueryInterface(shellLink
, &IID_IPersistFile
, (LPVOID
)&persistFile
);
3478 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr
);
3482 hr
= IPersistFile_Load(persistFile
, winLnkPath
, STGM_READ
);
3485 WINE_ERR("could not read .lnk, error 0x%08X\n", hr
);
3489 get_cmdline(shellLink
, szTmp
, MAX_PATH
, szArgs
, INFOTIPSIZE
);
3490 ExpandEnvironmentStringsW(szTmp
, szPath
, MAX_PATH
);
3492 IShellLinkW_GetIconLocation(shellLink
, szTmp
, MAX_PATH
, &iconId
);
3493 ExpandEnvironmentStringsW(szTmp
, szIconPath
, MAX_PATH
);
3497 LPITEMIDLIST pidl
= NULL
;
3498 IShellLinkW_GetIDList(shellLink
, &pidl
);
3499 if (pidl
&& SHGetPathFromIDListW(pidl
, szPath
))
3500 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath
));
3505 hr
= open_icon(szIconPath
, iconId
, FALSE
, &stream
, &pIconDirEntries
, &numEntries
);
3507 hr
= write_native_icon(stream
, pIconDirEntries
, numEntries
, utf8OutputPath
, NULL
);
3511 hr
= open_icon(szPath
, iconId
, FALSE
, &stream
, &pIconDirEntries
, &numEntries
);
3513 hr
= write_native_icon(stream
, pIconDirEntries
, numEntries
, utf8OutputPath
, NULL
);
3517 HeapFree(GetProcessHeap(), 0, utf8lnkPath
);
3518 HeapFree(GetProcessHeap(), 0, utf8OutputPath
);
3519 HeapFree(GetProcessHeap(), 0, winLnkPath
);
3520 if (shellLink
!= NULL
)
3521 IShellLinkW_Release(shellLink
);
3522 if (persistFile
!= NULL
)
3523 IPersistFile_Release(persistFile
);
3525 IStream_Release(stream
);
3526 HeapFree(GetProcessHeap(), 0, pIconDirEntries
);
3529 static WCHAR
*next_token( LPWSTR
*p
)
3531 LPWSTR token
= NULL
, t
= *p
;
3536 while( t
&& !token
)
3544 /* unquote the token */
3546 t
= strchrW( token
, '"' );
3555 t
= strchrW( token
, ' ' );
3565 static BOOL
init_xdg(void)
3567 WCHAR shellDesktopPath
[MAX_PATH
];
3568 HRESULT hr
= SHGetFolderPathW(NULL
, CSIDL_DESKTOP
, NULL
, SHGFP_TYPE_CURRENT
, shellDesktopPath
);
3570 xdg_desktop_dir
= wine_get_unix_file_name(shellDesktopPath
);
3571 if (xdg_desktop_dir
== NULL
)
3573 WINE_ERR("error looking up the desktop directory\n");
3577 if (getenv("XDG_CONFIG_HOME"))
3578 xdg_config_dir
= heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3580 xdg_config_dir
= heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3583 create_directories(xdg_config_dir
);
3584 if (getenv("XDG_DATA_HOME"))
3585 xdg_data_dir
= strdupA(getenv("XDG_DATA_HOME"));
3587 xdg_data_dir
= heap_printf("%s/.local/share", getenv("HOME"));
3591 create_directories(xdg_data_dir
);
3592 buffer
= heap_printf("%s/desktop-directories", xdg_data_dir
);
3595 mkdir(buffer
, 0777);
3596 HeapFree(GetProcessHeap(), 0, buffer
);
3600 HeapFree(GetProcessHeap(), 0, xdg_config_dir
);
3602 WINE_ERR("out of memory\n");
3606 /***********************************************************************
3610 int PASCAL
wWinMain (HINSTANCE hInstance
, HINSTANCE prev
, LPWSTR cmdline
, int show
)
3612 static const WCHAR dash_aW
[] = {'-','a',0};
3613 static const WCHAR dash_rW
[] = {'-','r',0};
3614 static const WCHAR dash_tW
[] = {'-','t',0};
3615 static const WCHAR dash_uW
[] = {'-','u',0};
3616 static const WCHAR dash_wW
[] = {'-','w',0};
3618 LPWSTR token
= NULL
, p
;
3627 hr
= CoInitialize(NULL
);
3630 WINE_ERR("could not initialize COM, error 0x%08X\n", hr
);
3634 for( p
= cmdline
; p
&& *p
; )
3636 token
= next_token( &p
);
3639 if( !strcmpW( token
, dash_aW
) )
3641 RefreshFileTypeAssociations();
3644 if( !strcmpW( token
, dash_rW
) )
3649 if( !strcmpW( token
, dash_wW
) )
3651 else if ( !strcmpW( token
, dash_uW
) )
3653 else if ( !strcmpW( token
, dash_tW
) )
3655 WCHAR
*lnkFile
= next_token( &p
);
3658 WCHAR
*outputFile
= next_token( &p
);
3660 thumbnail_lnk(lnkFile
, outputFile
);
3663 else if( token
[0] == '-' )
3665 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token
) );
3672 bRet
= Process_URL( token
, bWait
);
3674 bRet
= Process_Link( token
, bWait
);
3677 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token
) );