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 #define IS_OPTION_TRUE(ch) \
108 ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
110 /* link file formats */
112 #include "pshpack1.h"
131 GRPICONDIRENTRY idEntries
[1];
170 #define NE_RSCTYPE_ICON 0x8003
171 #define NE_RSCTYPE_GROUP_ICON 0x800e
189 struct rb_string_entry
192 struct wine_rb_entry entry
;
195 DEFINE_GUID(CLSID_WICIcnsEncoder
, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
197 static char *xdg_config_dir
;
198 static char *xdg_data_dir
;
199 static char *xdg_desktop_dir
;
202 /* Utility routines */
203 static unsigned short crc16(const char* string
)
205 unsigned short crc
= 0;
208 for (i
= 0; string
[i
] != 0; i
++)
211 for (j
= 0; j
< 8; c
>>= 1, j
++)
213 xor_poly
= (c
^ crc
) & 1;
222 static char *strdupA( const char *str
)
226 if (!str
) return NULL
;
227 if ((ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 ))) strcpy( ret
, str
);
231 static char* heap_printf(const char *format
, ...)
240 buffer
= HeapAlloc(GetProcessHeap(), 0, size
);
243 va_start(args
, format
);
244 n
= vsnprintf(buffer
, size
, format
, args
);
252 HeapFree(GetProcessHeap(), 0, buffer
);
255 if (!buffer
) return NULL
;
256 ret
= HeapReAlloc(GetProcessHeap(), 0, buffer
, strlen(buffer
) + 1 );
257 if (!ret
) ret
= buffer
;
261 static int winemenubuilder_rb_string_compare(const void *key
, const struct wine_rb_entry
*entry
)
263 const struct rb_string_entry
*t
= WINE_RB_ENTRY_VALUE(entry
, const struct rb_string_entry
, entry
);
265 return strcmp((char*)key
, t
->string
);
268 static void winemenubuilder_rb_destroy(struct wine_rb_entry
*entry
, void *context
)
270 struct rb_string_entry
*t
= WINE_RB_ENTRY_VALUE(entry
, struct rb_string_entry
, entry
);
271 HeapFree(GetProcessHeap(), 0, t
->string
);
272 HeapFree(GetProcessHeap(), 0, t
);
275 static void write_xml_text(FILE *file
, const char *text
)
278 for (i
= 0; text
[i
]; i
++)
281 fputs("&", file
);
282 else if (text
[i
] == '<')
284 else if (text
[i
] == '>')
286 else if (text
[i
] == '\'')
287 fputs("'", file
);
288 else if (text
[i
] == '"')
289 fputs(""", file
);
291 fputc(text
[i
], file
);
295 static BOOL
create_directories(char *directory
)
300 for (i
= 0; directory
[i
]; i
++)
302 if (i
> 0 && directory
[i
] == '/')
305 mkdir(directory
, 0777);
309 if (mkdir(directory
, 0777) && errno
!= EEXIST
)
315 static char* wchars_to_utf8_chars(LPCWSTR string
)
318 INT size
= WideCharToMultiByte(CP_UTF8
, 0, string
, -1, NULL
, 0, NULL
, NULL
);
319 ret
= HeapAlloc(GetProcessHeap(), 0, size
);
321 WideCharToMultiByte(CP_UTF8
, 0, string
, -1, ret
, size
, NULL
, NULL
);
325 static char* wchars_to_unix_chars(LPCWSTR string
)
328 INT size
= WideCharToMultiByte(CP_UNIXCP
, 0, string
, -1, NULL
, 0, NULL
, NULL
);
329 ret
= HeapAlloc(GetProcessHeap(), 0, size
);
331 WideCharToMultiByte(CP_UNIXCP
, 0, string
, -1, ret
, size
, NULL
, NULL
);
335 static WCHAR
* utf8_chars_to_wchars(LPCSTR string
)
338 INT size
= MultiByteToWideChar(CP_UTF8
, 0, string
, -1, NULL
, 0);
339 ret
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
341 MultiByteToWideChar(CP_UTF8
, 0, string
, -1, ret
, size
);
345 /* Icon extraction routines
347 * FIXME: should use PrivateExtractIcons and friends
348 * FIXME: should not use stdio
351 static HRESULT
convert_to_native_icon(IStream
*icoFile
, int *indices
, int numIndices
,
352 const CLSID
*outputFormat
, const char *outputFileName
, LPCWSTR commentW
)
354 WCHAR
*dosOutputFileName
= NULL
;
355 IWICImagingFactory
*factory
= NULL
;
356 IWICBitmapDecoder
*decoder
= NULL
;
357 IWICBitmapEncoder
*encoder
= NULL
;
358 IWICBitmapScaler
*scaler
= NULL
;
359 IStream
*outputFile
= NULL
;
363 dosOutputFileName
= wine_get_dos_file_name(outputFileName
);
364 if (dosOutputFileName
== NULL
)
366 WINE_ERR("error converting %s to DOS file name\n", outputFileName
);
369 hr
= CoCreateInstance(&CLSID_WICImagingFactory
, NULL
, CLSCTX_INPROC_SERVER
,
370 &IID_IWICImagingFactory
, (void**)&factory
);
373 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr
);
376 hr
= IWICImagingFactory_CreateDecoderFromStream(factory
, icoFile
, NULL
,
377 WICDecodeMetadataCacheOnDemand
, &decoder
);
380 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr
);
383 if (IsEqualCLSID(outputFormat
,&CLSID_WICIcnsEncoder
))
385 hr
= IWICImagingFactory_CreateBitmapScaler(factory
, &scaler
);
388 WINE_WARN("error 0x%08X creating IWICBitmapScaler\n", hr
);
391 hr
= CoCreateInstance(outputFormat
, NULL
, CLSCTX_INPROC_SERVER
,
392 &IID_IWICBitmapEncoder
, (void**)&encoder
);
395 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr
);
398 hr
= SHCreateStreamOnFileW(dosOutputFileName
, STGM_CREATE
| STGM_WRITE
, &outputFile
);
401 WINE_ERR("error 0x%08X creating output file %s\n", hr
, wine_dbgstr_w(dosOutputFileName
));
404 hr
= IWICBitmapEncoder_Initialize(encoder
, outputFile
, GENERIC_WRITE
);
407 WINE_ERR("error 0x%08X initializing encoder\n", hr
);
411 for (i
= 0; i
< numIndices
; i
++)
413 IWICBitmapFrameDecode
*sourceFrame
= NULL
;
414 IWICBitmapSource
*sourceBitmap
= NULL
;
415 IWICBitmapFrameEncode
*dstFrame
= NULL
;
416 IPropertyBag2
*options
= NULL
;
419 hr
= IWICBitmapDecoder_GetFrame(decoder
, indices
[i
], &sourceFrame
);
422 WINE_ERR("error 0x%08X getting frame %d\n", hr
, indices
[i
]);
425 hr
= WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA
, (IWICBitmapSource
*)sourceFrame
, &sourceBitmap
);
428 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr
);
433 IWICBitmapSource_GetSize(sourceBitmap
, &width
, &height
);
434 if (width
== 64) /* Classic Mode */
436 hr
= IWICBitmapScaler_Initialize( scaler
, sourceBitmap
, 128, 128,
437 WICBitmapInterpolationModeNearestNeighbor
);
439 WINE_ERR("error 0x%08X scaling bitmap\n", hr
);
442 IWICBitmapSource_Release(sourceBitmap
);
443 IWICBitmapScaler_QueryInterface(scaler
, &IID_IWICBitmapSource
, (LPVOID
)&sourceBitmap
);
447 hr
= IWICBitmapEncoder_CreateNewFrame(encoder
, &dstFrame
, &options
);
450 WINE_ERR("error 0x%08X creating encoder frame\n", hr
);
453 hr
= IWICBitmapFrameEncode_Initialize(dstFrame
, options
);
456 WINE_ERR("error 0x%08X initializing encoder frame\n", hr
);
459 hr
= IWICBitmapSource_GetSize(sourceBitmap
, &width
, &height
);
462 WINE_ERR("error 0x%08X getting source bitmap size\n", hr
);
465 hr
= IWICBitmapFrameEncode_SetSize(dstFrame
, width
, height
);
468 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr
);
471 hr
= IWICBitmapFrameEncode_SetResolution(dstFrame
, 96, 96);
474 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr
);
477 hr
= IWICBitmapFrameEncode_WriteSource(dstFrame
, sourceBitmap
, NULL
);
480 WINE_ERR("error 0x%08X copying bitmaps\n", hr
);
483 hr
= IWICBitmapFrameEncode_Commit(dstFrame
);
486 WINE_ERR("error 0x%08X committing frame\n", hr
);
491 IWICBitmapFrameDecode_Release(sourceFrame
);
493 IWICBitmapSource_Release(sourceBitmap
);
495 IWICBitmapFrameEncode_Release(dstFrame
);
497 IPropertyBag2_Release(options
);
500 hr
= IWICBitmapEncoder_Commit(encoder
);
503 WINE_ERR("error 0x%08X committing encoder\n", hr
);
508 HeapFree(GetProcessHeap(), 0, dosOutputFileName
);
510 IWICImagingFactory_Release(factory
);
512 IWICBitmapDecoder_Release(decoder
);
514 IWICBitmapScaler_Release(scaler
);
516 IWICBitmapEncoder_Release(encoder
);
518 IStream_Release(outputFile
);
525 NE_TYPEINFO
*iconResources
;
526 WORD alignmentShiftCount
;
529 static int populate_module16_icons(struct IconData16
*iconData16
, GRPICONDIR
*grpIconDir
, ICONDIRENTRY
*iconDirEntries
, BYTE
*icons
, SIZE_T
*iconOffset
)
532 int validEntries
= 0;
534 for (i
= 0; i
< grpIconDir
->idCount
; i
++)
536 BYTE
*iconPtr
= (BYTE
*)iconData16
->iconResources
;
537 NE_NAMEINFO
*matchingIcon
= NULL
;
538 iconPtr
+= sizeof(NE_TYPEINFO
);
539 for (j
= 0; j
< iconData16
->iconResources
->count
; j
++)
541 NE_NAMEINFO
*iconInfo
= (NE_NAMEINFO
*)iconPtr
;
542 if ((((BYTE
*)iconPtr
) + sizeof(NE_NAMEINFO
)) > (iconData16
->fileBytes
+ iconData16
->fileSize
))
544 WINE_WARN("file too small for icon NE_NAMEINFO\n");
547 if (iconInfo
->id
== (0x8000 | grpIconDir
->idEntries
[i
].nID
))
549 matchingIcon
= iconInfo
;
552 iconPtr
+= sizeof(NE_NAMEINFO
);
555 if (matchingIcon
== NULL
)
557 if (((matchingIcon
->offset
<< iconData16
->alignmentShiftCount
) + grpIconDir
->idEntries
[i
].dwBytesInRes
) > iconData16
->fileSize
)
559 WINE_WARN("file too small for icon contents\n");
563 iconDirEntries
[validEntries
].bWidth
= grpIconDir
->idEntries
[i
].bWidth
;
564 iconDirEntries
[validEntries
].bHeight
= grpIconDir
->idEntries
[i
].bHeight
;
565 iconDirEntries
[validEntries
].bColorCount
= grpIconDir
->idEntries
[i
].bColorCount
;
566 iconDirEntries
[validEntries
].bReserved
= grpIconDir
->idEntries
[i
].bReserved
;
567 iconDirEntries
[validEntries
].wPlanes
= grpIconDir
->idEntries
[i
].wPlanes
;
568 iconDirEntries
[validEntries
].wBitCount
= grpIconDir
->idEntries
[i
].wBitCount
;
569 iconDirEntries
[validEntries
].dwBytesInRes
= grpIconDir
->idEntries
[i
].dwBytesInRes
;
570 iconDirEntries
[validEntries
].dwImageOffset
= *iconOffset
;
572 memcpy(&icons
[*iconOffset
], &iconData16
->fileBytes
[matchingIcon
->offset
<< iconData16
->alignmentShiftCount
], grpIconDir
->idEntries
[i
].dwBytesInRes
);
573 *iconOffset
+= grpIconDir
->idEntries
[i
].dwBytesInRes
;
578 static int populate_module_icons(HMODULE hModule
, GRPICONDIR
*grpIconDir
, ICONDIRENTRY
*iconDirEntries
, BYTE
*icons
, SIZE_T
*iconOffset
)
581 int validEntries
= 0;
583 for (i
= 0; i
< grpIconDir
->idCount
; i
++)
586 LPCWSTR lpName
= MAKEINTRESOURCEW(grpIconDir
->idEntries
[i
].nID
);
587 if ((hResInfo
= FindResourceW(hModule
, lpName
, (LPCWSTR
)RT_ICON
)))
590 if ((hResData
= LoadResource(hModule
, hResInfo
)))
593 DWORD size
= min( grpIconDir
->idEntries
[i
].dwBytesInRes
, ((IMAGE_RESOURCE_DATA_ENTRY
*)hResInfo
)->Size
);
594 if ((pIcon
= LockResource(hResData
)))
596 iconDirEntries
[validEntries
].bWidth
= grpIconDir
->idEntries
[i
].bWidth
;
597 iconDirEntries
[validEntries
].bHeight
= grpIconDir
->idEntries
[i
].bHeight
;
598 iconDirEntries
[validEntries
].bColorCount
= grpIconDir
->idEntries
[i
].bColorCount
;
599 iconDirEntries
[validEntries
].bReserved
= grpIconDir
->idEntries
[i
].bReserved
;
600 iconDirEntries
[validEntries
].wPlanes
= grpIconDir
->idEntries
[i
].wPlanes
;
601 iconDirEntries
[validEntries
].wBitCount
= grpIconDir
->idEntries
[i
].wBitCount
;
602 iconDirEntries
[validEntries
].dwBytesInRes
= size
;
603 iconDirEntries
[validEntries
].dwImageOffset
= *iconOffset
;
605 memcpy(&icons
[*iconOffset
], pIcon
, size
);
608 FreeResource(hResData
);
615 static IStream
*add_module_icons_to_stream(struct IconData16
*iconData16
, HMODULE hModule
, GRPICONDIR
*grpIconDir
)
618 SIZE_T iconsSize
= 0;
620 ICONDIRENTRY
*iconDirEntries
= NULL
;
621 IStream
*stream
= NULL
;
626 int validEntries
= 0;
629 for (i
= 0; i
< grpIconDir
->idCount
; i
++)
630 iconsSize
+= grpIconDir
->idEntries
[i
].dwBytesInRes
;
631 icons
= HeapAlloc(GetProcessHeap(), 0, iconsSize
);
634 WINE_ERR("out of memory allocating icon\n");
638 iconDirEntries
= HeapAlloc(GetProcessHeap(), 0, grpIconDir
->idCount
*sizeof(ICONDIRENTRY
));
639 if (iconDirEntries
== NULL
)
641 WINE_ERR("out of memory allocating icon dir entries\n");
645 hr
= CreateStreamOnHGlobal(NULL
, TRUE
, &stream
);
648 WINE_ERR("error creating icon stream\n");
654 validEntries
= populate_module16_icons(iconData16
, grpIconDir
, iconDirEntries
, icons
, &iconOffset
);
656 validEntries
= populate_module_icons(hModule
, grpIconDir
, iconDirEntries
, icons
, &iconOffset
);
658 if (validEntries
== 0)
660 WINE_ERR("no valid icon entries\n");
664 iconDir
.idReserved
= 0;
666 iconDir
.idCount
= validEntries
;
667 hr
= IStream_Write(stream
, &iconDir
, sizeof(iconDir
), &bytesWritten
);
668 if (FAILED(hr
) || bytesWritten
!= sizeof(iconDir
))
670 WINE_ERR("error 0x%08X writing icon stream\n", hr
);
673 for (i
= 0; i
< validEntries
; i
++)
674 iconDirEntries
[i
].dwImageOffset
+= sizeof(ICONDIR
) + validEntries
*sizeof(ICONDIRENTRY
);
675 hr
= IStream_Write(stream
, iconDirEntries
, validEntries
*sizeof(ICONDIRENTRY
), &bytesWritten
);
676 if (FAILED(hr
) || bytesWritten
!= validEntries
*sizeof(ICONDIRENTRY
))
678 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr
);
681 hr
= IStream_Write(stream
, icons
, iconOffset
, &bytesWritten
);
682 if (FAILED(hr
) || bytesWritten
!= iconOffset
)
684 WINE_ERR("error 0x%08X writing icon images to stream\n", hr
);
688 hr
= IStream_Seek(stream
, zero
, STREAM_SEEK_SET
, NULL
);
691 HeapFree(GetProcessHeap(), 0, icons
);
692 HeapFree(GetProcessHeap(), 0, iconDirEntries
);
693 if (FAILED(hr
) && stream
!= NULL
)
695 IStream_Release(stream
);
701 static HRESULT
open_module16_icon(LPCWSTR szFileName
, int nIndex
, IStream
**ppStream
)
703 HANDLE hFile
= INVALID_HANDLE_VALUE
;
704 HANDLE hFileMapping
= NULL
;
706 BYTE
*fileBytes
= NULL
;
707 IMAGE_DOS_HEADER
*dosHeader
;
708 IMAGE_OS2_HEADER
*neHeader
;
710 NE_TYPEINFO
*iconGroupResources
;
711 NE_TYPEINFO
*iconResources
;
712 NE_NAMEINFO
*iconDirPtr
;
714 WORD alignmentShiftCount
;
715 struct IconData16 iconData16
;
718 hFile
= CreateFileW(szFileName
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
,
719 OPEN_EXISTING
, FILE_FLAG_RANDOM_ACCESS
, NULL
);
720 if (hFile
== INVALID_HANDLE_VALUE
)
722 WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName
), GetLastError());
726 hFileMapping
= CreateFileMappingW(hFile
, NULL
, PAGE_READONLY
| SEC_COMMIT
, 0, 0, NULL
);
727 if (hFileMapping
== NULL
)
729 WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
733 fileSize
= GetFileSize(hFile
, NULL
);
735 fileBytes
= MapViewOfFile(hFileMapping
, FILE_MAP_READ
, 0, 0, 0);
736 if (fileBytes
== NULL
)
738 WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
742 dosHeader
= (IMAGE_DOS_HEADER
*)fileBytes
;
743 if (sizeof(IMAGE_DOS_HEADER
) >= fileSize
|| dosHeader
->e_magic
!= IMAGE_DOS_SIGNATURE
)
745 WINE_WARN("file too small for MZ header\n");
749 neHeader
= (IMAGE_OS2_HEADER
*)(fileBytes
+ dosHeader
->e_lfanew
);
750 if ((((BYTE
*)neHeader
) + sizeof(IMAGE_OS2_HEADER
)) > (fileBytes
+ fileSize
) ||
751 neHeader
->ne_magic
!= IMAGE_OS2_SIGNATURE
)
753 WINE_WARN("file too small for NE header\n");
757 rsrcTab
= ((BYTE
*)neHeader
) + neHeader
->ne_rsrctab
;
758 if ((rsrcTab
+ 2) > (fileBytes
+ fileSize
))
760 WINE_WARN("file too small for resource table\n");
764 alignmentShiftCount
= *(WORD
*)rsrcTab
;
766 iconGroupResources
= NULL
;
767 iconResources
= NULL
;
770 NE_TYPEINFO
*neTypeInfo
= (NE_TYPEINFO
*)rsrcTab
;
771 if ((rsrcTab
+ sizeof(NE_TYPEINFO
)) > (fileBytes
+ fileSize
))
773 WINE_WARN("file too small for resource table\n");
776 if (neTypeInfo
->type_id
== 0)
778 else if (neTypeInfo
->type_id
== NE_RSCTYPE_GROUP_ICON
)
779 iconGroupResources
= neTypeInfo
;
780 else if (neTypeInfo
->type_id
== NE_RSCTYPE_ICON
)
781 iconResources
= neTypeInfo
;
782 rsrcTab
+= sizeof(NE_TYPEINFO
) + neTypeInfo
->count
*sizeof(NE_NAMEINFO
);
784 if (iconGroupResources
== NULL
)
786 WINE_WARN("no group icon resource type found\n");
789 if (iconResources
== NULL
)
791 WINE_WARN("no icon resource type found\n");
795 if (nIndex
>= iconGroupResources
->count
)
797 WINE_WARN("icon index out of range\n");
801 iconDirPtr
= (NE_NAMEINFO
*)(((BYTE
*)iconGroupResources
) + sizeof(NE_TYPEINFO
) + nIndex
*sizeof(NE_NAMEINFO
));
802 if ((((BYTE
*)iconDirPtr
) + sizeof(NE_NAMEINFO
)) > (fileBytes
+ fileSize
))
804 WINE_WARN("file too small for icon group NE_NAMEINFO\n");
807 iconDir
= (GRPICONDIR
*)(fileBytes
+ (iconDirPtr
->offset
<< alignmentShiftCount
));
808 if ((((BYTE
*)iconDir
) + sizeof(GRPICONDIR
) + iconDir
->idCount
*sizeof(GRPICONDIRENTRY
)) > (fileBytes
+ fileSize
))
810 WINE_WARN("file too small for GRPICONDIR\n");
814 iconData16
.fileBytes
= fileBytes
;
815 iconData16
.fileSize
= fileSize
;
816 iconData16
.iconResources
= iconResources
;
817 iconData16
.alignmentShiftCount
= alignmentShiftCount
;
818 *ppStream
= add_module_icons_to_stream(&iconData16
, NULL
, iconDir
);
823 if (hFile
!= INVALID_HANDLE_VALUE
)
825 if (hFileMapping
!= NULL
)
826 CloseHandle(hFileMapping
);
827 if (fileBytes
!= NULL
)
828 UnmapViewOfFile(fileBytes
);
832 static BOOL CALLBACK
EnumResNameProc(HMODULE hModule
, LPCWSTR lpszType
, LPWSTR lpszName
, LONG_PTR lParam
)
834 ENUMRESSTRUCT
*sEnumRes
= (ENUMRESSTRUCT
*) lParam
;
836 if (!sEnumRes
->nIndex
--)
838 *sEnumRes
->pResInfo
= FindResourceW(hModule
, lpszName
, (LPCWSTR
)RT_GROUP_ICON
);
845 static HRESULT
open_module_icon(LPCWSTR szFileName
, int nIndex
, IStream
**ppStream
)
850 GRPICONDIR
*pIconDir
;
851 ENUMRESSTRUCT sEnumRes
;
854 hModule
= LoadLibraryExW(szFileName
, 0, LOAD_LIBRARY_AS_DATAFILE
);
857 if (GetLastError() == ERROR_BAD_EXE_FORMAT
)
858 return open_module16_icon(szFileName
, nIndex
, ppStream
);
861 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
862 wine_dbgstr_w(szFileName
), GetLastError());
863 return HRESULT_FROM_WIN32(GetLastError());
869 hResInfo
= FindResourceW(hModule
, MAKEINTRESOURCEW(-nIndex
), (LPCWSTR
)RT_GROUP_ICON
);
870 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
871 wine_dbgstr_w(szFileName
), hResInfo
, GetLastError());
876 sEnumRes
.pResInfo
= &hResInfo
;
877 sEnumRes
.nIndex
= nIndex
;
878 if (!EnumResourceNamesW(hModule
, (LPCWSTR
)RT_GROUP_ICON
,
879 EnumResNameProc
, (LONG_PTR
)&sEnumRes
) &&
880 sEnumRes
.nIndex
!= -1)
882 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
888 if ((hResData
= LoadResource(hModule
, hResInfo
)))
890 if ((pIconDir
= LockResource(hResData
)))
892 *ppStream
= add_module_icons_to_stream(0, hModule
, pIconDir
);
897 FreeResource(hResData
);
902 WINE_WARN("found no icon\n");
903 FreeLibrary(hModule
);
904 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND
);
907 FreeLibrary(hModule
);
911 static HRESULT
read_ico_direntries(IStream
*icoStream
, ICONDIRENTRY
**ppIconDirEntries
, int *numEntries
)
917 *ppIconDirEntries
= NULL
;
919 hr
= IStream_Read(icoStream
, &iconDir
, sizeof(ICONDIR
), &bytesRead
);
920 if (FAILED(hr
) || bytesRead
!= sizeof(ICONDIR
) ||
921 (iconDir
.idReserved
!= 0) || (iconDir
.idType
!= 1))
923 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr
, bytesRead
);
927 *numEntries
= iconDir
.idCount
;
929 if ((*ppIconDirEntries
= HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY
)*iconDir
.idCount
)) == NULL
)
934 hr
= IStream_Read(icoStream
, *ppIconDirEntries
, sizeof(ICONDIRENTRY
)*iconDir
.idCount
, &bytesRead
);
935 if (FAILED(hr
) || bytesRead
!= sizeof(ICONDIRENTRY
)*iconDir
.idCount
)
937 if (SUCCEEDED(hr
)) hr
= E_FAIL
;
943 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries
);
947 static HRESULT
validate_ico(IStream
**ppStream
, ICONDIRENTRY
**ppIconDirEntries
, int *numEntries
)
951 hr
= read_ico_direntries(*ppStream
, ppIconDirEntries
, numEntries
);
956 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries
);
957 *ppIconDirEntries
= NULL
;
959 IStream_Release(*ppStream
);
964 static HRESULT
write_native_icon(IStream
*iconStream
, ICONDIRENTRY
*pIconDirEntry
,
965 int numEntries
, const char *icon_name
, LPCWSTR szFileName
)
967 int nMax
= 0, nMaxBits
= 0;
970 LARGE_INTEGER position
;
973 for (i
= 0; i
< numEntries
; i
++)
975 WINE_TRACE("[%d]: %d x %d @ %d\n", i
, pIconDirEntry
[i
].bWidth
, pIconDirEntry
[i
].bHeight
, pIconDirEntry
[i
].wBitCount
);
976 if (pIconDirEntry
[i
].wBitCount
>= nMaxBits
&&
977 (pIconDirEntry
[i
].bHeight
* pIconDirEntry
[i
].bWidth
) >= nMax
)
980 nMax
= pIconDirEntry
[i
].bHeight
* pIconDirEntry
[i
].bWidth
;
981 nMaxBits
= pIconDirEntry
[i
].wBitCount
;
984 WINE_TRACE("Selected: %d\n", nIndex
);
986 position
.QuadPart
= 0;
987 hr
= IStream_Seek(iconStream
, position
, STREAM_SEEK_SET
, NULL
);
988 if (FAILED(hr
)) return hr
;
989 return convert_to_native_icon(iconStream
, &nIndex
, 1, &CLSID_WICPngEncoder
, icon_name
, szFileName
);
992 static WCHAR
* assoc_query(ASSOCSTR assocStr
, LPCWSTR name
, LPCWSTR extra
)
997 hr
= AssocQueryStringW(0, assocStr
, name
, extra
, NULL
, &size
);
1000 value
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
1003 hr
= AssocQueryStringW(0, assocStr
, name
, extra
, value
, &size
);
1006 HeapFree(GetProcessHeap(), 0, value
);
1014 static HRESULT
open_file_type_icon(LPCWSTR szFileName
, IStream
**ppStream
)
1016 static const WCHAR openW
[] = {'o','p','e','n',0};
1020 WCHAR
*executable
= NULL
;
1022 HRESULT hr
= HRESULT_FROM_WIN32(ERROR_NOT_FOUND
);
1024 extension
= strrchrW(szFileName
, '.');
1025 if (extension
== NULL
)
1028 icon
= assoc_query(ASSOCSTR_DEFAULTICON
, extension
, NULL
);
1031 comma
= strrchrW(icon
, ',');
1035 index
= atoiW(comma
+ 1);
1037 hr
= open_module_icon(icon
, index
, ppStream
);
1041 executable
= assoc_query(ASSOCSTR_EXECUTABLE
, extension
, openW
);
1043 hr
= open_module_icon(executable
, 0, ppStream
);
1047 HeapFree(GetProcessHeap(), 0, icon
);
1048 HeapFree(GetProcessHeap(), 0, executable
);
1052 static HRESULT
open_default_icon(IStream
**ppStream
)
1054 static const WCHAR user32W
[] = {'u','s','e','r','3','2',0};
1056 return open_module_icon(user32W
, -(INT_PTR
)IDI_WINLOGO
, ppStream
);
1059 static HRESULT
open_icon(LPCWSTR filename
, int index
, BOOL bWait
, IStream
**ppStream
, ICONDIRENTRY
**ppIconDirEntries
, int *numEntries
)
1063 hr
= open_module_icon(filename
, index
, ppStream
);
1066 if(bWait
&& hr
== HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND
))
1068 WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
1069 wine_dbgstr_w(filename
));
1074 /* This might be a raw .ico file */
1075 hr
= SHCreateStreamOnFileW(filename
, STGM_READ
, ppStream
);
1079 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1083 hr
= open_file_type_icon(filename
, ppStream
);
1085 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1087 if (FAILED(hr
) && !bWait
)
1089 hr
= open_default_icon(ppStream
);
1091 hr
= validate_ico(ppStream
, ppIconDirEntries
, numEntries
);
1096 static char* compute_native_identifier(int exeIndex
, LPCWSTR icoPathW
)
1098 char* nativeIdentifier
;
1101 char *basename
, *ext
;
1103 icoPathA
= wchars_to_utf8_chars(icoPathW
);
1104 if (icoPathA
== NULL
)
1107 crc
= crc16(icoPathA
);
1108 basename
= strrchr(icoPathA
, '\\');
1109 if (basename
== NULL
)
1110 basename
= icoPathA
;
1116 ext
= strrchr(basename
, '.');
1120 nativeIdentifier
= heap_printf("%04X_%s.%d", crc
, basename
, exeIndex
);
1121 HeapFree(GetProcessHeap(), 0, icoPathA
);
1122 return nativeIdentifier
;
1126 #define ICNS_SLOTS 6
1128 static inline int size_to_slot(int size
)
1135 case 64: return -2; /* Classic Mode */
1144 #define CLASSIC_SLOT 3
1146 static HRESULT
platform_write_icon(IStream
*icoStream
, ICONDIRENTRY
*iconDirEntries
,
1147 int numEntries
, int exeIndex
, LPCWSTR icoPathW
,
1148 const char *destFilename
, char **nativeIdentifier
)
1155 int indexes
[ICNS_SLOTS
];
1158 char *icnsPath
= NULL
;
1162 for (i
= 0; i
< ICNS_SLOTS
; i
++)
1165 best
[i
].maxBits
= 0;
1167 for (i
= 0; i
< numEntries
; i
++)
1170 int width
= iconDirEntries
[i
].bWidth
? iconDirEntries
[i
].bWidth
: 256;
1171 int height
= iconDirEntries
[i
].bHeight
? iconDirEntries
[i
].bHeight
: 256;
1172 BOOL scaled
= FALSE
;
1174 WINE_TRACE("[%d]: %d x %d @ %d\n", i
, width
, height
, iconDirEntries
[i
].wBitCount
);
1175 if (height
!= width
)
1177 slot
= size_to_slot(width
);
1181 slot
= CLASSIC_SLOT
;
1185 if (scaled
&& best
[slot
].maxBits
&& !best
[slot
].scaled
)
1186 continue; /* don't replace unscaled with scaled */
1187 if (iconDirEntries
[i
].wBitCount
>= best
[slot
].maxBits
|| (!scaled
&& best
[slot
].scaled
))
1189 best
[slot
].index
= i
;
1190 best
[slot
].maxBits
= iconDirEntries
[i
].wBitCount
;
1191 best
[slot
].scaled
= scaled
;
1194 /* remove the scaled icon if a larger unscaled icon exists */
1195 if (best
[CLASSIC_SLOT
].scaled
)
1197 for (i
= CLASSIC_SLOT
+1; i
< ICNS_SLOTS
; i
++)
1198 if (best
[i
].index
>= 0 && !best
[i
].scaled
)
1200 best
[CLASSIC_SLOT
].index
= -1;
1206 for (i
= 0; i
< ICNS_SLOTS
; i
++)
1208 if (best
[i
].index
>= 0)
1210 indexes
[numEntries
] = best
[i
].index
;
1216 *nativeIdentifier
= heap_printf("%s", destFilename
);
1218 *nativeIdentifier
= compute_native_identifier(exeIndex
, icoPathW
);
1219 if (*nativeIdentifier
== NULL
)
1224 if (!(tmpdir
= getenv("TMPDIR"))) tmpdir
= "/tmp";
1225 icnsPath
= heap_printf("%s/%s.icns", tmpdir
, *nativeIdentifier
);
1226 if (icnsPath
== NULL
)
1229 WINE_WARN("out of memory creating ICNS path\n");
1233 hr
= IStream_Seek(icoStream
, zero
, STREAM_SEEK_SET
, NULL
);
1236 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr
);
1239 hr
= convert_to_native_icon(icoStream
, indexes
, numEntries
, &CLSID_WICIcnsEncoder
,
1240 icnsPath
, icoPathW
);
1243 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
1244 wine_dbgstr_w(icoPathW
), wine_dbgstr_a(icnsPath
), hr
);
1249 HeapFree(GetProcessHeap(), 0, icnsPath
);
1253 static void refresh_icon_cache(const char *iconsDir
)
1255 /* The icon theme spec only requires the mtime on the "toplevel"
1256 * directory (whatever that is) to be changed for a refresh,
1257 * but on GNOME you have to create a file in that directory
1258 * instead. Creating a file also works on KDE, Xfce and LXDE.
1260 char *filename
= heap_printf("%s/.wine-refresh-XXXXXX", iconsDir
);
1261 if (filename
!= NULL
)
1263 int fd
= mkstemps(filename
, 0);
1269 HeapFree(GetProcessHeap(), 0, filename
);
1273 static HRESULT
platform_write_icon(IStream
*icoStream
, ICONDIRENTRY
*iconDirEntries
,
1274 int numEntries
, int exeIndex
, LPCWSTR icoPathW
,
1275 const char *destFilename
, char **nativeIdentifier
)
1278 char *iconsDir
= NULL
;
1283 *nativeIdentifier
= heap_printf("%s", destFilename
);
1285 *nativeIdentifier
= compute_native_identifier(exeIndex
, icoPathW
);
1286 if (*nativeIdentifier
== NULL
)
1291 iconsDir
= heap_printf("%s/icons/hicolor", xdg_data_dir
);
1292 if (iconsDir
== NULL
)
1298 for (i
= 0; i
< numEntries
; i
++)
1302 BOOLEAN duplicate
= FALSE
;
1304 char *iconDir
= NULL
;
1305 char *pngPath
= NULL
;
1307 WINE_TRACE("[%d]: %d x %d @ %d\n", i
, iconDirEntries
[i
].bWidth
,
1308 iconDirEntries
[i
].bHeight
, iconDirEntries
[i
].wBitCount
);
1310 for (j
= 0; j
< i
; j
++)
1312 if (iconDirEntries
[j
].bWidth
== iconDirEntries
[i
].bWidth
&&
1313 iconDirEntries
[j
].bHeight
== iconDirEntries
[i
].bHeight
)
1321 for (j
= i
+ 1; j
< numEntries
; j
++)
1323 if (iconDirEntries
[j
].bWidth
== iconDirEntries
[i
].bWidth
&&
1324 iconDirEntries
[j
].bHeight
== iconDirEntries
[i
].bHeight
&&
1325 iconDirEntries
[j
].wBitCount
>= iconDirEntries
[bestIndex
].wBitCount
)
1330 WINE_TRACE("Selected: %d\n", bestIndex
);
1332 w
= iconDirEntries
[bestIndex
].bWidth
? iconDirEntries
[bestIndex
].bWidth
: 256;
1333 h
= iconDirEntries
[bestIndex
].bHeight
? iconDirEntries
[bestIndex
].bHeight
: 256;
1334 iconDir
= heap_printf("%s/%dx%d/apps", iconsDir
, w
, h
);
1335 if (iconDir
== NULL
)
1340 create_directories(iconDir
);
1341 pngPath
= heap_printf("%s/%s.png", iconDir
, *nativeIdentifier
);
1342 if (pngPath
== NULL
)
1348 hr
= IStream_Seek(icoStream
, zero
, STREAM_SEEK_SET
, NULL
);
1351 hr
= convert_to_native_icon(icoStream
, &bestIndex
, 1, &CLSID_WICPngEncoder
,
1355 HeapFree(GetProcessHeap(), 0, iconDir
);
1356 HeapFree(GetProcessHeap(), 0, pngPath
);
1358 refresh_icon_cache(iconsDir
);
1361 HeapFree(GetProcessHeap(), 0, iconsDir
);
1364 #endif /* defined(__APPLE__) */
1366 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1367 static char *extract_icon(LPCWSTR icoPathW
, int index
, const char *destFilename
, BOOL bWait
)
1369 IStream
*stream
= NULL
;
1370 ICONDIRENTRY
*pIconDirEntries
= NULL
;
1373 char *nativeIdentifier
= NULL
;
1375 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW
), index
, wine_dbgstr_a(destFilename
));
1377 hr
= open_icon(icoPathW
, index
, bWait
, &stream
, &pIconDirEntries
, &numEntries
);
1380 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW
), index
, hr
);
1383 hr
= platform_write_icon(stream
, pIconDirEntries
, numEntries
, index
, icoPathW
, destFilename
, &nativeIdentifier
);
1385 WINE_WARN("writing icon failed, error 0x%08X\n", hr
);
1389 IStream_Release(stream
);
1390 HeapFree(GetProcessHeap(), 0, pIconDirEntries
);
1393 HeapFree(GetProcessHeap(), 0, nativeIdentifier
);
1394 nativeIdentifier
= NULL
;
1396 return nativeIdentifier
;
1399 static HKEY
open_menus_reg_key(void)
1401 static const WCHAR Software_Wine_FileOpenMenuFilesW
[] = {
1402 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1405 ret
= RegCreateKeyW(HKEY_CURRENT_USER
, Software_Wine_FileOpenMenuFilesW
, &assocKey
);
1406 if (ret
== ERROR_SUCCESS
)
1412 static DWORD
register_menus_entry(const char *unix_file
, const char *windows_file
)
1415 WCHAR
*windows_fileW
;
1419 size
= MultiByteToWideChar(CP_UNIXCP
, 0, unix_file
, -1, NULL
, 0);
1420 unix_fileW
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
1423 MultiByteToWideChar(CP_UNIXCP
, 0, unix_file
, -1, unix_fileW
, size
);
1424 size
= MultiByteToWideChar(CP_UNIXCP
, 0, windows_file
, -1, NULL
, 0);
1425 windows_fileW
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
1429 MultiByteToWideChar(CP_UNIXCP
, 0, windows_file
, -1, windows_fileW
, size
);
1430 hkey
= open_menus_reg_key();
1433 ret
= RegSetValueExW(hkey
, unix_fileW
, 0, REG_SZ
, (const BYTE
*)windows_fileW
,
1434 (strlenW(windows_fileW
) + 1) * sizeof(WCHAR
));
1438 ret
= GetLastError();
1439 HeapFree(GetProcessHeap(), 0, windows_fileW
);
1442 ret
= ERROR_NOT_ENOUGH_MEMORY
;
1443 HeapFree(GetProcessHeap(), 0, unix_fileW
);
1446 ret
= ERROR_NOT_ENOUGH_MEMORY
;
1450 static BOOL
write_desktop_entry(const char *unix_link
, const char *location
, const char *linkname
,
1451 const char *path
, const char *args
, const char *descr
,
1452 const char *workdir
, const char *icon
, const char *wmclass
)
1456 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link
), wine_dbgstr_a(location
),
1457 wine_dbgstr_a(linkname
), wine_dbgstr_a(path
), wine_dbgstr_a(args
),
1458 wine_dbgstr_a(descr
), wine_dbgstr_a(workdir
), wine_dbgstr_a(icon
),
1459 wine_dbgstr_a(wmclass
));
1461 file
= fopen(location
, "w");
1465 fprintf(file
, "[Desktop Entry]\n");
1466 fprintf(file
, "Name=%s\n", linkname
);
1467 fprintf(file
, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1468 wine_get_config_dir(), path
, args
);
1469 fprintf(file
, "Type=Application\n");
1470 fprintf(file
, "StartupNotify=true\n");
1471 if (descr
&& lstrlenA(descr
))
1472 fprintf(file
, "Comment=%s\n", descr
);
1473 if (workdir
&& lstrlenA(workdir
))
1474 fprintf(file
, "Path=%s\n", workdir
);
1475 if (icon
&& lstrlenA(icon
))
1476 fprintf(file
, "Icon=%s\n", icon
);
1477 if (wmclass
&& lstrlenA(wmclass
))
1478 fprintf(file
, "StartupWMClass=%s\n", wmclass
);
1484 DWORD ret
= register_menus_entry(location
, unix_link
);
1485 if (ret
!= ERROR_SUCCESS
)
1492 static BOOL
write_directory_entry(const char *directory
, const char *location
)
1496 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory
), wine_dbgstr_a(location
));
1498 file
= fopen(location
, "w");
1502 fprintf(file
, "[Desktop Entry]\n");
1503 fprintf(file
, "Type=Directory\n");
1504 if (strcmp(directory
, "wine") == 0)
1506 fprintf(file
, "Name=Wine\n");
1507 fprintf(file
, "Icon=wine\n");
1511 fprintf(file
, "Name=%s\n", directory
);
1512 fprintf(file
, "Icon=folder\n");
1519 static BOOL
write_menu_file(const char *unix_link
, const char *filename
)
1522 FILE *tempfile
= NULL
;
1525 char *menuPath
= NULL
;
1530 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename
));
1534 tempfilename
= heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir
);
1537 int tempfd
= mkstemps(tempfilename
, 0);
1540 tempfile
= fdopen(tempfd
, "w");
1546 else if (errno
== EEXIST
)
1548 HeapFree(GetProcessHeap(), 0, tempfilename
);
1551 HeapFree(GetProcessHeap(), 0, tempfilename
);
1556 fprintf(tempfile
, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1557 fprintf(tempfile
, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1558 fprintf(tempfile
, "<Menu>\n");
1559 fprintf(tempfile
, " <Name>Applications</Name>\n");
1561 name
= HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename
) + 1);
1562 if (name
== NULL
) goto end
;
1564 for (i
= 0; filename
[i
]; i
++)
1566 name
[i
] = filename
[i
];
1567 if (filename
[i
] == '/')
1569 char *dir_file_name
;
1572 fprintf(tempfile
, " <Menu>\n");
1573 fprintf(tempfile
, " <Name>%s", count
? "" : "wine-");
1574 write_xml_text(tempfile
, name
);
1575 fprintf(tempfile
, "</Name>\n");
1576 fprintf(tempfile
, " <Directory>%s", count
? "" : "wine-");
1577 write_xml_text(tempfile
, name
);
1578 fprintf(tempfile
, ".directory</Directory>\n");
1579 dir_file_name
= heap_printf("%s/desktop-directories/%s%s.directory",
1580 xdg_data_dir
, count
? "" : "wine-", name
);
1583 if (stat(dir_file_name
, &st
) != 0 && errno
== ENOENT
)
1584 write_directory_entry(lastEntry
, dir_file_name
);
1585 HeapFree(GetProcessHeap(), 0, dir_file_name
);
1588 lastEntry
= &name
[i
+1];
1594 fprintf(tempfile
, " <Include>\n");
1595 fprintf(tempfile
, " <Filename>");
1596 write_xml_text(tempfile
, name
);
1597 fprintf(tempfile
, "</Filename>\n");
1598 fprintf(tempfile
, " </Include>\n");
1599 for (i
= 0; i
< count
; i
++)
1600 fprintf(tempfile
, " </Menu>\n");
1601 fprintf(tempfile
, "</Menu>\n");
1603 menuPath
= heap_printf("%s/%s", xdg_config_dir
, name
);
1604 if (menuPath
== NULL
) goto end
;
1605 strcpy(menuPath
+ strlen(menuPath
) - strlen(".desktop"), ".menu");
1612 ret
= (rename(tempfilename
, menuPath
) == 0);
1613 if (!ret
&& tempfilename
)
1614 remove(tempfilename
);
1615 HeapFree(GetProcessHeap(), 0, tempfilename
);
1617 register_menus_entry(menuPath
, unix_link
);
1618 HeapFree(GetProcessHeap(), 0, name
);
1619 HeapFree(GetProcessHeap(), 0, menuPath
);
1623 static BOOL
write_menu_entry(const char *unix_link
, const char *link
, const char *path
, const char *args
,
1624 const char *descr
, const char *workdir
, const char *icon
, const char *wmclass
)
1626 const char *linkname
;
1627 char *desktopPath
= NULL
;
1629 char *filename
= NULL
;
1632 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link
), wine_dbgstr_a(link
),
1633 wine_dbgstr_a(path
), wine_dbgstr_a(args
), wine_dbgstr_a(descr
),
1634 wine_dbgstr_a(workdir
), wine_dbgstr_a(icon
), wine_dbgstr_a(wmclass
));
1636 linkname
= strrchr(link
, '/');
1637 if (linkname
== NULL
)
1642 desktopPath
= heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir
, link
);
1645 WINE_WARN("out of memory creating menu entry\n");
1649 desktopDir
= strrchr(desktopPath
, '/');
1651 if (!create_directories(desktopPath
))
1653 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath
));
1658 if (!write_desktop_entry(unix_link
, desktopPath
, linkname
, path
, args
, descr
, workdir
, icon
, wmclass
))
1660 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath
));
1665 filename
= heap_printf("wine/%s.desktop", link
);
1666 if (!filename
|| !write_menu_file(unix_link
, filename
))
1668 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename
));
1673 HeapFree(GetProcessHeap(), 0, desktopPath
);
1674 HeapFree(GetProcessHeap(), 0, filename
);
1678 /* This escapes reserved characters in .desktop files' Exec keys. */
1679 static LPSTR
escape(LPCWSTR arg
)
1682 WCHAR
*escaped_string
;
1685 escaped_string
= HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg
) + 1) * sizeof(WCHAR
));
1686 if (escaped_string
== NULL
) return NULL
;
1687 for (i
= j
= 0; arg
[i
]; i
++)
1692 escaped_string
[j
++] = '\\';
1693 escaped_string
[j
++] = '\\';
1694 escaped_string
[j
++] = '\\';
1695 escaped_string
[j
++] = '\\';
1715 escaped_string
[j
++] = '\\';
1716 escaped_string
[j
++] = '\\';
1719 escaped_string
[j
++] = arg
[i
];
1723 escaped_string
[j
] = 0;
1725 utf8_string
= wchars_to_utf8_chars(escaped_string
);
1726 if (utf8_string
== NULL
)
1728 WINE_ERR("out of memory\n");
1733 HeapFree(GetProcessHeap(), 0, escaped_string
);
1737 /* Return a heap-allocated copy of the unix format difference between the two
1738 * Windows-format paths.
1739 * locn is the owning location
1740 * link is within locn
1742 static char *relative_path( LPCWSTR link
, LPCWSTR locn
)
1744 char *unix_locn
, *unix_link
;
1745 char *relative
= NULL
;
1747 unix_locn
= wine_get_unix_file_name(locn
);
1748 unix_link
= wine_get_unix_file_name(link
);
1749 if (unix_locn
&& unix_link
)
1751 size_t len_unix_locn
, len_unix_link
;
1752 len_unix_locn
= strlen (unix_locn
);
1753 len_unix_link
= strlen (unix_link
);
1754 if (len_unix_locn
< len_unix_link
&& memcmp (unix_locn
, unix_link
, len_unix_locn
) == 0 && unix_link
[len_unix_locn
] == '/')
1757 char *p
= strrchr (unix_link
+ len_unix_locn
, '/');
1758 p
= strrchr (p
, '.');
1762 len_unix_link
= p
- unix_link
;
1764 len_rel
= len_unix_link
- len_unix_locn
;
1765 relative
= HeapAlloc(GetProcessHeap(), 0, len_rel
);
1768 memcpy (relative
, unix_link
+ len_unix_locn
+ 1, len_rel
);
1773 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link
), wine_dbgstr_w(locn
));
1774 HeapFree(GetProcessHeap(), 0, unix_locn
);
1775 HeapFree(GetProcessHeap(), 0, unix_link
);
1779 /***********************************************************************
1783 * returns TRUE if successful
1784 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1785 * *relative will contain the address of a heap-allocated copy of the portion
1786 * of the filename that is within the specified location, in unix form
1788 static BOOL
GetLinkLocation( LPCWSTR linkfile
, DWORD
*loc
, char **relative
)
1790 WCHAR filename
[MAX_PATH
], shortfilename
[MAX_PATH
], buffer
[MAX_PATH
];
1791 DWORD len
, i
, r
, filelen
;
1792 const DWORD locations
[] = {
1793 CSIDL_STARTUP
, CSIDL_DESKTOPDIRECTORY
, CSIDL_STARTMENU
,
1794 CSIDL_COMMON_STARTUP
, CSIDL_COMMON_DESKTOPDIRECTORY
,
1795 CSIDL_COMMON_STARTMENU
};
1797 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile
));
1798 filelen
=GetFullPathNameW( linkfile
, MAX_PATH
, shortfilename
, NULL
);
1799 if (filelen
==0 || filelen
>MAX_PATH
)
1802 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename
));
1804 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1805 * expand or our hardcoded list won't match.
1807 filelen
=GetLongPathNameW(shortfilename
, filename
, MAX_PATH
);
1808 if (filelen
==0 || filelen
>MAX_PATH
)
1811 WINE_TRACE("%s\n", wine_dbgstr_w(filename
));
1813 for( i
=0; i
<ARRAY_SIZE( locations
); i
++ )
1815 if (!SHGetSpecialFolderPathW( 0, buffer
, locations
[i
], FALSE
))
1818 len
= lstrlenW(buffer
);
1819 if (len
>= MAX_PATH
)
1820 continue; /* We've just trashed memory! Hopefully we are OK */
1822 if (len
> filelen
|| filename
[len
]!='\\')
1824 /* do a lstrcmpinW */
1826 r
= lstrcmpiW( filename
, buffer
);
1827 filename
[len
] = '\\';
1831 /* return the remainder of the string and link type */
1832 *loc
= locations
[i
];
1833 *relative
= relative_path (filename
, buffer
);
1834 return (*relative
!= NULL
);
1840 /* gets the target path directly or through MSI */
1841 static HRESULT
get_cmdline( IShellLinkW
*sl
, LPWSTR szPath
, DWORD pathSize
,
1842 LPWSTR szArgs
, DWORD argsSize
)
1844 IShellLinkDataList
*dl
= NULL
;
1845 EXP_DARWIN_LINK
*dar
= NULL
;
1851 hr
= IShellLinkW_GetPath( sl
, szPath
, pathSize
, NULL
, SLGP_RAWPATH
);
1852 if (hr
== S_OK
&& szPath
[0])
1854 IShellLinkW_GetArguments( sl
, szArgs
, argsSize
);
1858 hr
= IShellLinkW_QueryInterface( sl
, &IID_IShellLinkDataList
, (LPVOID
*) &dl
);
1862 hr
= IShellLinkDataList_CopyDataBlock( dl
, EXP_DARWIN_ID_SIG
, (LPVOID
*) &dar
);
1869 hr
= CommandLineFromMsiDescriptor( dar
->szwDarwinID
, NULL
, &cmdSize
);
1870 if (hr
== ERROR_SUCCESS
)
1873 szCmdline
= HeapAlloc( GetProcessHeap(), 0, cmdSize
*sizeof(WCHAR
) );
1874 hr
= CommandLineFromMsiDescriptor( dar
->szwDarwinID
, szCmdline
, &cmdSize
);
1875 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline
));
1876 if (hr
== ERROR_SUCCESS
)
1880 BOOL in_quotes
= FALSE
;
1882 /* Extract the application path */
1887 if ((*s
==0x0009 || *s
==0x0020) && !in_quotes
)
1889 /* skip the remaining spaces */
1892 } while (*s
==0x0009 || *s
==0x0020);
1895 else if (*s
==0x005c)
1901 else if (*s
==0x0022)
1904 if ((bcount
& 1)==0)
1906 /* Preceded by an even number of '\', this is
1907 * half that number of '\', plus a quote which
1911 in_quotes
=!in_quotes
;
1916 /* Preceded by an odd number of '\', this is
1917 * half that number of '\' followed by a '"'
1927 /* a regular character */
1931 if ((d
-szPath
) == pathSize
)
1933 /* Keep processing the path till we get to the
1934 * arguments, but 'stand still'
1939 /* Close the application path */
1942 lstrcpynW(szArgs
, s
, argsSize
);
1944 HeapFree( GetProcessHeap(), 0, szCmdline
);
1949 IShellLinkDataList_Release( dl
);
1953 static char *slashes_to_minuses(const char *string
)
1956 char *ret
= HeapAlloc(GetProcessHeap(), 0, lstrlenA(string
) + 1);
1959 for (i
= 0; string
[i
]; i
++)
1961 if (string
[i
] == '/')
1972 static BOOL
next_line(FILE *file
, char **line
, int *size
)
1979 *line
= HeapAlloc(GetProcessHeap(), 0, *size
);
1981 while (*line
!= NULL
)
1983 if (fgets(&(*line
)[pos
], *size
- pos
, file
) == NULL
)
1985 HeapFree(GetProcessHeap(), 0, *line
);
1991 pos
= strlen(*line
);
1992 cr
= strchr(*line
, '\n');
1997 line2
= HeapReAlloc(GetProcessHeap(), 0, *line
, *size
);
2002 HeapFree(GetProcessHeap(), 0, *line
);
2015 static BOOL
add_mimes(const char *xdg_data_dir
, struct list
*mime_types
)
2017 char *globs_filename
= NULL
;
2019 globs_filename
= heap_printf("%s/mime/globs", xdg_data_dir
);
2022 FILE *globs_file
= fopen(globs_filename
, "r");
2023 if (globs_file
) /* doesn't have to exist */
2027 while (ret
&& (ret
= next_line(globs_file
, &line
, &size
)) && line
)
2030 struct xdg_mime_type
*mime_type_entry
= NULL
;
2031 if (line
[0] != '#' && (pos
= strchr(line
, ':')))
2033 mime_type_entry
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type
));
2034 if (mime_type_entry
)
2037 mime_type_entry
->mimeType
= strdupA(line
);
2038 mime_type_entry
->glob
= strdupA(pos
+ 1);
2039 mime_type_entry
->lower_glob
= strdupA(pos
+ 1);
2040 if (mime_type_entry
->lower_glob
)
2043 for (l
= mime_type_entry
->lower_glob
; *l
; l
++)
2046 if (mime_type_entry
->mimeType
&& mime_type_entry
->glob
&& mime_type_entry
->lower_glob
)
2047 list_add_tail(mime_types
, &mime_type_entry
->entry
);
2050 HeapFree(GetProcessHeap(), 0, mime_type_entry
->mimeType
);
2051 HeapFree(GetProcessHeap(), 0, mime_type_entry
->glob
);
2052 HeapFree(GetProcessHeap(), 0, mime_type_entry
->lower_glob
);
2053 HeapFree(GetProcessHeap(), 0, mime_type_entry
);
2061 HeapFree(GetProcessHeap(), 0, line
);
2064 HeapFree(GetProcessHeap(), 0, globs_filename
);
2071 static void free_native_mime_types(struct list
*native_mime_types
)
2073 struct xdg_mime_type
*mime_type_entry
, *mime_type_entry2
;
2075 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry
, mime_type_entry2
, native_mime_types
, struct xdg_mime_type
, entry
)
2077 list_remove(&mime_type_entry
->entry
);
2078 HeapFree(GetProcessHeap(), 0, mime_type_entry
->glob
);
2079 HeapFree(GetProcessHeap(), 0, mime_type_entry
->lower_glob
);
2080 HeapFree(GetProcessHeap(), 0, mime_type_entry
->mimeType
);
2081 HeapFree(GetProcessHeap(), 0, mime_type_entry
);
2085 static BOOL
build_native_mime_types(const char *xdg_data_home
, struct list
*mime_types
)
2087 char *xdg_data_dirs
;
2090 xdg_data_dirs
= getenv("XDG_DATA_DIRS");
2091 if (xdg_data_dirs
== NULL
)
2092 xdg_data_dirs
= heap_printf("/usr/local/share/:/usr/share/");
2094 xdg_data_dirs
= strdupA(xdg_data_dirs
);
2101 ret
= add_mimes(xdg_data_home
, mime_types
);
2104 for (begin
= xdg_data_dirs
; (end
= strchr(begin
, ':')); begin
= end
+ 1)
2107 ret
= add_mimes(begin
, mime_types
);
2113 ret
= add_mimes(begin
, mime_types
);
2115 HeapFree(GetProcessHeap(), 0, xdg_data_dirs
);
2120 free_native_mime_types(mime_types
);
2124 static BOOL
match_glob(struct list
*native_mime_types
, const char *extension
,
2125 int ignoreGlobCase
, char **match
)
2128 struct xdg_mime_type
*mime_type_entry
;
2129 int matchLength
= 0;
2133 LIST_FOR_EACH_ENTRY(mime_type_entry
, native_mime_types
, struct xdg_mime_type
, entry
)
2135 const char *glob
= ignoreGlobCase
? mime_type_entry
->lower_glob
: mime_type_entry
->glob
;
2136 if (fnmatch(glob
, extension
, 0) == 0)
2138 if (*match
== NULL
|| matchLength
< strlen(glob
))
2140 *match
= mime_type_entry
->mimeType
;
2141 matchLength
= strlen(glob
);
2148 *match
= strdupA(*match
);
2158 static BOOL
freedesktop_mime_type_for_extension(struct list
*native_mime_types
,
2159 const char *extensionA
,
2163 WCHAR
*lower_extensionW
;
2165 BOOL ret
= match_glob(native_mime_types
, extensionA
, 0, mime_type
);
2166 if (ret
== FALSE
|| *mime_type
!= NULL
)
2168 len
= strlenW(extensionW
);
2169 lower_extensionW
= HeapAlloc(GetProcessHeap(), 0, (len
+ 1)*sizeof(WCHAR
));
2170 if (lower_extensionW
)
2172 char *lower_extensionA
;
2173 memcpy(lower_extensionW
, extensionW
, (len
+ 1)*sizeof(WCHAR
));
2174 strlwrW(lower_extensionW
);
2175 lower_extensionA
= wchars_to_utf8_chars(lower_extensionW
);
2176 if (lower_extensionA
)
2178 ret
= match_glob(native_mime_types
, lower_extensionA
, 1, mime_type
);
2179 HeapFree(GetProcessHeap(), 0, lower_extensionA
);
2184 WINE_FIXME("out of memory\n");
2186 HeapFree(GetProcessHeap(), 0, lower_extensionW
);
2191 WINE_FIXME("out of memory\n");
2196 static WCHAR
* reg_get_valW(HKEY key
, LPCWSTR subkey
, LPCWSTR name
)
2199 if (RegGetValueW(key
, subkey
, name
, RRF_RT_REG_SZ
, NULL
, NULL
, &size
) == ERROR_SUCCESS
)
2201 WCHAR
*ret
= HeapAlloc(GetProcessHeap(), 0, size
);
2204 if (RegGetValueW(key
, subkey
, name
, RRF_RT_REG_SZ
, NULL
, ret
, &size
) == ERROR_SUCCESS
)
2207 HeapFree(GetProcessHeap(), 0, ret
);
2212 static CHAR
* reg_get_val_utf8(HKEY key
, LPCWSTR subkey
, LPCWSTR name
)
2214 WCHAR
*valW
= reg_get_valW(key
, subkey
, name
);
2217 char *val
= wchars_to_utf8_chars(valW
);
2218 HeapFree(GetProcessHeap(), 0, valW
);
2224 static HKEY
open_associations_reg_key(void)
2226 static const WCHAR Software_Wine_FileOpenAssociationsW
[] = {
2227 '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};
2229 if (RegCreateKeyW(HKEY_CURRENT_USER
, Software_Wine_FileOpenAssociationsW
, &assocKey
) == ERROR_SUCCESS
)
2234 static BOOL
has_association_changed(LPCWSTR extensionW
, LPCSTR mimeType
, LPCWSTR progId
,
2235 LPCSTR appName
, LPCSTR openWithIcon
)
2237 static const WCHAR ProgIDW
[] = {'P','r','o','g','I','D',0};
2238 static const WCHAR MimeTypeW
[] = {'M','i','m','e','T','y','p','e',0};
2239 static const WCHAR AppNameW
[] = {'A','p','p','N','a','m','e',0};
2240 static const WCHAR OpenWithIconW
[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2244 if ((assocKey
= open_associations_reg_key()))
2251 valueA
= reg_get_val_utf8(assocKey
, extensionW
, MimeTypeW
);
2252 if (!valueA
|| lstrcmpA(valueA
, mimeType
))
2254 HeapFree(GetProcessHeap(), 0, valueA
);
2256 value
= reg_get_valW(assocKey
, extensionW
, ProgIDW
);
2257 if (!value
|| strcmpW(value
, progId
))
2259 HeapFree(GetProcessHeap(), 0, value
);
2261 valueA
= reg_get_val_utf8(assocKey
, extensionW
, AppNameW
);
2262 if (!valueA
|| lstrcmpA(valueA
, appName
))
2264 HeapFree(GetProcessHeap(), 0, valueA
);
2266 valueA
= reg_get_val_utf8(assocKey
, extensionW
, OpenWithIconW
);
2267 if ((openWithIcon
&& !valueA
) ||
2268 (!openWithIcon
&& valueA
) ||
2269 (openWithIcon
&& valueA
&& lstrcmpA(valueA
, openWithIcon
)))
2271 HeapFree(GetProcessHeap(), 0, valueA
);
2273 RegCloseKey(assocKey
);
2277 WINE_ERR("error opening associations registry key\n");
2283 static void update_association(LPCWSTR extension
, LPCSTR mimeType
, LPCWSTR progId
,
2284 LPCSTR appName
, LPCSTR desktopFile
, LPCSTR openWithIcon
)
2286 static const WCHAR ProgIDW
[] = {'P','r','o','g','I','D',0};
2287 static const WCHAR MimeTypeW
[] = {'M','i','m','e','T','y','p','e',0};
2288 static const WCHAR AppNameW
[] = {'A','p','p','N','a','m','e',0};
2289 static const WCHAR DesktopFileW
[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2290 static const WCHAR OpenWithIconW
[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2291 HKEY assocKey
= NULL
;
2293 WCHAR
*mimeTypeW
= NULL
;
2294 WCHAR
*appNameW
= NULL
;
2295 WCHAR
*desktopFileW
= NULL
;
2296 WCHAR
*openWithIconW
= NULL
;
2298 assocKey
= open_associations_reg_key();
2299 if (assocKey
== NULL
)
2301 WINE_ERR("could not open file associations key\n");
2305 if (RegCreateKeyW(assocKey
, extension
, &subkey
) != ERROR_SUCCESS
)
2307 WINE_ERR("could not create extension subkey\n");
2311 mimeTypeW
= utf8_chars_to_wchars(mimeType
);
2312 if (mimeTypeW
== NULL
)
2314 WINE_ERR("out of memory\n");
2318 appNameW
= utf8_chars_to_wchars(appName
);
2319 if (appNameW
== NULL
)
2321 WINE_ERR("out of memory\n");
2325 desktopFileW
= utf8_chars_to_wchars(desktopFile
);
2326 if (desktopFileW
== NULL
)
2328 WINE_ERR("out of memory\n");
2334 openWithIconW
= utf8_chars_to_wchars(openWithIcon
);
2335 if (openWithIconW
== NULL
)
2337 WINE_ERR("out of memory\n");
2342 RegSetValueExW(subkey
, MimeTypeW
, 0, REG_SZ
, (const BYTE
*) mimeTypeW
, (lstrlenW(mimeTypeW
) + 1) * sizeof(WCHAR
));
2343 RegSetValueExW(subkey
, ProgIDW
, 0, REG_SZ
, (const BYTE
*) progId
, (lstrlenW(progId
) + 1) * sizeof(WCHAR
));
2344 RegSetValueExW(subkey
, AppNameW
, 0, REG_SZ
, (const BYTE
*) appNameW
, (lstrlenW(appNameW
) + 1) * sizeof(WCHAR
));
2345 RegSetValueExW(subkey
, DesktopFileW
, 0, REG_SZ
, (const BYTE
*) desktopFileW
, (lstrlenW(desktopFileW
) + 1) * sizeof(WCHAR
));
2347 RegSetValueExW(subkey
, OpenWithIconW
, 0, REG_SZ
, (const BYTE
*) openWithIconW
, (lstrlenW(openWithIconW
) + 1) * sizeof(WCHAR
));
2349 RegDeleteValueW(subkey
, OpenWithIconW
);
2352 RegCloseKey(assocKey
);
2353 RegCloseKey(subkey
);
2354 HeapFree(GetProcessHeap(), 0, mimeTypeW
);
2355 HeapFree(GetProcessHeap(), 0, appNameW
);
2356 HeapFree(GetProcessHeap(), 0, desktopFileW
);
2357 HeapFree(GetProcessHeap(), 0, openWithIconW
);
2360 static BOOL
cleanup_associations(void)
2362 static const WCHAR openW
[] = {'o','p','e','n',0};
2363 static const WCHAR DesktopFileW
[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2365 BOOL hasChanged
= FALSE
;
2366 if ((assocKey
= open_associations_reg_key()))
2372 WCHAR
*extensionW
= NULL
;
2378 HeapFree(GetProcessHeap(), 0, extensionW
);
2379 extensionW
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
2380 if (extensionW
== NULL
)
2382 WINE_ERR("out of memory\n");
2383 ret
= ERROR_OUTOFMEMORY
;
2386 ret
= RegEnumKeyExW(assocKey
, i
, extensionW
, &size
, NULL
, NULL
, NULL
, NULL
);
2388 } while (ret
== ERROR_MORE_DATA
);
2390 if (ret
== ERROR_SUCCESS
)
2393 command
= assoc_query(ASSOCSTR_COMMAND
, extensionW
, openW
);
2394 if (command
== NULL
)
2396 char *desktopFile
= reg_get_val_utf8(assocKey
, extensionW
, DesktopFileW
);
2399 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW
));
2400 remove(desktopFile
);
2402 RegDeleteKeyW(assocKey
, extensionW
);
2404 HeapFree(GetProcessHeap(), 0, desktopFile
);
2408 HeapFree(GetProcessHeap(), 0, command
);
2412 if (ret
!= ERROR_NO_MORE_ITEMS
)
2413 WINE_ERR("error %d while reading registry\n", ret
);
2416 HeapFree(GetProcessHeap(), 0, extensionW
);
2418 RegCloseKey(assocKey
);
2421 WINE_ERR("could not open file associations key\n");
2425 static BOOL
write_freedesktop_mime_type_entry(const char *packages_dir
, const char *dot_extension
,
2426 const char *mime_type
, const char *comment
)
2431 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type
),
2432 wine_dbgstr_a(dot_extension
), wine_dbgstr_a(comment
));
2434 filename
= heap_printf("%s/x-wine-extension-%s.xml", packages_dir
, &dot_extension
[1]);
2437 FILE *packageFile
= fopen(filename
, "w");
2440 fprintf(packageFile
, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2441 fprintf(packageFile
, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2442 fprintf(packageFile
, " <mime-type type=\"");
2443 write_xml_text(packageFile
, mime_type
);
2444 fprintf(packageFile
, "\">\n");
2445 fprintf(packageFile
, " <glob pattern=\"*");
2446 write_xml_text(packageFile
, dot_extension
);
2447 fprintf(packageFile
, "\"/>\n");
2450 fprintf(packageFile
, " <comment>");
2451 write_xml_text(packageFile
, comment
);
2452 fprintf(packageFile
, "</comment>\n");
2454 fprintf(packageFile
, " </mime-type>\n");
2455 fprintf(packageFile
, "</mime-info>\n");
2457 fclose(packageFile
);
2460 WINE_ERR("error writing file %s\n", filename
);
2461 HeapFree(GetProcessHeap(), 0, filename
);
2464 WINE_ERR("out of memory\n");
2468 static BOOL
is_extension_blacklisted(LPCWSTR extension
)
2470 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2471 static const WCHAR comW
[] = {'.','c','o','m',0};
2472 static const WCHAR exeW
[] = {'.','e','x','e',0};
2473 static const WCHAR msiW
[] = {'.','m','s','i',0};
2475 if (!strcmpiW(extension
, comW
) ||
2476 !strcmpiW(extension
, exeW
) ||
2477 !strcmpiW(extension
, msiW
))
2482 static const char* get_special_mime_type(LPCWSTR extension
)
2484 static const WCHAR lnkW
[] = {'.','l','n','k',0};
2485 if (!strcmpiW(extension
, lnkW
))
2486 return "application/x-ms-shortcut";
2490 static BOOL
write_freedesktop_association_entry(const char *desktopPath
, const char *dot_extension
,
2491 const char *friendlyAppName
, const char *mimeType
,
2492 const char *progId
, const char *openWithIcon
)
2497 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2498 wine_dbgstr_a(dot_extension
), wine_dbgstr_a(friendlyAppName
), wine_dbgstr_a(mimeType
),
2499 wine_dbgstr_a(progId
), wine_dbgstr_a(openWithIcon
), wine_dbgstr_a(desktopPath
));
2501 desktop
= fopen(desktopPath
, "w");
2504 fprintf(desktop
, "[Desktop Entry]\n");
2505 fprintf(desktop
, "Type=Application\n");
2506 fprintf(desktop
, "Name=%s\n", friendlyAppName
);
2507 fprintf(desktop
, "MimeType=%s;\n", mimeType
);
2508 fprintf(desktop
, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId
);
2509 fprintf(desktop
, "NoDisplay=true\n");
2510 fprintf(desktop
, "StartupNotify=true\n");
2512 fprintf(desktop
, "Icon=%s\n", openWithIcon
);
2517 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath
));
2521 static BOOL
generate_associations(const char *xdg_data_home
, const char *packages_dir
, const char *applications_dir
)
2523 static const WCHAR openW
[] = {'o','p','e','n',0};
2524 struct wine_rb_tree mimeProgidTree
= { winemenubuilder_rb_string_compare
};
2525 struct list nativeMimeTypes
= LIST_INIT(nativeMimeTypes
);
2528 BOOL hasChanged
= FALSE
;
2530 if (!build_native_mime_types(xdg_data_home
, &nativeMimeTypes
))
2532 WINE_ERR("could not build native MIME types\n");
2538 WCHAR
*extensionW
= NULL
;
2543 HeapFree(GetProcessHeap(), 0, extensionW
);
2544 extensionW
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
2545 if (extensionW
== NULL
)
2547 WINE_ERR("out of memory\n");
2548 ret
= ERROR_OUTOFMEMORY
;
2551 ret
= RegEnumKeyExW(HKEY_CLASSES_ROOT
, i
, extensionW
, &size
, NULL
, NULL
, NULL
, NULL
);
2553 } while (ret
== ERROR_MORE_DATA
);
2555 if (ret
== ERROR_SUCCESS
&& extensionW
[0] == '.' && !is_extension_blacklisted(extensionW
))
2557 char *extensionA
= NULL
;
2558 WCHAR
*commandW
= NULL
;
2559 WCHAR
*executableW
= NULL
;
2560 char *openWithIconA
= NULL
;
2561 WCHAR
*friendlyDocNameW
= NULL
;
2562 char *friendlyDocNameA
= NULL
;
2563 WCHAR
*iconW
= NULL
;
2565 WCHAR
*contentTypeW
= NULL
;
2566 char *mimeTypeA
= NULL
;
2567 WCHAR
*friendlyAppNameW
= NULL
;
2568 char *friendlyAppNameA
= NULL
;
2569 WCHAR
*progIdW
= NULL
;
2570 char *progIdA
= NULL
;
2571 char *mimeProgId
= NULL
;
2573 extensionA
= wchars_to_utf8_chars(strlwrW(extensionW
));
2574 if (extensionA
== NULL
)
2576 WINE_ERR("out of memory\n");
2580 friendlyDocNameW
= assoc_query(ASSOCSTR_FRIENDLYDOCNAME
, extensionW
, NULL
);
2581 if (friendlyDocNameW
)
2583 friendlyDocNameA
= wchars_to_utf8_chars(friendlyDocNameW
);
2584 if (friendlyDocNameA
== NULL
)
2586 WINE_ERR("out of memory\n");
2591 iconW
= assoc_query(ASSOCSTR_DEFAULTICON
, extensionW
, NULL
);
2593 contentTypeW
= assoc_query(ASSOCSTR_CONTENTTYPE
, extensionW
, NULL
);
2595 strlwrW(contentTypeW
);
2597 if (!freedesktop_mime_type_for_extension(&nativeMimeTypes
, extensionA
, extensionW
, &mimeTypeA
))
2600 if (mimeTypeA
== NULL
)
2602 if (contentTypeW
!= NULL
&& strchrW(contentTypeW
, '/'))
2603 mimeTypeA
= wchars_to_utf8_chars(contentTypeW
);
2604 else if ((get_special_mime_type(extensionW
)))
2605 mimeTypeA
= strdupA(get_special_mime_type(extensionW
));
2607 mimeTypeA
= heap_printf("application/x-wine-extension-%s", &extensionA
[1]);
2609 if (mimeTypeA
!= NULL
)
2611 /* GNOME seems to ignore the <icon> tag in MIME packages,
2612 * and the default name is more intuitive anyway.
2616 char *flattened_mime
= slashes_to_minuses(mimeTypeA
);
2620 WCHAR
*comma
= strrchrW(iconW
, ',');
2624 index
= atoiW(comma
+ 1);
2626 iconA
= extract_icon(iconW
, index
, flattened_mime
, FALSE
);
2627 HeapFree(GetProcessHeap(), 0, flattened_mime
);
2631 write_freedesktop_mime_type_entry(packages_dir
, extensionA
, mimeTypeA
, friendlyDocNameA
);
2636 WINE_FIXME("out of memory\n");
2641 commandW
= assoc_query(ASSOCSTR_COMMAND
, extensionW
, openW
);
2642 if (commandW
== NULL
)
2643 /* no command => no application is associated */
2646 executableW
= assoc_query(ASSOCSTR_EXECUTABLE
, extensionW
, openW
);
2648 openWithIconA
= extract_icon(executableW
, 0, NULL
, FALSE
);
2650 friendlyAppNameW
= assoc_query(ASSOCSTR_FRIENDLYAPPNAME
, extensionW
, openW
);
2651 if (friendlyAppNameW
)
2653 friendlyAppNameA
= wchars_to_utf8_chars(friendlyAppNameW
);
2654 if (friendlyAppNameA
== NULL
)
2656 WINE_ERR("out of memory\n");
2662 friendlyAppNameA
= heap_printf("A Wine application");
2663 if (friendlyAppNameA
== NULL
)
2665 WINE_ERR("out of memory\n");
2670 progIdW
= reg_get_valW(HKEY_CLASSES_ROOT
, extensionW
, NULL
);
2673 progIdA
= escape(progIdW
);
2674 if (progIdA
== NULL
)
2676 WINE_ERR("out of memory\n");
2681 goto end
; /* no progID => not a file type association */
2683 /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
2684 mimeProgId
= heap_printf("%s=>%s", mimeTypeA
, progIdA
);
2687 struct rb_string_entry
*entry
;
2688 if (wine_rb_get(&mimeProgidTree
, mimeProgId
))
2690 HeapFree(GetProcessHeap(), 0, mimeProgId
);
2693 entry
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry
));
2696 WINE_ERR("out of memory allocating rb_string_entry\n");
2699 entry
->string
= mimeProgId
;
2700 if (wine_rb_put(&mimeProgidTree
, mimeProgId
, &entry
->entry
))
2702 WINE_ERR("error updating rb tree\n");
2707 if (has_association_changed(extensionW
, mimeTypeA
, progIdW
, friendlyAppNameA
, openWithIconA
))
2709 char *desktopPath
= heap_printf("%s/wine-extension-%s.desktop", applications_dir
, &extensionA
[1]);
2712 if (write_freedesktop_association_entry(desktopPath
, extensionA
, friendlyAppNameA
, mimeTypeA
, progIdA
, openWithIconA
))
2715 update_association(extensionW
, mimeTypeA
, progIdW
, friendlyAppNameA
, desktopPath
, openWithIconA
);
2717 HeapFree(GetProcessHeap(), 0, desktopPath
);
2722 HeapFree(GetProcessHeap(), 0, extensionA
);
2723 HeapFree(GetProcessHeap(), 0, commandW
);
2724 HeapFree(GetProcessHeap(), 0, executableW
);
2725 HeapFree(GetProcessHeap(), 0, openWithIconA
);
2726 HeapFree(GetProcessHeap(), 0, friendlyDocNameW
);
2727 HeapFree(GetProcessHeap(), 0, friendlyDocNameA
);
2728 HeapFree(GetProcessHeap(), 0, iconW
);
2729 HeapFree(GetProcessHeap(), 0, iconA
);
2730 HeapFree(GetProcessHeap(), 0, contentTypeW
);
2731 HeapFree(GetProcessHeap(), 0, mimeTypeA
);
2732 HeapFree(GetProcessHeap(), 0, friendlyAppNameW
);
2733 HeapFree(GetProcessHeap(), 0, friendlyAppNameA
);
2734 HeapFree(GetProcessHeap(), 0, progIdW
);
2735 HeapFree(GetProcessHeap(), 0, progIdA
);
2737 HeapFree(GetProcessHeap(), 0, extensionW
);
2738 if (ret
!= ERROR_SUCCESS
)
2742 wine_rb_destroy(&mimeProgidTree
, winemenubuilder_rb_destroy
, NULL
);
2743 free_native_mime_types(&nativeMimeTypes
);
2747 static char *get_start_exe_path(void)
2749 static const WCHAR startW
[] = {'\\','c','o','m','m','a','n','d',
2750 '\\','s','t','a','r','t','.','e','x','e',0};
2751 WCHAR start_path
[MAX_PATH
];
2752 GetWindowsDirectoryW(start_path
, MAX_PATH
);
2753 lstrcatW(start_path
, startW
);
2754 return escape(start_path
);
2757 static char* escape_unix_link_arg(LPCSTR unix_link
)
2760 WCHAR
*unix_linkW
= utf8_chars_to_wchars(unix_link
);
2763 char *escaped_lnk
= escape(unix_linkW
);
2766 ret
= heap_printf("/Unix %s", escaped_lnk
);
2767 HeapFree(GetProcessHeap(), 0, escaped_lnk
);
2769 HeapFree(GetProcessHeap(), 0, unix_linkW
);
2774 static BOOL
InvokeShellLinker( IShellLinkW
*sl
, LPCWSTR link
, BOOL bWait
)
2776 static const WCHAR startW
[] = {'\\','c','o','m','m','a','n','d',
2777 '\\','s','t','a','r','t','.','e','x','e',0};
2778 char *link_name
= NULL
, *icon_name
= NULL
, *work_dir
= NULL
;
2779 char *escaped_path
= NULL
, *escaped_args
= NULL
, *description
= NULL
;
2780 char *wmclass
= NULL
;
2781 WCHAR szTmp
[INFOTIPSIZE
];
2782 WCHAR szDescription
[INFOTIPSIZE
], szPath
[MAX_PATH
], szWorkDir
[MAX_PATH
];
2783 WCHAR szArgs
[INFOTIPSIZE
], szIconPath
[MAX_PATH
], szWMClass
[MAX_PATH
];
2784 int iIconId
= 0, r
= -1;
2787 char *unix_link
= NULL
;
2788 char *start_path
= NULL
;
2792 WINE_ERR("Link name is null\n");
2796 if( !GetLinkLocation( link
, &csidl
, &link_name
) )
2798 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link
));
2801 if (!in_desktop_dir(csidl
) && !in_startmenu(csidl
))
2803 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2806 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name
));
2809 IShellLinkW_GetWorkingDirectory( sl
, szTmp
, MAX_PATH
);
2810 ExpandEnvironmentStringsW(szTmp
, szWorkDir
, MAX_PATH
);
2811 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir
));
2814 IShellLinkW_GetDescription( sl
, szTmp
, INFOTIPSIZE
);
2815 ExpandEnvironmentStringsW(szTmp
, szDescription
, INFOTIPSIZE
);
2816 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription
));
2818 get_cmdline( sl
, szTmp
, MAX_PATH
, szArgs
, INFOTIPSIZE
);
2819 ExpandEnvironmentStringsW(szTmp
, szPath
, MAX_PATH
);
2820 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath
));
2821 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs
));
2824 IShellLinkW_GetIconLocation( sl
, szTmp
, MAX_PATH
, &iIconId
);
2825 ExpandEnvironmentStringsW(szTmp
, szIconPath
, MAX_PATH
);
2826 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath
) );
2832 LPITEMIDLIST pidl
= NULL
;
2833 IShellLinkW_GetIDList( sl
, &pidl
);
2834 if( pidl
&& SHGetPathFromIDListW( pidl
, szPath
) )
2835 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath
));
2838 /* extract the icon */
2840 icon_name
= extract_icon( szIconPath
, iIconId
, NULL
, bWait
);
2842 icon_name
= extract_icon( szPath
, iIconId
, NULL
, bWait
);
2844 /* fail - try once again after parent process exit */
2849 WINE_WARN("Unable to extract icon, deferring.\n");
2852 WINE_ERR("failed to extract icon from %s\n",
2853 wine_dbgstr_w( szIconPath
[0] ? szIconPath
: szPath
));
2856 unix_link
= wine_get_unix_file_name(link
);
2857 if (unix_link
== NULL
)
2859 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link
));
2863 /* check the path */
2866 static const WCHAR exeW
[] = {'.','e','x','e',0};
2869 /* check for .exe extension */
2870 if (!(p
= strrchrW( szPath
, '.' )) ||
2871 strchrW( p
, '\\' ) || strchrW( p
, '/' ) ||
2872 lstrcmpiW( p
, exeW
))
2874 /* Not .exe - use 'start.exe' to launch this file */
2875 p
= szArgs
+ lstrlenW(szPath
) + 2;
2879 memmove( p
+1, szArgs
, min( (lstrlenW(szArgs
) + 1) * sizeof(szArgs
[0]),
2880 sizeof(szArgs
) - (p
+ 1 - szArgs
) * sizeof(szArgs
[0]) ) );
2886 lstrcpyW(szArgs
+ 1, szPath
);
2889 GetWindowsDirectoryW(szPath
, MAX_PATH
);
2890 lstrcatW(szPath
, startW
);
2894 /* FIXME: Use AppUserModelID if present. */
2895 WCHAR
*p
= PathFindFileNameW(szPath
);
2897 lstrcpyW(szWMClass
, p
);
2898 CharLowerW(szWMClass
);
2901 /* convert app working dir */
2903 work_dir
= wine_get_unix_file_name( szWorkDir
);
2907 /* if there's no path... try run the link itself */
2908 lstrcpynW(szArgs
, link
, MAX_PATH
);
2909 GetWindowsDirectoryW(szPath
, MAX_PATH
);
2910 lstrcatW(szPath
, startW
);
2913 /* escape the path and parameters */
2914 escaped_path
= escape(szPath
);
2915 escaped_args
= escape(szArgs
);
2916 description
= wchars_to_utf8_chars(szDescription
);
2917 wmclass
= wchars_to_utf8_chars(szWMClass
);
2918 if (escaped_path
== NULL
|| escaped_args
== NULL
|| description
== NULL
|| wmclass
== NULL
)
2920 WINE_ERR("out of memory allocating/escaping parameters\n");
2924 start_path
= get_start_exe_path();
2925 if (start_path
== NULL
)
2927 WINE_ERR("out of memory\n");
2931 /* building multiple menus concurrently has race conditions */
2932 hsem
= CreateSemaphoreA( NULL
, 1, 1, "winemenubuilder_semaphore");
2933 if( WAIT_OBJECT_0
!= MsgWaitForMultipleObjects( 1, &hsem
, FALSE
, INFINITE
, QS_ALLINPUT
) )
2935 WINE_ERR("failed wait for semaphore\n");
2939 if (in_desktop_dir(csidl
))
2942 const char *lastEntry
;
2943 lastEntry
= strrchr(link_name
, '/');
2944 if (lastEntry
== NULL
)
2945 lastEntry
= link_name
;
2948 location
= heap_printf("%s/%s.desktop", xdg_desktop_dir
, lastEntry
);
2951 if (csidl
== CSIDL_COMMON_DESKTOPDIRECTORY
)
2953 char *link_arg
= escape_unix_link_arg(unix_link
);
2956 r
= !write_desktop_entry(unix_link
, location
, lastEntry
,
2957 start_path
, link_arg
, description
, work_dir
, icon_name
, wmclass
);
2958 HeapFree(GetProcessHeap(), 0, link_arg
);
2962 r
= !write_desktop_entry(NULL
, location
, lastEntry
, escaped_path
, escaped_args
, description
, work_dir
, icon_name
, wmclass
);
2964 chmod(location
, 0755);
2965 HeapFree(GetProcessHeap(), 0, location
);
2970 char *link_arg
= escape_unix_link_arg(unix_link
);
2973 r
= !write_menu_entry(unix_link
, link_name
, start_path
, link_arg
, description
, work_dir
, icon_name
, wmclass
);
2974 HeapFree(GetProcessHeap(), 0, link_arg
);
2978 ReleaseSemaphore( hsem
, 1, NULL
);
2981 if (hsem
) CloseHandle( hsem
);
2982 HeapFree( GetProcessHeap(), 0, icon_name
);
2983 HeapFree( GetProcessHeap(), 0, work_dir
);
2984 HeapFree( GetProcessHeap(), 0, link_name
);
2985 HeapFree( GetProcessHeap(), 0, escaped_args
);
2986 HeapFree( GetProcessHeap(), 0, escaped_path
);
2987 HeapFree( GetProcessHeap(), 0, description
);
2988 HeapFree( GetProcessHeap(), 0, wmclass
);
2989 HeapFree( GetProcessHeap(), 0, unix_link
);
2990 HeapFree( GetProcessHeap(), 0, start_path
);
2993 WINE_ERR("failed to build the menu\n" );
2998 static BOOL
InvokeShellLinkerForURL( IUniformResourceLocatorW
*url
, LPCWSTR link
, BOOL bWait
)
3000 char *link_name
= NULL
, *icon_name
= NULL
;
3002 LPWSTR urlPath
= NULL
;
3003 char *escaped_urlPath
= NULL
;
3008 char *unix_link
= NULL
;
3009 IPropertySetStorage
*pPropSetStg
;
3010 IPropertyStorage
*pPropStg
;
3013 char *start_path
= NULL
;
3014 BOOL has_icon
= FALSE
;
3018 WINE_ERR("Link name is null\n");
3022 if( !GetLinkLocation( link
, &csidl
, &link_name
) )
3024 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link
));
3027 if (!in_desktop_dir(csidl
) && !in_startmenu(csidl
))
3029 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
3033 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name
));
3035 hr
= url
->lpVtbl
->GetURL(url
, &urlPath
);
3041 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath
));
3043 unix_link
= wine_get_unix_file_name(link
);
3044 if (unix_link
== NULL
)
3046 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link
));
3050 escaped_urlPath
= escape(urlPath
);
3051 if (escaped_urlPath
== NULL
)
3053 WINE_ERR("couldn't escape url, out of memory\n");
3057 start_path
= get_start_exe_path();
3058 if (start_path
== NULL
)
3060 WINE_ERR("out of memory\n");
3064 ps
[0].ulKind
= PRSPEC_PROPID
;
3065 ps
[0].u
.propid
= PID_IS_ICONFILE
;
3066 ps
[1].ulKind
= PRSPEC_PROPID
;
3067 ps
[1].u
.propid
= PID_IS_ICONINDEX
;
3069 hr
= url
->lpVtbl
->QueryInterface(url
, &IID_IPropertySetStorage
, (void **) &pPropSetStg
);
3072 hr
= IPropertySetStorage_Open(pPropSetStg
, &FMTID_Intshcut
, STGM_READ
| STGM_SHARE_EXCLUSIVE
, &pPropStg
);
3075 hr
= IPropertyStorage_ReadMultiple(pPropStg
, 2, ps
, pv
);
3078 if (pv
[0].vt
== VT_LPWSTR
&& pv
[0].u
.pwszVal
&& pv
[0].u
.pwszVal
[0])
3081 icon_name
= extract_icon( pv
[0].u
.pwszVal
, pv
[1].u
.iVal
, NULL
, bWait
);
3083 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
);
3085 PropVariantClear(&pv
[0]);
3086 PropVariantClear(&pv
[1]);
3088 IPropertyStorage_Release(pPropStg
);
3090 IPropertySetStorage_Release(pPropSetStg
);
3093 /* fail - try once again after parent process exit */
3094 if( has_icon
&& !icon_name
)
3098 WINE_WARN("Unable to extract icon, deferring.\n");
3102 WINE_ERR("failed to extract icon from %s\n",
3103 wine_dbgstr_w( pv
[0].u
.pwszVal
));
3106 hSem
= CreateSemaphoreA( NULL
, 1, 1, "winemenubuilder_semaphore");
3107 if( WAIT_OBJECT_0
!= MsgWaitForMultipleObjects( 1, &hSem
, FALSE
, INFINITE
, QS_ALLINPUT
) )
3109 WINE_ERR("failed wait for semaphore\n");
3112 if (in_desktop_dir(csidl
))
3115 const char *lastEntry
;
3116 lastEntry
= strrchr(link_name
, '/');
3117 if (lastEntry
== NULL
)
3118 lastEntry
= link_name
;
3121 location
= heap_printf("%s/%s.desktop", xdg_desktop_dir
, lastEntry
);
3124 r
= !write_desktop_entry(NULL
, location
, lastEntry
, start_path
, escaped_urlPath
, NULL
, NULL
, icon_name
, NULL
);
3126 chmod(location
, 0755);
3127 HeapFree(GetProcessHeap(), 0, location
);
3131 r
= !write_menu_entry(unix_link
, link_name
, start_path
, escaped_urlPath
, NULL
, NULL
, icon_name
, NULL
);
3133 ReleaseSemaphore(hSem
, 1, NULL
);
3138 HeapFree( GetProcessHeap(), 0, icon_name
);
3139 HeapFree(GetProcessHeap(), 0, link_name
);
3140 CoTaskMemFree( urlPath
);
3141 HeapFree(GetProcessHeap(), 0, escaped_urlPath
);
3142 HeapFree(GetProcessHeap(), 0, unix_link
);
3146 static BOOL
WaitForParentProcess( void )
3148 PROCESSENTRY32 procentry
;
3149 HANDLE hsnapshot
= NULL
, hprocess
= NULL
;
3150 DWORD ourpid
= GetCurrentProcessId();
3151 BOOL ret
= FALSE
, rc
;
3153 WINE_TRACE("Waiting for parent process\n");
3154 if ((hsnapshot
= CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS
, 0 )) ==
3155 INVALID_HANDLE_VALUE
)
3157 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
3161 procentry
.dwSize
= sizeof(PROCESSENTRY32
);
3162 rc
= Process32First( hsnapshot
, &procentry
);
3165 if (procentry
.th32ProcessID
== ourpid
) break;
3166 rc
= Process32Next( hsnapshot
, &procentry
);
3170 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid
);
3174 if ((hprocess
= OpenProcess( SYNCHRONIZE
, FALSE
, procentry
.th32ParentProcessID
)) ==
3177 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry
.th32ParentProcessID
,
3182 if (MsgWaitForMultipleObjects( 1, &hprocess
, FALSE
, INFINITE
, QS_ALLINPUT
) == WAIT_OBJECT_0
)
3185 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
3188 if (hprocess
) CloseHandle( hprocess
);
3189 if (hsnapshot
) CloseHandle( hsnapshot
);
3193 static BOOL
Process_Link( LPCWSTR linkname
, BOOL bWait
)
3198 WCHAR fullname
[MAX_PATH
];
3201 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname
), bWait
);
3205 WINE_ERR("link name missing\n");
3209 len
=GetFullPathNameW( linkname
, MAX_PATH
, fullname
, NULL
);
3210 if (len
==0 || len
>MAX_PATH
)
3212 WINE_ERR("couldn't get full path of link file\n");
3216 r
= CoCreateInstance( &CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
3217 &IID_IShellLinkW
, (LPVOID
*) &sl
);
3220 WINE_ERR("No IID_IShellLink\n");
3224 r
= IShellLinkW_QueryInterface( sl
, &IID_IPersistFile
, (LPVOID
*) &pf
);
3227 WINE_ERR("No IID_IPersistFile\n");
3231 r
= IPersistFile_Load( pf
, fullname
, STGM_READ
);
3232 if( SUCCEEDED( r
) )
3234 /* If something fails (eg. Couldn't extract icon)
3235 * wait for parent process and try again
3237 if( ! InvokeShellLinker( sl
, fullname
, bWait
) && bWait
)
3239 WaitForParentProcess();
3240 InvokeShellLinker( sl
, fullname
, FALSE
);
3245 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname
));
3248 IPersistFile_Release( pf
);
3249 IShellLinkW_Release( sl
);
3254 static BOOL
Process_URL( LPCWSTR urlname
, BOOL bWait
)
3256 IUniformResourceLocatorW
*url
;
3259 WCHAR fullname
[MAX_PATH
];
3262 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname
), bWait
);
3266 WINE_ERR("URL name missing\n");
3270 len
=GetFullPathNameW( urlname
, MAX_PATH
, fullname
, NULL
);
3271 if (len
==0 || len
>MAX_PATH
)
3273 WINE_ERR("couldn't get full path of URL file\n");
3277 r
= CoCreateInstance( &CLSID_InternetShortcut
, NULL
, CLSCTX_INPROC_SERVER
,
3278 &IID_IUniformResourceLocatorW
, (LPVOID
*) &url
);
3281 WINE_ERR("No IID_IUniformResourceLocatorW\n");
3285 r
= url
->lpVtbl
->QueryInterface( url
, &IID_IPersistFile
, (LPVOID
*) &pf
);
3288 WINE_ERR("No IID_IPersistFile\n");
3291 r
= IPersistFile_Load( pf
, fullname
, STGM_READ
);
3292 if( SUCCEEDED( r
) )
3294 /* If something fails (eg. Couldn't extract icon)
3295 * wait for parent process and try again
3297 if( ! InvokeShellLinkerForURL( url
, fullname
, bWait
) && bWait
)
3299 WaitForParentProcess();
3300 InvokeShellLinkerForURL( url
, fullname
, FALSE
);
3304 IPersistFile_Release( pf
);
3305 url
->lpVtbl
->Release( url
);
3310 static void RefreshFileTypeAssociations(void)
3313 char *mime_dir
= NULL
;
3314 char *packages_dir
= NULL
;
3315 char *applications_dir
= NULL
;
3318 hSem
= CreateSemaphoreA( NULL
, 1, 1, "winemenubuilder_semaphore");
3319 if( WAIT_OBJECT_0
!= MsgWaitForMultipleObjects( 1, &hSem
, FALSE
, INFINITE
, QS_ALLINPUT
) )
3321 WINE_ERR("failed wait for semaphore\n");
3327 mime_dir
= heap_printf("%s/mime", xdg_data_dir
);
3328 if (mime_dir
== NULL
)
3330 WINE_ERR("out of memory\n");
3333 create_directories(mime_dir
);
3335 packages_dir
= heap_printf("%s/packages", mime_dir
);
3336 if (packages_dir
== NULL
)
3338 WINE_ERR("out of memory\n");
3341 create_directories(packages_dir
);
3343 applications_dir
= heap_printf("%s/applications", xdg_data_dir
);
3344 if (applications_dir
== NULL
)
3346 WINE_ERR("out of memory\n");
3349 create_directories(applications_dir
);
3351 hasChanged
= generate_associations(xdg_data_dir
, packages_dir
, applications_dir
);
3352 hasChanged
|= cleanup_associations();
3355 const char *argv
[3];
3357 argv
[0] = "update-mime-database";
3360 _spawnvp( _P_DETACH
, argv
[0], argv
);
3362 argv
[0] = "update-desktop-database";
3363 argv
[1] = applications_dir
;
3364 _spawnvp( _P_DETACH
, argv
[0], argv
);
3370 ReleaseSemaphore(hSem
, 1, NULL
);
3373 HeapFree(GetProcessHeap(), 0, mime_dir
);
3374 HeapFree(GetProcessHeap(), 0, packages_dir
);
3375 HeapFree(GetProcessHeap(), 0, applications_dir
);
3378 static void cleanup_menus(void)
3382 hkey
= open_menus_reg_key();
3386 LSTATUS lret
= ERROR_SUCCESS
;
3387 for (i
= 0; lret
== ERROR_SUCCESS
; )
3389 WCHAR
*value
= NULL
;
3391 DWORD valueSize
= 4096;
3392 DWORD dataSize
= 4096;
3395 lret
= ERROR_OUTOFMEMORY
;
3396 value
= HeapAlloc(GetProcessHeap(), 0, valueSize
* sizeof(WCHAR
));
3399 data
= HeapAlloc(GetProcessHeap(), 0, dataSize
* sizeof(WCHAR
));
3402 lret
= RegEnumValueW(hkey
, i
, value
, &valueSize
, NULL
, NULL
, (BYTE
*)data
, &dataSize
);
3403 if (lret
!= ERROR_MORE_DATA
)
3407 HeapFree(GetProcessHeap(), 0, value
);
3408 HeapFree(GetProcessHeap(), 0, data
);
3409 value
= data
= NULL
;
3411 if (lret
== ERROR_SUCCESS
)
3415 unix_file
= wchars_to_unix_chars(value
);
3416 windows_file
= wchars_to_unix_chars(data
);
3417 if (unix_file
!= NULL
&& windows_file
!= NULL
)
3419 struct stat filestats
;
3420 if (stat(windows_file
, &filestats
) < 0 && errno
== ENOENT
)
3422 WINE_TRACE("removing menu related file %s\n", unix_file
);
3424 RegDeleteValueW(hkey
, value
);
3431 WINE_ERR("out of memory enumerating menus\n");
3432 lret
= ERROR_OUTOFMEMORY
;
3434 HeapFree(GetProcessHeap(), 0, unix_file
);
3435 HeapFree(GetProcessHeap(), 0, windows_file
);
3437 else if (lret
!= ERROR_NO_MORE_ITEMS
)
3438 WINE_ERR("error %d reading registry\n", lret
);
3439 HeapFree(GetProcessHeap(), 0, value
);
3440 HeapFree(GetProcessHeap(), 0, data
);
3445 WINE_ERR("error opening registry key, menu cleanup failed\n");
3448 static void thumbnail_lnk(LPCWSTR lnkPath
, LPCWSTR outputPath
)
3450 char *utf8lnkPath
= NULL
;
3451 char *utf8OutputPath
= NULL
;
3452 WCHAR
*winLnkPath
= NULL
;
3453 IShellLinkW
*shellLink
= NULL
;
3454 IPersistFile
*persistFile
= NULL
;
3455 WCHAR szTmp
[MAX_PATH
];
3456 WCHAR szPath
[MAX_PATH
];
3457 WCHAR szArgs
[INFOTIPSIZE
];
3458 WCHAR szIconPath
[MAX_PATH
];
3460 IStream
*stream
= NULL
;
3461 ICONDIRENTRY
*pIconDirEntries
= NULL
;
3465 utf8lnkPath
= wchars_to_utf8_chars(lnkPath
);
3466 if (utf8lnkPath
== NULL
)
3468 WINE_ERR("out of memory converting paths\n");
3472 utf8OutputPath
= wchars_to_utf8_chars(outputPath
);
3473 if (utf8OutputPath
== NULL
)
3475 WINE_ERR("out of memory converting paths\n");
3479 winLnkPath
= wine_get_dos_file_name(utf8lnkPath
);
3480 if (winLnkPath
== NULL
)
3482 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath
);
3486 hr
= CoCreateInstance(&CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
3487 &IID_IShellLinkW
, (LPVOID
*)&shellLink
);
3490 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr
);
3494 hr
= IShellLinkW_QueryInterface(shellLink
, &IID_IPersistFile
, (LPVOID
)&persistFile
);
3497 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr
);
3501 hr
= IPersistFile_Load(persistFile
, winLnkPath
, STGM_READ
);
3504 WINE_ERR("could not read .lnk, error 0x%08X\n", hr
);
3508 get_cmdline(shellLink
, szTmp
, MAX_PATH
, szArgs
, INFOTIPSIZE
);
3509 ExpandEnvironmentStringsW(szTmp
, szPath
, MAX_PATH
);
3511 IShellLinkW_GetIconLocation(shellLink
, szTmp
, MAX_PATH
, &iconId
);
3512 ExpandEnvironmentStringsW(szTmp
, szIconPath
, MAX_PATH
);
3516 LPITEMIDLIST pidl
= NULL
;
3517 IShellLinkW_GetIDList(shellLink
, &pidl
);
3518 if (pidl
&& SHGetPathFromIDListW(pidl
, szPath
))
3519 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath
));
3524 hr
= open_icon(szIconPath
, iconId
, FALSE
, &stream
, &pIconDirEntries
, &numEntries
);
3526 hr
= write_native_icon(stream
, pIconDirEntries
, numEntries
, utf8OutputPath
, NULL
);
3530 hr
= open_icon(szPath
, iconId
, FALSE
, &stream
, &pIconDirEntries
, &numEntries
);
3532 hr
= write_native_icon(stream
, pIconDirEntries
, numEntries
, utf8OutputPath
, NULL
);
3536 HeapFree(GetProcessHeap(), 0, utf8lnkPath
);
3537 HeapFree(GetProcessHeap(), 0, utf8OutputPath
);
3538 HeapFree(GetProcessHeap(), 0, winLnkPath
);
3539 if (shellLink
!= NULL
)
3540 IShellLinkW_Release(shellLink
);
3541 if (persistFile
!= NULL
)
3542 IPersistFile_Release(persistFile
);
3544 IStream_Release(stream
);
3545 HeapFree(GetProcessHeap(), 0, pIconDirEntries
);
3548 static WCHAR
*next_token( LPWSTR
*p
)
3550 LPWSTR token
= NULL
, t
= *p
;
3555 while( t
&& !token
)
3563 /* unquote the token */
3565 t
= strchrW( token
, '"' );
3574 t
= strchrW( token
, ' ' );
3584 static BOOL
init_xdg(void)
3586 WCHAR shellDesktopPath
[MAX_PATH
];
3587 HRESULT hr
= SHGetFolderPathW(NULL
, CSIDL_DESKTOP
, NULL
, SHGFP_TYPE_CURRENT
, shellDesktopPath
);
3589 xdg_desktop_dir
= wine_get_unix_file_name(shellDesktopPath
);
3590 if (xdg_desktop_dir
== NULL
)
3592 WINE_ERR("error looking up the desktop directory\n");
3596 if (getenv("XDG_CONFIG_HOME"))
3597 xdg_config_dir
= heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3599 xdg_config_dir
= heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3602 create_directories(xdg_config_dir
);
3603 if (getenv("XDG_DATA_HOME"))
3604 xdg_data_dir
= strdupA(getenv("XDG_DATA_HOME"));
3606 xdg_data_dir
= heap_printf("%s/.local/share", getenv("HOME"));
3610 create_directories(xdg_data_dir
);
3611 buffer
= heap_printf("%s/desktop-directories", xdg_data_dir
);
3614 mkdir(buffer
, 0777);
3615 HeapFree(GetProcessHeap(), 0, buffer
);
3619 HeapFree(GetProcessHeap(), 0, xdg_config_dir
);
3621 WINE_ERR("out of memory\n");
3625 static BOOL
associations_enabled(void)
3632 if ((hkey
= open_associations_reg_key()))
3635 if (!RegQueryValueExA(hkey
, "Enable", NULL
, NULL
, buf
, &len
))
3636 ret
= IS_OPTION_TRUE(buf
[0]);
3637 RegCloseKey( hkey
);
3643 /***********************************************************************
3647 int PASCAL
wWinMain (HINSTANCE hInstance
, HINSTANCE prev
, LPWSTR cmdline
, int show
)
3649 static const WCHAR dash_aW
[] = {'-','a',0};
3650 static const WCHAR dash_rW
[] = {'-','r',0};
3651 static const WCHAR dash_tW
[] = {'-','t',0};
3652 static const WCHAR dash_uW
[] = {'-','u',0};
3653 static const WCHAR dash_wW
[] = {'-','w',0};
3655 LPWSTR token
= NULL
, p
;
3664 hr
= CoInitialize(NULL
);
3667 WINE_ERR("could not initialize COM, error 0x%08X\n", hr
);
3671 for( p
= cmdline
; p
&& *p
; )
3673 token
= next_token( &p
);
3676 if( !strcmpW( token
, dash_aW
) )
3678 if (associations_enabled())
3679 RefreshFileTypeAssociations();
3682 if( !strcmpW( token
, dash_rW
) )
3687 if( !strcmpW( token
, dash_wW
) )
3689 else if ( !strcmpW( token
, dash_uW
) )
3691 else if ( !strcmpW( token
, dash_tW
) )
3693 WCHAR
*lnkFile
= next_token( &p
);
3696 WCHAR
*outputFile
= next_token( &p
);
3698 thumbnail_lnk(lnkFile
, outputFile
);
3701 else if( token
[0] == '-' )
3703 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token
) );
3710 bRet
= Process_URL( token
, bWait
);
3712 bRet
= Process_Link( token
, bWait
);
3715 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token
) );