mshtml: Add the Serbian (Latin and Cyrillic) translation.
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blobbf40c895c780016278b954bc359e2280aa941e97
1 /*
2 * Helper program to build unix menu entries
4 * Copyright 1997 Marcus Meissner
5 * Copyright 1998 Juergen Schmied
6 * Copyright 2003 Mike McCormack for CodeWeavers
7 * Copyright 2004 Dmitry Timoshkov
8 * Copyright 2005 Bill Medland
9 * Copyright 2008 Damjan Jovanovic
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 * This program is used to replicate the Windows desktop and start menu
27 * into the native desktop's copies. Desktop entries are merged directly
28 * into the native desktop. The Windows Start Menu corresponds to a Wine
29 * entry within the native "start" menu and replicates the whole tree
30 * structure of the Windows Start Menu. Currently it does not differentiate
31 * between the user's desktop/start menu and the "All Users" copies.
33 * This program will read a Windows shortcut file using the IShellLink
34 * interface, then create a KDE/Gnome menu entry for the shortcut.
36 * winemenubuilder [ -w ] <shortcut.lnk>
38 * If the -w parameter is passed, and the shortcut cannot be created,
39 * this program will wait for the parent process to finish and then try
40 * again. This covers the case when a ShortCut is created before the
41 * executable containing its icon.
43 * TODO
44 * Handle data lnk files. There is no icon in the file; the icon is in
45 * the handler for the file type (or pointed to by the lnk file). Also it
46 * might be better to use a native handler (e.g. a native acroread for pdf
47 * files).
48 * Differentiate between the user's entries and the "All Users" entries.
49 * If it is possible to add the desktop files to the native system's
50 * shared location for an "All Users" entry then do so. As a suggestion the
51 * shared menu Wine base could be writable to the wine group, or a wineadm
52 * group.
53 * Clean up fd.o menu icons and .directory files when the menu is deleted
54 * in Windows.
55 * Generate icons for file open handlers to go into the "Open with..."
56 * list. What does Windows use, the default icon for the .EXE file? It's
57 * not in the registry.
58 * Associate applications under HKCR\Applications to open any MIME type
59 * (by associating with application/octet-stream, or how?).
60 * Clean up fd.o MIME types when they are deleted in Windows, their icons
61 * too. Very hard - once we associate them with fd.o, we can't tell whether
62 * they are ours or not, and the extension <-> MIME type mapping isn't
63 * one-to-one either.
64 * Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
65 * that write associations there won't associate (#17019).
68 #include "config.h"
69 #include "wine/port.h"
71 #include <ctype.h>
72 #include <stdio.h>
73 #include <string.h>
74 #ifdef HAVE_UNISTD_H
75 #include <unistd.h>
76 #endif
77 #include <errno.h>
78 #include <stdarg.h>
79 #ifdef HAVE_FNMATCH_H
80 #include <fnmatch.h>
81 #endif
83 #define COBJMACROS
85 #include <windows.h>
86 #include <shlobj.h>
87 #include <objidl.h>
88 #include <shlguid.h>
89 #include <appmgmt.h>
90 #include <tlhelp32.h>
91 #include <intshcut.h>
92 #include <shlwapi.h>
93 #include <initguid.h>
94 #include <wincodec.h>
96 #include "wine/unicode.h"
97 #include "wine/debug.h"
98 #include "wine/library.h"
99 #include "wine/list.h"
101 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
103 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
104 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
105 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
106 (csidl)==CSIDL_COMMON_STARTMENU)
108 /* link file formats */
110 #include "pshpack1.h"
112 typedef struct
114 BYTE bWidth;
115 BYTE bHeight;
116 BYTE bColorCount;
117 BYTE bReserved;
118 WORD wPlanes;
119 WORD wBitCount;
120 DWORD dwBytesInRes;
121 WORD nID;
122 } GRPICONDIRENTRY;
124 typedef struct
126 WORD idReserved;
127 WORD idType;
128 WORD idCount;
129 GRPICONDIRENTRY idEntries[1];
130 } GRPICONDIR;
132 typedef struct
134 BYTE bWidth;
135 BYTE bHeight;
136 BYTE bColorCount;
137 BYTE bReserved;
138 WORD wPlanes;
139 WORD wBitCount;
140 DWORD dwBytesInRes;
141 DWORD dwImageOffset;
142 } ICONDIRENTRY;
144 typedef struct
146 WORD idReserved;
147 WORD idType;
148 WORD idCount;
149 } ICONDIR;
152 #include "poppack.h"
154 typedef struct
156 HRSRC *pResInfo;
157 int nIndex;
158 } ENUMRESSTRUCT;
160 struct xdg_mime_type
162 char *mimeType;
163 char *glob;
164 struct list entry;
167 DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);
169 static char *xdg_config_dir;
170 static char *xdg_data_dir;
171 static char *xdg_desktop_dir;
173 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra);
174 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream);
176 /* Utility routines */
177 static unsigned short crc16(const char* string)
179 unsigned short crc = 0;
180 int i, j, xor_poly;
182 for (i = 0; string[i] != 0; i++)
184 char c = string[i];
185 for (j = 0; j < 8; c >>= 1, j++)
187 xor_poly = (c ^ crc) & 1;
188 crc >>= 1;
189 if (xor_poly)
190 crc ^= 0xa001;
193 return crc;
196 static char *strdupA( const char *str )
198 char *ret;
200 if (!str) return NULL;
201 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
202 return ret;
205 static char* heap_printf(const char *format, ...)
207 va_list args;
208 int size = 4096;
209 char *buffer, *ret;
210 int n;
212 va_start(args, format);
213 while (1)
215 buffer = HeapAlloc(GetProcessHeap(), 0, size);
216 if (buffer == NULL)
217 break;
218 n = vsnprintf(buffer, size, format, args);
219 if (n == -1)
220 size *= 2;
221 else if (n >= size)
222 size = n + 1;
223 else
224 break;
225 HeapFree(GetProcessHeap(), 0, buffer);
227 va_end(args);
228 if (!buffer) return NULL;
229 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
230 if (!ret) ret = buffer;
231 return ret;
234 static void write_xml_text(FILE *file, const char *text)
236 int i;
237 for (i = 0; text[i]; i++)
239 if (text[i] == '&')
240 fputs("&amp;", file);
241 else if (text[i] == '<')
242 fputs("&lt;", file);
243 else if (text[i] == '>')
244 fputs("&gt;", file);
245 else if (text[i] == '\'')
246 fputs("&apos;", file);
247 else if (text[i] == '"')
248 fputs("&quot;", file);
249 else
250 fputc(text[i], file);
254 static BOOL create_directories(char *directory)
256 BOOL ret = TRUE;
257 int i;
259 for (i = 0; directory[i]; i++)
261 if (i > 0 && directory[i] == '/')
263 directory[i] = 0;
264 mkdir(directory, 0777);
265 directory[i] = '/';
268 if (mkdir(directory, 0777) && errno != EEXIST)
269 ret = FALSE;
271 return ret;
274 static char* wchars_to_utf8_chars(LPCWSTR string)
276 char *ret;
277 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
278 ret = HeapAlloc(GetProcessHeap(), 0, size);
279 if (ret)
280 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
281 return ret;
284 static char* wchars_to_unix_chars(LPCWSTR string)
286 char *ret;
287 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
288 ret = HeapAlloc(GetProcessHeap(), 0, size);
289 if (ret)
290 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
291 return ret;
294 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
296 WCHAR *ret;
297 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
298 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
299 if (ret)
300 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
301 return ret;
304 /* Icon extraction routines
306 * FIXME: should use PrivateExtractIcons and friends
307 * FIXME: should not use stdio
310 static HRESULT convert_to_native_icon(IStream *icoFile, int *indeces, int numIndeces,
311 const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
313 WCHAR *dosOutputFileName = NULL;
314 IWICImagingFactory *factory = NULL;
315 IWICBitmapDecoder *decoder = NULL;
316 IWICBitmapEncoder *encoder = NULL;
317 IStream *outputFile = NULL;
318 int i;
319 HRESULT hr = E_FAIL;
321 dosOutputFileName = wine_get_dos_file_name(outputFileName);
322 if (dosOutputFileName == NULL)
324 WINE_ERR("error converting %s to DOS file name\n", outputFileName);
325 goto end;
327 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
328 &IID_IWICImagingFactory, (void**)&factory);
329 if (FAILED(hr))
331 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
332 goto end;
334 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
335 WICDecodeMetadataCacheOnDemand, &decoder);
336 if (FAILED(hr))
338 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
339 goto end;
341 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
342 &IID_IWICBitmapEncoder, (void**)&encoder);
343 if (FAILED(hr))
345 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
346 goto end;
348 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
349 if (FAILED(hr))
351 WINE_ERR("error 0x%08X creating output file\n", hr);
352 goto end;
354 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, GENERIC_WRITE);
355 if (FAILED(hr))
357 WINE_ERR("error 0x%08X initializing encoder\n", hr);
358 goto end;
361 for (i = 0; i < numIndeces; i++)
363 IWICBitmapFrameDecode *sourceFrame = NULL;
364 IWICBitmapSource *sourceBitmap = NULL;
365 IWICBitmapFrameEncode *dstFrame = NULL;
366 IPropertyBag2 *options = NULL;
367 UINT width, height;
369 hr = IWICBitmapDecoder_GetFrame(decoder, indeces[i], &sourceFrame);
370 if (FAILED(hr))
372 WINE_ERR("error 0x%08X getting frame %d\n", hr, indeces[i]);
373 goto endloop;
375 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
376 if (FAILED(hr))
378 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
379 goto endloop;
381 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
382 if (FAILED(hr))
384 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
385 goto endloop;
387 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
388 if (FAILED(hr))
390 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
391 goto endloop;
393 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
394 if (FAILED(hr))
396 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
397 goto endloop;
399 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
400 if (FAILED(hr))
402 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
403 goto endloop;
405 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
406 if (FAILED(hr))
408 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
409 goto endloop;
411 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
412 if (FAILED(hr))
414 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
415 goto endloop;
417 hr = IWICBitmapFrameEncode_Commit(dstFrame);
418 if (FAILED(hr))
420 WINE_ERR("error 0x%08X committing frame\n", hr);
421 goto endloop;
423 endloop:
424 if (sourceFrame)
425 IWICBitmapFrameDecode_Release(sourceFrame);
426 if (sourceBitmap)
427 IWICBitmapSource_Release(sourceBitmap);
428 if (dstFrame)
429 IWICBitmapFrameEncode_Release(dstFrame);
432 hr = IWICBitmapEncoder_Commit(encoder);
433 if (FAILED(hr))
435 WINE_ERR("error 0x%08X committing encoder\n", hr);
436 goto end;
439 end:
440 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
441 if (factory)
442 IWICImagingFactory_Release(factory);
443 if (decoder)
444 IWICBitmapDecoder_Release(decoder);
445 if (encoder)
446 IWICBitmapEncoder_Release(encoder);
447 if (outputFile)
448 IStream_Release(outputFile);
449 return hr;
452 static IStream *add_module_icons_to_stream(HMODULE hModule, GRPICONDIR *grpIconDir)
454 int i;
455 SIZE_T iconsSize = 0;
456 BYTE *icons = NULL;
457 ICONDIRENTRY *iconDirEntries = NULL;
458 IStream *stream = NULL;
459 HRESULT hr = E_FAIL;
460 ULONG bytesWritten;
461 ICONDIR iconDir;
462 SIZE_T iconOffset;
463 int validEntries = 0;
464 LARGE_INTEGER zero;
466 for (i = 0; i < grpIconDir->idCount; i++)
467 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
468 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
469 if (icons == NULL)
471 WINE_ERR("out of memory allocating icon\n");
472 goto end;
475 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
476 if (iconDirEntries == NULL)
478 WINE_ERR("out of memory allocating icon dir entries\n");
479 goto end;
482 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
483 if (FAILED(hr))
485 WINE_ERR("error creating icon stream\n");
486 goto end;
489 iconOffset = 0;
490 for (i = 0; i < grpIconDir->idCount; i++)
492 HRSRC hResInfo;
493 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
494 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
496 HGLOBAL hResData;
497 if ((hResData = LoadResource(hModule, hResInfo)))
499 BITMAPINFO *pIcon;
500 if ((pIcon = LockResource(hResData)))
502 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
503 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
504 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
505 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
506 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
507 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
508 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
509 iconDirEntries[validEntries].dwImageOffset = iconOffset;
510 validEntries++;
511 memcpy(&icons[iconOffset], pIcon, grpIconDir->idEntries[i].dwBytesInRes);
512 iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
514 FreeResource(hResData);
519 if (validEntries == 0)
521 WINE_ERR("no valid icon entries\n");
522 goto end;
525 iconDir.idReserved = 0;
526 iconDir.idType = 1;
527 iconDir.idCount = validEntries;
528 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
529 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
531 WINE_ERR("error 0x%08X writing icon stream\n", hr);
532 goto end;
534 for (i = 0; i < validEntries; i++)
535 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
536 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
537 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
539 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
540 goto end;
542 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
543 if (FAILED(hr) || bytesWritten != iconOffset)
545 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
546 goto end;
548 zero.QuadPart = 0;
549 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
551 end:
552 HeapFree(GetProcessHeap(), 0, icons);
553 HeapFree(GetProcessHeap(), 0, iconDirEntries);
554 if (FAILED(hr) && stream != NULL)
556 IStream_Release(stream);
557 stream = NULL;
559 return stream;
562 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
564 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
566 if (!sEnumRes->nIndex--)
568 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
569 return FALSE;
571 else
572 return TRUE;
575 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
577 HMODULE hModule;
578 HRSRC hResInfo;
579 HGLOBAL hResData;
580 GRPICONDIR *pIconDir;
581 ENUMRESSTRUCT sEnumRes;
582 HRESULT hr = E_FAIL;
584 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
585 if (!hModule)
587 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
588 wine_dbgstr_w(szFileName), GetLastError());
589 return HRESULT_FROM_WIN32(GetLastError());
592 if (nIndex < 0)
594 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
595 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
596 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
598 else
600 hResInfo=NULL;
601 sEnumRes.pResInfo = &hResInfo;
602 sEnumRes.nIndex = nIndex;
603 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
604 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
605 sEnumRes.nIndex != -1)
607 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
611 if (hResInfo)
613 if ((hResData = LoadResource(hModule, hResInfo)))
615 if ((pIconDir = LockResource(hResData)))
617 *ppStream = add_module_icons_to_stream(hModule, pIconDir);
618 if (*ppStream)
619 hr = S_OK;
622 FreeResource(hResData);
625 else
627 WINE_WARN("found no icon\n");
628 FreeLibrary(hModule);
629 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
632 FreeLibrary(hModule);
633 return hr;
636 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
638 ICONDIR iconDir;
639 ULONG bytesRead;
640 HRESULT hr;
642 *ppIconDirEntries = NULL;
644 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
645 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
646 (iconDir.idReserved != 0) || (iconDir.idType != 1))
648 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
649 hr = E_FAIL;
650 goto end;
652 *numEntries = iconDir.idCount;
654 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
656 hr = E_OUTOFMEMORY;
657 goto end;
659 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
660 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
662 if (SUCCEEDED(hr)) hr = E_FAIL;
663 goto end;
666 end:
667 if (FAILED(hr))
668 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
669 return hr;
672 static HRESULT write_native_icon(IStream *iconStream, const char *icon_name, LPCWSTR szFileName)
674 ICONDIRENTRY *pIconDirEntry = NULL;
675 int numEntries;
676 int nMax = 0, nMaxBits = 0;
677 int nIndex = 0;
678 int i;
679 LARGE_INTEGER position;
680 HRESULT hr;
682 hr = read_ico_direntries(iconStream, &pIconDirEntry, &numEntries);
683 if (FAILED(hr))
684 goto end;
686 for (i = 0; i < numEntries; i++)
688 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
689 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
690 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
692 nIndex = i;
693 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
694 nMaxBits = pIconDirEntry[i].wBitCount;
697 WINE_TRACE("Selected: %d\n", nIndex);
699 position.QuadPart = 0;
700 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
701 if (FAILED(hr))
702 goto end;
703 hr = convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
705 end:
706 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
707 return hr;
710 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
712 WCHAR *extension;
713 WCHAR *icon = NULL;
714 WCHAR *comma;
715 WCHAR *executable = NULL;
716 int index = 0;
717 char *output_path = NULL;
718 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
720 extension = strrchrW(szFileName, '.');
721 if (extension == NULL)
722 goto end;
724 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
725 if (icon)
727 comma = strrchrW(icon, ',');
728 if (comma)
730 *comma = 0;
731 index = atoiW(comma + 1);
733 hr = open_icon(icon, index, FALSE, ppStream);
735 else
737 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, NULL);
738 if (executable)
739 hr = open_icon(executable, 0, FALSE, ppStream);
742 end:
743 HeapFree(GetProcessHeap(), 0, icon);
744 HeapFree(GetProcessHeap(), 0, executable);
745 HeapFree(GetProcessHeap(), 0, output_path);
746 return hr;
749 static HRESULT open_default_icon(IStream **ppStream)
751 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
753 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
756 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream)
758 HRESULT hr;
760 hr = open_module_icon(filename, index, ppStream);
761 if (FAILED(hr))
763 static const WCHAR dot_icoW[] = {'.','i','c','o',0};
764 int len = strlenW(filename);
765 if (len >= 4 && strcmpiW(&filename[len - 4], dot_icoW) == 0)
766 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
768 if (FAILED(hr))
769 hr = open_file_type_icon(filename, ppStream);
770 if (FAILED(hr) && !bWait)
771 hr = open_default_icon(ppStream);
772 return hr;
775 #ifdef __APPLE__
776 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex,
777 int bestIndex, LPCWSTR icoPathW,
778 const char *destFilename, char **nativeIdentifier)
780 GUID guid;
781 WCHAR *guidStrW = NULL;
782 char *guidStrA = NULL;
783 char *icnsPath = NULL;
784 LARGE_INTEGER zero;
785 HRESULT hr;
787 hr = CoCreateGuid(&guid);
788 if (FAILED(hr))
790 WINE_WARN("CoCreateGuid failed, error 0x%08X\n", hr);
791 goto end;
793 hr = StringFromCLSID(&guid, &guidStrW);
794 if (FAILED(hr))
796 WINE_WARN("StringFromCLSID failed, error 0x%08X\n", hr);
797 goto end;
799 guidStrA = wchars_to_utf8_chars(guidStrW);
800 if (guidStrA == NULL)
802 hr = E_OUTOFMEMORY;
803 WINE_WARN("out of memory converting GUID string\n");
804 goto end;
806 icnsPath = heap_printf("/tmp/%s.icns", guidStrA);
807 if (icnsPath == NULL)
809 hr = E_OUTOFMEMORY;
810 WINE_WARN("out of memory creating ICNS path\n");
811 goto end;
813 zero.QuadPart = 0;
814 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
815 if (FAILED(hr))
817 WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
818 goto end;
820 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICIcnsEncoder,
821 icnsPath, icoPathW);
822 if (FAILED(hr))
824 WINE_WARN("converting %s to %s failed, error 0x%08X\n",
825 wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
826 goto end;
829 end:
830 CoTaskMemFree(guidStrW);
831 HeapFree(GetProcessHeap(), 0, guidStrA);
832 if (SUCCEEDED(hr))
833 *nativeIdentifier = icnsPath;
834 else
835 HeapFree(GetProcessHeap(), 0, icnsPath);
836 return hr;
838 #else
839 static HRESULT platform_write_icon(IStream *icoStream, int exeIndex,
840 int bestIndex, LPCWSTR icoPathW,
841 const char *destFilename, char **nativeIdentifier)
843 char *icoPathA = NULL;
844 char *iconsDir = NULL;
845 char *pngPath = NULL;
846 unsigned short crc;
847 char *p, *q;
848 HRESULT hr = S_OK;
849 LARGE_INTEGER zero;
851 icoPathA = wchars_to_utf8_chars(icoPathW);
852 if (icoPathA == NULL)
854 hr = E_OUTOFMEMORY;
855 goto end;
857 crc = crc16(icoPathA);
858 p = strrchr(icoPathA, '\\');
859 if (p == NULL)
860 p = icoPathA;
861 else
863 *p = 0;
864 p++;
866 q = strrchr(p, '.');
867 if (q)
868 *q = 0;
869 if (destFilename)
870 *nativeIdentifier = heap_printf("%s", destFilename);
871 else
872 *nativeIdentifier = heap_printf("%04X_%s.%d", crc, p, exeIndex);
873 if (*nativeIdentifier == NULL)
875 hr = E_OUTOFMEMORY;
876 goto end;
878 iconsDir = heap_printf("%s/icons", xdg_data_dir);
879 if (iconsDir == NULL)
881 hr = E_OUTOFMEMORY;
882 goto end;
884 create_directories(iconsDir);
885 pngPath = heap_printf("%s/%s.png", iconsDir, *nativeIdentifier);
886 if (pngPath == NULL)
888 hr = E_OUTOFMEMORY;
889 goto end;
891 zero.QuadPart = 0;
892 hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
893 if (FAILED(hr))
894 goto end;
895 hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
896 pngPath, icoPathW);
898 end:
899 HeapFree(GetProcessHeap(), 0, icoPathA);
900 HeapFree(GetProcessHeap(), 0, iconsDir);
901 HeapFree(GetProcessHeap(), 0, pngPath);
902 return hr;
904 #endif /* defined(__APPLE__) */
906 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
907 static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
909 IStream *stream = NULL;
910 HRESULT hr;
911 char *nativeIdentifier = NULL;
912 ICONDIRENTRY *iconDirEntries = NULL;
913 int numEntries;
914 int bestIndex = -1;
915 int maxPixels = 0;
916 int maxBits = 0;
917 int i;
919 WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
921 hr = open_icon(icoPathW, index, bWait, &stream);
922 if (FAILED(hr))
924 WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
925 goto end;
927 hr = read_ico_direntries(stream, &iconDirEntries, &numEntries);
928 if (FAILED(hr))
929 goto end;
930 for (i = 0; i < numEntries; i++)
932 WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
933 iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);
934 if (iconDirEntries[i].wBitCount >= maxBits &&
935 (iconDirEntries[i].bHeight * iconDirEntries[i].bWidth) >= maxPixels)
937 bestIndex = i;
938 maxPixels = iconDirEntries[i].bHeight * iconDirEntries[i].bWidth;
939 maxBits = iconDirEntries[i].wBitCount;
942 WINE_TRACE("Selected: %d\n", bestIndex);
943 hr = platform_write_icon(stream, index, bestIndex, icoPathW, destFilename, &nativeIdentifier);
944 if (FAILED(hr))
945 WINE_WARN("writing icon failed, error 0x%08X\n", hr);
947 end:
948 if (stream)
949 IStream_Release(stream);
950 HeapFree(GetProcessHeap(), 0, iconDirEntries);
951 if (FAILED(hr))
953 HeapFree(GetProcessHeap(), 0, nativeIdentifier);
954 nativeIdentifier = NULL;
956 return nativeIdentifier;
959 static HKEY open_menus_reg_key(void)
961 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
962 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
963 HKEY assocKey;
964 DWORD ret;
965 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
966 if (ret == ERROR_SUCCESS)
967 return assocKey;
968 SetLastError(ret);
969 return NULL;
972 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
974 WCHAR *unix_fileW;
975 WCHAR *windows_fileW;
976 INT size;
977 DWORD ret;
979 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
980 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
981 if (unix_fileW)
983 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
984 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
985 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
986 if (windows_fileW)
988 HKEY hkey;
989 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
990 hkey = open_menus_reg_key();
991 if (hkey)
993 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
994 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
995 RegCloseKey(hkey);
997 else
998 ret = GetLastError();
999 HeapFree(GetProcessHeap(), 0, windows_fileW);
1001 else
1002 ret = ERROR_NOT_ENOUGH_MEMORY;
1003 HeapFree(GetProcessHeap(), 0, unix_fileW);
1005 else
1006 ret = ERROR_NOT_ENOUGH_MEMORY;
1007 return ret;
1010 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1011 const char *path, const char *args, const char *descr,
1012 const char *workdir, const char *icon)
1014 FILE *file;
1016 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1017 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1018 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1020 file = fopen(location, "w");
1021 if (file == NULL)
1022 return FALSE;
1024 fprintf(file, "[Desktop Entry]\n");
1025 fprintf(file, "Name=%s\n", linkname);
1026 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1027 wine_get_config_dir(), path, args);
1028 fprintf(file, "Type=Application\n");
1029 fprintf(file, "StartupNotify=true\n");
1030 if (descr && lstrlenA(descr))
1031 fprintf(file, "Comment=%s\n", descr);
1032 if (workdir && lstrlenA(workdir))
1033 fprintf(file, "Path=%s\n", workdir);
1034 if (icon && lstrlenA(icon))
1035 fprintf(file, "Icon=%s\n", icon);
1037 fclose(file);
1039 if (unix_link)
1041 DWORD ret = register_menus_entry(location, unix_link);
1042 if (ret != ERROR_SUCCESS)
1043 return FALSE;
1046 return TRUE;
1049 static BOOL write_directory_entry(const char *directory, const char *location)
1051 FILE *file;
1053 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1055 file = fopen(location, "w");
1056 if (file == NULL)
1057 return FALSE;
1059 fprintf(file, "[Desktop Entry]\n");
1060 fprintf(file, "Type=Directory\n");
1061 if (strcmp(directory, "wine") == 0)
1063 fprintf(file, "Name=Wine\n");
1064 fprintf(file, "Icon=wine\n");
1066 else
1068 fprintf(file, "Name=%s\n", directory);
1069 fprintf(file, "Icon=folder\n");
1072 fclose(file);
1073 return TRUE;
1076 static BOOL write_menu_file(const char *unix_link, const char *filename)
1078 char *tempfilename;
1079 FILE *tempfile = NULL;
1080 char *lastEntry;
1081 char *name = NULL;
1082 char *menuPath = NULL;
1083 int i;
1084 int count = 0;
1085 BOOL ret = FALSE;
1087 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1089 while (1)
1091 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1092 if (tempfilename)
1094 int tempfd = mkstemps(tempfilename, 0);
1095 if (tempfd >= 0)
1097 tempfile = fdopen(tempfd, "w");
1098 if (tempfile)
1099 break;
1100 close(tempfd);
1101 goto end;
1103 else if (errno == EEXIST)
1105 HeapFree(GetProcessHeap(), 0, tempfilename);
1106 continue;
1108 HeapFree(GetProcessHeap(), 0, tempfilename);
1110 return FALSE;
1113 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1114 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1115 fprintf(tempfile, "<Menu>\n");
1116 fprintf(tempfile, " <Name>Applications</Name>\n");
1118 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1119 if (name == NULL) goto end;
1120 lastEntry = name;
1121 for (i = 0; filename[i]; i++)
1123 name[i] = filename[i];
1124 if (filename[i] == '/')
1126 char *dir_file_name;
1127 struct stat st;
1128 name[i] = 0;
1129 fprintf(tempfile, " <Menu>\n");
1130 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1131 write_xml_text(tempfile, name);
1132 fprintf(tempfile, "</Name>\n");
1133 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1134 write_xml_text(tempfile, name);
1135 fprintf(tempfile, ".directory</Directory>\n");
1136 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1137 xdg_data_dir, count ? "" : "wine-", name);
1138 if (dir_file_name)
1140 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1141 write_directory_entry(lastEntry, dir_file_name);
1142 HeapFree(GetProcessHeap(), 0, dir_file_name);
1144 name[i] = '-';
1145 lastEntry = &name[i+1];
1146 ++count;
1149 name[i] = 0;
1151 fprintf(tempfile, " <Include>\n");
1152 fprintf(tempfile, " <Filename>");
1153 write_xml_text(tempfile, name);
1154 fprintf(tempfile, "</Filename>\n");
1155 fprintf(tempfile, " </Include>\n");
1156 for (i = 0; i < count; i++)
1157 fprintf(tempfile, " </Menu>\n");
1158 fprintf(tempfile, "</Menu>\n");
1160 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1161 if (menuPath == NULL) goto end;
1162 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1163 ret = TRUE;
1165 end:
1166 if (tempfile)
1167 fclose(tempfile);
1168 if (ret)
1169 ret = (rename(tempfilename, menuPath) == 0);
1170 if (!ret && tempfilename)
1171 remove(tempfilename);
1172 HeapFree(GetProcessHeap(), 0, tempfilename);
1173 if (ret)
1174 register_menus_entry(menuPath, unix_link);
1175 HeapFree(GetProcessHeap(), 0, name);
1176 HeapFree(GetProcessHeap(), 0, menuPath);
1177 return ret;
1180 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1181 const char *descr, const char *workdir, const char *icon)
1183 const char *linkname;
1184 char *desktopPath = NULL;
1185 char *desktopDir;
1186 char *filename = NULL;
1187 BOOL ret = TRUE;
1189 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1190 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1191 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1193 linkname = strrchr(link, '/');
1194 if (linkname == NULL)
1195 linkname = link;
1196 else
1197 ++linkname;
1199 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1200 if (!desktopPath)
1202 WINE_WARN("out of memory creating menu entry\n");
1203 ret = FALSE;
1204 goto end;
1206 desktopDir = strrchr(desktopPath, '/');
1207 *desktopDir = 0;
1208 if (!create_directories(desktopPath))
1210 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1211 ret = FALSE;
1212 goto end;
1214 *desktopDir = '/';
1215 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1217 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1218 ret = FALSE;
1219 goto end;
1222 filename = heap_printf("wine/%s.desktop", link);
1223 if (!filename || !write_menu_file(unix_link, filename))
1225 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1226 ret = FALSE;
1229 end:
1230 HeapFree(GetProcessHeap(), 0, desktopPath);
1231 HeapFree(GetProcessHeap(), 0, filename);
1232 return ret;
1235 /* This escapes reserved characters in .desktop files' Exec keys. */
1236 static LPSTR escape(LPCWSTR arg)
1238 int i, j;
1239 WCHAR *escaped_string;
1240 char *utf8_string;
1242 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1243 if (escaped_string == NULL) return NULL;
1244 for (i = j = 0; arg[i]; i++)
1246 switch (arg[i])
1248 case '\\':
1249 escaped_string[j++] = '\\';
1250 escaped_string[j++] = '\\';
1251 escaped_string[j++] = '\\';
1252 escaped_string[j++] = '\\';
1253 break;
1254 case ' ':
1255 case '\t':
1256 case '\n':
1257 case '"':
1258 case '\'':
1259 case '>':
1260 case '<':
1261 case '~':
1262 case '|':
1263 case '&':
1264 case ';':
1265 case '$':
1266 case '*':
1267 case '?':
1268 case '#':
1269 case '(':
1270 case ')':
1271 case '`':
1272 escaped_string[j++] = '\\';
1273 escaped_string[j++] = '\\';
1274 /* fall through */
1275 default:
1276 escaped_string[j++] = arg[i];
1277 break;
1280 escaped_string[j] = 0;
1282 utf8_string = wchars_to_utf8_chars(escaped_string);
1283 if (utf8_string == NULL)
1285 WINE_ERR("out of memory\n");
1286 goto end;
1289 end:
1290 HeapFree(GetProcessHeap(), 0, escaped_string);
1291 return utf8_string;
1294 /* Return a heap-allocated copy of the unix format difference between the two
1295 * Windows-format paths.
1296 * locn is the owning location
1297 * link is within locn
1299 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1301 char *unix_locn, *unix_link;
1302 char *relative = NULL;
1304 unix_locn = wine_get_unix_file_name(locn);
1305 unix_link = wine_get_unix_file_name(link);
1306 if (unix_locn && unix_link)
1308 size_t len_unix_locn, len_unix_link;
1309 len_unix_locn = strlen (unix_locn);
1310 len_unix_link = strlen (unix_link);
1311 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1313 size_t len_rel;
1314 char *p = strrchr (unix_link + len_unix_locn, '/');
1315 p = strrchr (p, '.');
1316 if (p)
1318 *p = '\0';
1319 len_unix_link = p - unix_link;
1321 len_rel = len_unix_link - len_unix_locn;
1322 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1323 if (relative)
1325 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1329 if (!relative)
1330 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1331 HeapFree(GetProcessHeap(), 0, unix_locn);
1332 HeapFree(GetProcessHeap(), 0, unix_link);
1333 return relative;
1336 /***********************************************************************
1338 * GetLinkLocation
1340 * returns TRUE if successful
1341 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1342 * *relative will contain the address of a heap-allocated copy of the portion
1343 * of the filename that is within the specified location, in unix form
1345 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1347 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1348 DWORD len, i, r, filelen;
1349 const DWORD locations[] = {
1350 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1351 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1352 CSIDL_COMMON_STARTMENU };
1354 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1355 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1356 if (filelen==0 || filelen>MAX_PATH)
1357 return FALSE;
1359 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1361 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1362 * expand or our hardcoded list won't match.
1364 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1365 if (filelen==0 || filelen>MAX_PATH)
1366 return FALSE;
1368 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1370 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1372 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1373 continue;
1375 len = lstrlenW(buffer);
1376 if (len >= MAX_PATH)
1377 continue; /* We've just trashed memory! Hopefully we are OK */
1379 if (len > filelen || filename[len]!='\\')
1380 continue;
1381 /* do a lstrcmpinW */
1382 filename[len] = 0;
1383 r = lstrcmpiW( filename, buffer );
1384 filename[len] = '\\';
1385 if ( r )
1386 continue;
1388 /* return the remainder of the string and link type */
1389 *loc = locations[i];
1390 *relative = relative_path (filename, buffer);
1391 return (*relative != NULL);
1394 return FALSE;
1397 /* gets the target path directly or through MSI */
1398 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1399 LPWSTR szArgs, DWORD argsSize)
1401 IShellLinkDataList *dl = NULL;
1402 EXP_DARWIN_LINK *dar = NULL;
1403 HRESULT hr;
1405 szPath[0] = 0;
1406 szArgs[0] = 0;
1408 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1409 if (hr == S_OK && szPath[0])
1411 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1412 return hr;
1415 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1416 if (FAILED(hr))
1417 return hr;
1419 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1420 if (SUCCEEDED(hr))
1422 WCHAR* szCmdline;
1423 DWORD cmdSize;
1425 cmdSize=0;
1426 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1427 if (hr == ERROR_SUCCESS)
1429 cmdSize++;
1430 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1431 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1432 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1433 if (hr == ERROR_SUCCESS)
1435 WCHAR *s, *d;
1436 int bcount, in_quotes;
1438 /* Extract the application path */
1439 bcount=0;
1440 in_quotes=0;
1441 s=szCmdline;
1442 d=szPath;
1443 while (*s)
1445 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1447 /* skip the remaining spaces */
1448 do {
1449 s++;
1450 } while (*s==0x0009 || *s==0x0020);
1451 break;
1453 else if (*s==0x005c)
1455 /* '\\' */
1456 *d++=*s++;
1457 bcount++;
1459 else if (*s==0x0022)
1461 /* '"' */
1462 if ((bcount & 1)==0)
1464 /* Preceded by an even number of '\', this is
1465 * half that number of '\', plus a quote which
1466 * we erase.
1468 d-=bcount/2;
1469 in_quotes=!in_quotes;
1470 s++;
1472 else
1474 /* Preceded by an odd number of '\', this is
1475 * half that number of '\' followed by a '"'
1477 d=d-bcount/2-1;
1478 *d++='"';
1479 s++;
1481 bcount=0;
1483 else
1485 /* a regular character */
1486 *d++=*s++;
1487 bcount=0;
1489 if ((d-szPath) == pathSize)
1491 /* Keep processing the path till we get to the
1492 * arguments, but 'stand still'
1494 d--;
1497 /* Close the application path */
1498 *d=0;
1500 lstrcpynW(szArgs, s, argsSize);
1502 HeapFree( GetProcessHeap(), 0, szCmdline );
1504 LocalFree( dar );
1507 IShellLinkDataList_Release( dl );
1508 return hr;
1511 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1513 HRESULT hr;
1514 WCHAR *value = NULL;
1515 DWORD size = 0;
1516 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1517 if (SUCCEEDED(hr))
1519 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1520 if (value)
1522 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1523 if (FAILED(hr))
1525 HeapFree(GetProcessHeap(), 0, value);
1526 value = NULL;
1530 return value;
1533 static char *slashes_to_minuses(const char *string)
1535 int i;
1536 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1537 if (ret)
1539 for (i = 0; string[i]; i++)
1541 if (string[i] == '/')
1542 ret[i] = '-';
1543 else
1544 ret[i] = string[i];
1546 ret[i] = 0;
1547 return ret;
1549 return NULL;
1552 static BOOL next_line(FILE *file, char **line, int *size)
1554 int pos = 0;
1555 char *cr;
1556 if (*line == NULL)
1558 *size = 4096;
1559 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1561 while (*line != NULL)
1563 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1565 HeapFree(GetProcessHeap(), 0, *line);
1566 *line = NULL;
1567 if (feof(file))
1568 return TRUE;
1569 return FALSE;
1571 pos = strlen(*line);
1572 cr = strchr(*line, '\n');
1573 if (cr == NULL)
1575 char *line2;
1576 (*size) *= 2;
1577 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1578 if (line2)
1579 *line = line2;
1580 else
1582 HeapFree(GetProcessHeap(), 0, *line);
1583 *line = NULL;
1586 else
1588 *cr = 0;
1589 return TRUE;
1592 return FALSE;
1595 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1597 char *globs_filename = NULL;
1598 BOOL ret = TRUE;
1599 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1600 if (globs_filename)
1602 FILE *globs_file = fopen(globs_filename, "r");
1603 if (globs_file) /* doesn't have to exist */
1605 char *line = NULL;
1606 int size = 0;
1607 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1609 char *pos;
1610 struct xdg_mime_type *mime_type_entry = NULL;
1611 if (line[0] != '#' && (pos = strchr(line, ':')))
1613 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1614 if (mime_type_entry)
1616 *pos = 0;
1617 mime_type_entry->mimeType = strdupA(line);
1618 mime_type_entry->glob = strdupA(pos + 1);
1619 if (mime_type_entry->mimeType && mime_type_entry->glob)
1620 list_add_tail(mime_types, &mime_type_entry->entry);
1621 else
1623 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1624 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1625 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1626 ret = FALSE;
1629 else
1630 ret = FALSE;
1633 HeapFree(GetProcessHeap(), 0, line);
1634 fclose(globs_file);
1636 HeapFree(GetProcessHeap(), 0, globs_filename);
1638 else
1639 ret = FALSE;
1640 return ret;
1643 static void free_native_mime_types(struct list *native_mime_types)
1645 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1647 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1649 list_remove(&mime_type_entry->entry);
1650 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1651 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1652 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1654 HeapFree(GetProcessHeap(), 0, native_mime_types);
1657 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1659 char *xdg_data_dirs;
1660 BOOL ret;
1662 *mime_types = NULL;
1664 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1665 if (xdg_data_dirs == NULL)
1666 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1667 else
1668 xdg_data_dirs = strdupA(xdg_data_dirs);
1670 if (xdg_data_dirs)
1672 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1673 if (*mime_types)
1675 const char *begin;
1676 char *end;
1678 list_init(*mime_types);
1679 ret = add_mimes(xdg_data_home, *mime_types);
1680 if (ret)
1682 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1684 *end = '\0';
1685 ret = add_mimes(begin, *mime_types);
1686 *end = ':';
1687 if (!ret)
1688 break;
1690 if (ret)
1691 ret = add_mimes(begin, *mime_types);
1694 else
1695 ret = FALSE;
1696 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1698 else
1699 ret = FALSE;
1700 if (!ret && *mime_types)
1702 free_native_mime_types(*mime_types);
1703 *mime_types = NULL;
1705 return ret;
1708 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1709 char **match)
1711 #ifdef HAVE_FNMATCH
1712 struct xdg_mime_type *mime_type_entry;
1713 int matchLength = 0;
1715 *match = NULL;
1717 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1719 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1721 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1723 *match = mime_type_entry->mimeType;
1724 matchLength = strlen(mime_type_entry->glob);
1729 if (*match != NULL)
1731 *match = strdupA(*match);
1732 if (*match == NULL)
1733 return FALSE;
1735 #else
1736 *match = NULL;
1737 #endif
1738 return TRUE;
1741 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1742 const char *extensionA,
1743 LPCWSTR extensionW,
1744 char **mime_type)
1746 WCHAR *lower_extensionW;
1747 INT len;
1748 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1749 if (ret == FALSE || *mime_type != NULL)
1750 return ret;
1751 len = strlenW(extensionW);
1752 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1753 if (lower_extensionW)
1755 char *lower_extensionA;
1756 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1757 strlwrW(lower_extensionW);
1758 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1759 if (lower_extensionA)
1761 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1762 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1764 else
1766 ret = FALSE;
1767 WINE_FIXME("out of memory\n");
1769 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1771 else
1773 ret = FALSE;
1774 WINE_FIXME("out of memory\n");
1776 return ret;
1779 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1781 DWORD size;
1782 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1784 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1785 if (ret)
1787 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1788 return ret;
1790 HeapFree(GetProcessHeap(), 0, ret);
1792 return NULL;
1795 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
1797 WCHAR *valW = reg_get_valW(key, subkey, name);
1798 if (valW)
1800 char *val = wchars_to_utf8_chars(valW);
1801 HeapFree(GetProcessHeap(), 0, valW);
1802 return val;
1804 return NULL;
1807 static HKEY open_associations_reg_key(void)
1809 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1810 '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};
1811 HKEY assocKey;
1812 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1813 return assocKey;
1814 return NULL;
1817 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1819 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1820 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1821 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1822 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1823 HKEY assocKey;
1824 BOOL ret;
1826 if ((assocKey = open_associations_reg_key()))
1828 CHAR *valueA;
1829 WCHAR *value;
1831 ret = FALSE;
1833 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
1834 if (!valueA || lstrcmpA(valueA, mimeType))
1835 ret = TRUE;
1836 HeapFree(GetProcessHeap(), 0, valueA);
1838 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1839 if (!value || strcmpW(value, progId))
1840 ret = TRUE;
1841 HeapFree(GetProcessHeap(), 0, value);
1843 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
1844 if (!valueA || lstrcmpA(valueA, appName))
1845 ret = TRUE;
1846 HeapFree(GetProcessHeap(), 0, valueA);
1848 value = reg_get_valW(assocKey, extensionW, DocNameW);
1849 if (docName && (!value || strcmpW(value, docName)))
1850 ret = TRUE;
1851 HeapFree(GetProcessHeap(), 0, value);
1853 RegCloseKey(assocKey);
1855 else
1857 WINE_ERR("error opening associations registry key\n");
1858 ret = FALSE;
1860 return ret;
1863 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1865 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1866 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1867 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1868 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1869 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
1870 HKEY assocKey = NULL;
1871 HKEY subkey = NULL;
1872 WCHAR *mimeTypeW = NULL;
1873 WCHAR *appNameW = NULL;
1874 WCHAR *desktopFileW = NULL;
1876 assocKey = open_associations_reg_key();
1877 if (assocKey == NULL)
1879 WINE_ERR("could not open file associations key\n");
1880 goto done;
1883 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
1885 WINE_ERR("could not create extension subkey\n");
1886 goto done;
1889 mimeTypeW = utf8_chars_to_wchars(mimeType);
1890 if (mimeTypeW == NULL)
1892 WINE_ERR("out of memory\n");
1893 goto done;
1896 appNameW = utf8_chars_to_wchars(appName);
1897 if (appNameW == NULL)
1899 WINE_ERR("out of memory\n");
1900 goto done;
1903 desktopFileW = utf8_chars_to_wchars(desktopFile);
1904 if (desktopFileW == NULL)
1906 WINE_ERR("out of memory\n");
1907 goto done;
1910 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
1911 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1912 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
1913 if (docName)
1914 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1915 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
1917 done:
1918 RegCloseKey(assocKey);
1919 RegCloseKey(subkey);
1920 HeapFree(GetProcessHeap(), 0, mimeTypeW);
1921 HeapFree(GetProcessHeap(), 0, appNameW);
1922 HeapFree(GetProcessHeap(), 0, desktopFileW);
1925 static BOOL cleanup_associations(void)
1927 static const WCHAR openW[] = {'o','p','e','n',0};
1928 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
1929 HKEY assocKey;
1930 BOOL hasChanged = FALSE;
1931 if ((assocKey = open_associations_reg_key()))
1933 int i;
1934 BOOL done = FALSE;
1935 for (i = 0; !done; i++)
1937 WCHAR *extensionW = NULL;
1938 DWORD size = 1024;
1939 LSTATUS ret;
1943 HeapFree(GetProcessHeap(), 0, extensionW);
1944 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1945 if (extensionW == NULL)
1947 WINE_ERR("out of memory\n");
1948 ret = ERROR_OUTOFMEMORY;
1949 break;
1951 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1952 size *= 2;
1953 } while (ret == ERROR_MORE_DATA);
1955 if (ret == ERROR_SUCCESS)
1957 WCHAR *command;
1958 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1959 if (command == NULL)
1961 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
1962 if (desktopFile)
1964 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
1965 remove(desktopFile);
1967 RegDeleteKeyW(assocKey, extensionW);
1968 hasChanged = TRUE;
1969 HeapFree(GetProcessHeap(), 0, desktopFile);
1971 HeapFree(GetProcessHeap(), 0, command);
1973 else
1975 if (ret != ERROR_NO_MORE_ITEMS)
1976 WINE_ERR("error %d while reading registry\n", ret);
1977 done = TRUE;
1979 HeapFree(GetProcessHeap(), 0, extensionW);
1981 RegCloseKey(assocKey);
1983 else
1984 WINE_ERR("could not open file associations key\n");
1985 return hasChanged;
1988 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1989 const char *mime_type, const char *comment)
1991 BOOL ret = FALSE;
1992 char *filename;
1994 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1995 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1997 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1998 if (filename)
2000 FILE *packageFile = fopen(filename, "w");
2001 if (packageFile)
2003 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2004 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2005 fprintf(packageFile, " <mime-type type=\"");
2006 write_xml_text(packageFile, mime_type);
2007 fprintf(packageFile, "\">\n");
2008 fprintf(packageFile, " <glob pattern=\"*");
2009 write_xml_text(packageFile, dot_extension);
2010 fprintf(packageFile, "\"/>\n");
2011 if (comment)
2013 fprintf(packageFile, " <comment>");
2014 write_xml_text(packageFile, comment);
2015 fprintf(packageFile, "</comment>\n");
2017 fprintf(packageFile, " </mime-type>\n");
2018 fprintf(packageFile, "</mime-info>\n");
2019 ret = TRUE;
2020 fclose(packageFile);
2022 else
2023 WINE_ERR("error writing file %s\n", filename);
2024 HeapFree(GetProcessHeap(), 0, filename);
2026 else
2027 WINE_ERR("out of memory\n");
2028 return ret;
2031 static BOOL is_extension_blacklisted(LPCWSTR extension)
2033 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2034 static const WCHAR comW[] = {'.','c','o','m',0};
2035 static const WCHAR exeW[] = {'.','e','x','e',0};
2036 static const WCHAR msiW[] = {'.','m','s','i',0};
2038 if (!strcmpiW(extension, comW) ||
2039 !strcmpiW(extension, exeW) ||
2040 !strcmpiW(extension, msiW))
2041 return TRUE;
2042 return FALSE;
2045 static const char* get_special_mime_type(LPCWSTR extension)
2047 static const WCHAR lnkW[] = {'.','l','n','k',0};
2048 if (!strcmpiW(extension, lnkW))
2049 return "application/x-ms-shortcut";
2050 return NULL;
2053 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2054 const char *friendlyAppName, const char *mimeType,
2055 const char *progId)
2057 BOOL ret = FALSE;
2058 FILE *desktop;
2060 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
2061 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2062 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
2064 desktop = fopen(desktopPath, "w");
2065 if (desktop)
2067 fprintf(desktop, "[Desktop Entry]\n");
2068 fprintf(desktop, "Type=Application\n");
2069 fprintf(desktop, "Name=%s\n", friendlyAppName);
2070 fprintf(desktop, "MimeType=%s\n", mimeType);
2071 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
2072 fprintf(desktop, "NoDisplay=true\n");
2073 fprintf(desktop, "StartupNotify=true\n");
2074 ret = TRUE;
2075 fclose(desktop);
2077 else
2078 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2079 return ret;
2082 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2084 static const WCHAR openW[] = {'o','p','e','n',0};
2085 struct list *nativeMimeTypes = NULL;
2086 LSTATUS ret = 0;
2087 int i;
2088 BOOL hasChanged = FALSE;
2090 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2092 WINE_ERR("could not build native MIME types\n");
2093 return FALSE;
2096 for (i = 0; ; i++)
2098 WCHAR *extensionW = NULL;
2099 DWORD size = 1024;
2103 HeapFree(GetProcessHeap(), 0, extensionW);
2104 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2105 if (extensionW == NULL)
2107 WINE_ERR("out of memory\n");
2108 ret = ERROR_OUTOFMEMORY;
2109 break;
2111 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2112 size *= 2;
2113 } while (ret == ERROR_MORE_DATA);
2115 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2117 char *extensionA = NULL;
2118 WCHAR *commandW = NULL;
2119 WCHAR *friendlyDocNameW = NULL;
2120 char *friendlyDocNameA = NULL;
2121 WCHAR *iconW = NULL;
2122 char *iconA = NULL;
2123 WCHAR *contentTypeW = NULL;
2124 char *mimeTypeA = NULL;
2125 WCHAR *friendlyAppNameW = NULL;
2126 char *friendlyAppNameA = NULL;
2127 WCHAR *progIdW = NULL;
2128 char *progIdA = NULL;
2130 extensionA = wchars_to_utf8_chars(extensionW);
2131 if (extensionA == NULL)
2133 WINE_ERR("out of memory\n");
2134 goto end;
2137 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2138 if (friendlyDocNameW)
2140 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2141 if (friendlyDocNameA == NULL)
2143 WINE_ERR("out of memory\n");
2144 goto end;
2148 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2150 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2151 if (contentTypeW)
2152 strlwrW(contentTypeW);
2154 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2155 goto end;
2157 if (mimeTypeA == NULL)
2159 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2160 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2161 else if ((get_special_mime_type(extensionW)))
2162 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2163 else
2164 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2166 if (mimeTypeA != NULL)
2168 /* Gnome seems to ignore the <icon> tag in MIME packages,
2169 * and the default name is more intuitive anyway.
2171 if (iconW)
2173 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2174 if (flattened_mime)
2176 int index = 0;
2177 WCHAR *comma = strrchrW(iconW, ',');
2178 if (comma)
2180 *comma = 0;
2181 index = atoiW(comma + 1);
2183 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2184 HeapFree(GetProcessHeap(), 0, flattened_mime);
2188 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2189 hasChanged = TRUE;
2191 else
2193 WINE_FIXME("out of memory\n");
2194 goto end;
2198 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2199 if (commandW == NULL)
2200 /* no command => no application is associated */
2201 goto end;
2203 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2204 if (friendlyAppNameW)
2206 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2207 if (friendlyAppNameA == NULL)
2209 WINE_ERR("out of memory\n");
2210 goto end;
2213 else
2215 friendlyAppNameA = heap_printf("A Wine application");
2216 if (friendlyAppNameA == NULL)
2218 WINE_ERR("out of memory\n");
2219 goto end;
2223 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2224 if (progIdW)
2226 progIdA = escape(progIdW);
2227 if (progIdA == NULL)
2229 WINE_ERR("out of memory\n");
2230 goto end;
2233 else
2234 goto end; /* no progID => not a file type association */
2236 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2238 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2239 if (desktopPath)
2241 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2243 hasChanged = TRUE;
2244 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2246 HeapFree(GetProcessHeap(), 0, desktopPath);
2250 end:
2251 HeapFree(GetProcessHeap(), 0, extensionA);
2252 HeapFree(GetProcessHeap(), 0, commandW);
2253 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2254 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2255 HeapFree(GetProcessHeap(), 0, iconW);
2256 HeapFree(GetProcessHeap(), 0, iconA);
2257 HeapFree(GetProcessHeap(), 0, contentTypeW);
2258 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2259 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2260 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2261 HeapFree(GetProcessHeap(), 0, progIdW);
2262 HeapFree(GetProcessHeap(), 0, progIdA);
2264 HeapFree(GetProcessHeap(), 0, extensionW);
2265 if (ret != ERROR_SUCCESS)
2266 break;
2269 free_native_mime_types(nativeMimeTypes);
2270 return hasChanged;
2273 static char *get_start_exe_path(void)
2275 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2276 '\\','s','t','a','r','t','.','e','x','e',0};
2277 WCHAR start_path[MAX_PATH];
2278 GetWindowsDirectoryW(start_path, MAX_PATH);
2279 lstrcatW(start_path, startW);
2280 return escape(start_path);
2283 static char* escape_unix_link_arg(LPCSTR unix_link)
2285 char *ret = NULL;
2286 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2287 if (unix_linkW)
2289 char *escaped_lnk = escape(unix_linkW);
2290 if (escaped_lnk)
2292 ret = heap_printf("/Unix %s", escaped_lnk);
2293 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2295 HeapFree(GetProcessHeap(), 0, unix_linkW);
2297 return ret;
2300 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2302 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2303 '\\','s','t','a','r','t','.','e','x','e',0};
2304 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2305 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2306 WCHAR szTmp[INFOTIPSIZE];
2307 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2308 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2309 int iIconId = 0, r = -1;
2310 DWORD csidl = -1;
2311 HANDLE hsem = NULL;
2312 char *unix_link = NULL;
2313 char *start_path = NULL;
2315 if ( !link )
2317 WINE_ERR("Link name is null\n");
2318 return FALSE;
2321 if( !GetLinkLocation( link, &csidl, &link_name ) )
2323 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2324 return TRUE;
2326 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2328 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2329 return TRUE;
2331 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2333 szTmp[0] = 0;
2334 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2335 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2336 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2338 szTmp[0] = 0;
2339 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2340 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2341 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2343 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2344 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2345 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2346 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2348 szTmp[0] = 0;
2349 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2350 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2351 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2353 if( !szPath[0] )
2355 LPITEMIDLIST pidl = NULL;
2356 IShellLinkW_GetIDList( sl, &pidl );
2357 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2358 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2361 /* extract the icon */
2362 if( szIconPath[0] )
2363 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2364 else
2365 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2367 /* fail - try once again after parent process exit */
2368 if( !icon_name )
2370 if (bWait)
2372 WINE_WARN("Unable to extract icon, deferring.\n");
2373 goto cleanup;
2375 WINE_ERR("failed to extract icon from %s\n",
2376 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2379 unix_link = wine_get_unix_file_name(link);
2380 if (unix_link == NULL)
2382 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2383 goto cleanup;
2386 /* check the path */
2387 if( szPath[0] )
2389 static const WCHAR exeW[] = {'.','e','x','e',0};
2390 WCHAR *p;
2392 /* check for .exe extension */
2393 if (!(p = strrchrW( szPath, '.' )) ||
2394 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2395 lstrcmpiW( p, exeW ))
2397 /* Not .exe - use 'start.exe' to launch this file */
2398 p = szArgs + lstrlenW(szPath) + 2;
2399 if (szArgs[0])
2401 p[0] = ' ';
2402 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2403 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2405 else
2406 p[0] = 0;
2408 szArgs[0] = '"';
2409 lstrcpyW(szArgs + 1, szPath);
2410 p[-1] = '"';
2412 GetWindowsDirectoryW(szPath, MAX_PATH);
2413 lstrcatW(szPath, startW);
2416 /* convert app working dir */
2417 if (szWorkDir[0])
2418 work_dir = wine_get_unix_file_name( szWorkDir );
2420 else
2422 /* if there's no path... try run the link itself */
2423 lstrcpynW(szArgs, link, MAX_PATH);
2424 GetWindowsDirectoryW(szPath, MAX_PATH);
2425 lstrcatW(szPath, startW);
2428 /* escape the path and parameters */
2429 escaped_path = escape(szPath);
2430 escaped_args = escape(szArgs);
2431 description = wchars_to_utf8_chars(szDescription);
2432 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2434 WINE_ERR("out of memory allocating/escaping parameters\n");
2435 goto cleanup;
2438 start_path = get_start_exe_path();
2439 if (start_path == NULL)
2441 WINE_ERR("out of memory\n");
2442 goto cleanup;
2445 /* building multiple menus concurrently has race conditions */
2446 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2447 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2449 WINE_ERR("failed wait for semaphore\n");
2450 goto cleanup;
2453 if (in_desktop_dir(csidl))
2455 char *location;
2456 const char *lastEntry;
2457 lastEntry = strrchr(link_name, '/');
2458 if (lastEntry == NULL)
2459 lastEntry = link_name;
2460 else
2461 ++lastEntry;
2462 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2463 if (location)
2465 if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
2467 char *link_arg = escape_unix_link_arg(unix_link);
2468 if (link_arg)
2470 r = !write_desktop_entry(unix_link, location, lastEntry,
2471 start_path, link_arg, description, work_dir, icon_name);
2472 HeapFree(GetProcessHeap(), 0, link_arg);
2475 else
2476 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2477 if (r == 0)
2478 chmod(location, 0755);
2479 HeapFree(GetProcessHeap(), 0, location);
2482 else
2484 char *link_arg = escape_unix_link_arg(unix_link);
2485 if (link_arg)
2487 r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name);
2488 HeapFree(GetProcessHeap(), 0, link_arg);
2492 ReleaseSemaphore( hsem, 1, NULL );
2494 cleanup:
2495 if (hsem) CloseHandle( hsem );
2496 HeapFree( GetProcessHeap(), 0, icon_name );
2497 HeapFree( GetProcessHeap(), 0, work_dir );
2498 HeapFree( GetProcessHeap(), 0, link_name );
2499 HeapFree( GetProcessHeap(), 0, escaped_args );
2500 HeapFree( GetProcessHeap(), 0, escaped_path );
2501 HeapFree( GetProcessHeap(), 0, description );
2502 HeapFree( GetProcessHeap(), 0, unix_link );
2503 HeapFree( GetProcessHeap(), 0, start_path );
2505 if (r && !bWait)
2506 WINE_ERR("failed to build the menu\n" );
2508 return ( r == 0 );
2511 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2513 char *link_name = NULL;
2514 DWORD csidl = -1;
2515 LPWSTR urlPath;
2516 char *escaped_urlPath = NULL;
2517 HRESULT hr;
2518 HANDLE hSem = NULL;
2519 BOOL ret = TRUE;
2520 int r = -1;
2521 char *unix_link = NULL;
2523 if ( !link )
2525 WINE_ERR("Link name is null\n");
2526 return TRUE;
2529 if( !GetLinkLocation( link, &csidl, &link_name ) )
2531 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2532 return TRUE;
2534 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2536 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2537 ret = TRUE;
2538 goto cleanup;
2540 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2542 hr = url->lpVtbl->GetURL(url, &urlPath);
2543 if (FAILED(hr))
2545 ret = TRUE;
2546 goto cleanup;
2548 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2550 unix_link = wine_get_unix_file_name(link);
2551 if (unix_link == NULL)
2553 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2554 goto cleanup;
2557 escaped_urlPath = escape(urlPath);
2558 if (escaped_urlPath == NULL)
2560 WINE_ERR("couldn't escape url, out of memory\n");
2561 goto cleanup;
2564 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2565 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2567 WINE_ERR("failed wait for semaphore\n");
2568 goto cleanup;
2570 if (in_desktop_dir(csidl))
2572 char *location;
2573 const char *lastEntry;
2574 lastEntry = strrchr(link_name, '/');
2575 if (lastEntry == NULL)
2576 lastEntry = link_name;
2577 else
2578 ++lastEntry;
2579 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2580 if (location)
2582 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2583 if (r == 0)
2584 chmod(location, 0755);
2585 HeapFree(GetProcessHeap(), 0, location);
2588 else
2589 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2590 ret = (r != 0);
2591 ReleaseSemaphore(hSem, 1, NULL);
2593 cleanup:
2594 if (hSem)
2595 CloseHandle(hSem);
2596 HeapFree(GetProcessHeap(), 0, link_name);
2597 CoTaskMemFree( urlPath );
2598 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2599 HeapFree(GetProcessHeap(), 0, unix_link);
2600 return ret;
2603 static BOOL WaitForParentProcess( void )
2605 PROCESSENTRY32 procentry;
2606 HANDLE hsnapshot = NULL, hprocess = NULL;
2607 DWORD ourpid = GetCurrentProcessId();
2608 BOOL ret = FALSE, rc;
2610 WINE_TRACE("Waiting for parent process\n");
2611 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2612 INVALID_HANDLE_VALUE)
2614 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2615 goto done;
2618 procentry.dwSize = sizeof(PROCESSENTRY32);
2619 rc = Process32First( hsnapshot, &procentry );
2620 while (rc)
2622 if (procentry.th32ProcessID == ourpid) break;
2623 rc = Process32Next( hsnapshot, &procentry );
2625 if (!rc)
2627 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2628 goto done;
2631 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2632 NULL)
2634 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2635 GetLastError());
2636 goto done;
2639 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2640 ret = TRUE;
2641 else
2642 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2644 done:
2645 if (hprocess) CloseHandle( hprocess );
2646 if (hsnapshot) CloseHandle( hsnapshot );
2647 return ret;
2650 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2652 IShellLinkW *sl;
2653 IPersistFile *pf;
2654 HRESULT r;
2655 WCHAR fullname[MAX_PATH];
2656 DWORD len;
2658 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2660 if( !linkname[0] )
2662 WINE_ERR("link name missing\n");
2663 return 1;
2666 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2667 if (len==0 || len>MAX_PATH)
2669 WINE_ERR("couldn't get full path of link file\n");
2670 return 1;
2673 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2674 &IID_IShellLinkW, (LPVOID *) &sl );
2675 if( FAILED( r ) )
2677 WINE_ERR("No IID_IShellLink\n");
2678 return 1;
2681 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2682 if( FAILED( r ) )
2684 WINE_ERR("No IID_IPersistFile\n");
2685 return 1;
2688 r = IPersistFile_Load( pf, fullname, STGM_READ );
2689 if( SUCCEEDED( r ) )
2691 /* If something fails (eg. Couldn't extract icon)
2692 * wait for parent process and try again
2694 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2696 WaitForParentProcess();
2697 InvokeShellLinker( sl, fullname, FALSE );
2700 else
2702 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2705 IPersistFile_Release( pf );
2706 IShellLinkW_Release( sl );
2708 return !r;
2711 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2713 IUniformResourceLocatorW *url;
2714 IPersistFile *pf;
2715 HRESULT r;
2716 WCHAR fullname[MAX_PATH];
2717 DWORD len;
2719 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2721 if( !urlname[0] )
2723 WINE_ERR("URL name missing\n");
2724 return 1;
2727 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2728 if (len==0 || len>MAX_PATH)
2730 WINE_ERR("couldn't get full path of URL file\n");
2731 return 1;
2734 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2735 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2736 if( FAILED( r ) )
2738 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2739 return 1;
2742 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2743 if( FAILED( r ) )
2745 WINE_ERR("No IID_IPersistFile\n");
2746 return 1;
2748 r = IPersistFile_Load( pf, fullname, STGM_READ );
2749 if( SUCCEEDED( r ) )
2751 /* If something fails (eg. Couldn't extract icon)
2752 * wait for parent process and try again
2754 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2756 WaitForParentProcess();
2757 InvokeShellLinkerForURL( url, fullname, FALSE );
2761 IPersistFile_Release( pf );
2762 url->lpVtbl->Release( url );
2764 return !r;
2767 static void RefreshFileTypeAssociations(void)
2769 HANDLE hSem = NULL;
2770 char *mime_dir = NULL;
2771 char *packages_dir = NULL;
2772 char *applications_dir = NULL;
2773 BOOL hasChanged;
2775 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2776 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2778 WINE_ERR("failed wait for semaphore\n");
2779 CloseHandle(hSem);
2780 hSem = NULL;
2781 goto end;
2784 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2785 if (mime_dir == NULL)
2787 WINE_ERR("out of memory\n");
2788 goto end;
2790 create_directories(mime_dir);
2792 packages_dir = heap_printf("%s/packages", mime_dir);
2793 if (packages_dir == NULL)
2795 WINE_ERR("out of memory\n");
2796 goto end;
2798 create_directories(packages_dir);
2800 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2801 if (applications_dir == NULL)
2803 WINE_ERR("out of memory\n");
2804 goto end;
2806 create_directories(applications_dir);
2808 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2809 hasChanged |= cleanup_associations();
2810 if (hasChanged)
2812 const char *argv[3];
2814 argv[0] = "update-mime-database";
2815 argv[1] = mime_dir;
2816 argv[2] = NULL;
2817 spawnvp( _P_NOWAIT, argv[0], argv );
2819 argv[0] = "update-desktop-database";
2820 argv[1] = applications_dir;
2821 spawnvp( _P_NOWAIT, argv[0], argv );
2824 end:
2825 if (hSem)
2827 ReleaseSemaphore(hSem, 1, NULL);
2828 CloseHandle(hSem);
2830 HeapFree(GetProcessHeap(), 0, mime_dir);
2831 HeapFree(GetProcessHeap(), 0, packages_dir);
2832 HeapFree(GetProcessHeap(), 0, applications_dir);
2835 static void cleanup_menus(void)
2837 HKEY hkey;
2839 hkey = open_menus_reg_key();
2840 if (hkey)
2842 int i;
2843 LSTATUS lret = ERROR_SUCCESS;
2844 for (i = 0; lret == ERROR_SUCCESS; )
2846 WCHAR *value = NULL;
2847 WCHAR *data = NULL;
2848 DWORD valueSize = 4096;
2849 DWORD dataSize = 4096;
2850 while (1)
2852 lret = ERROR_OUTOFMEMORY;
2853 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
2854 if (value == NULL)
2855 break;
2856 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
2857 if (data == NULL)
2858 break;
2859 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2860 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2861 break;
2862 valueSize *= 2;
2863 dataSize *= 2;
2864 HeapFree(GetProcessHeap(), 0, value);
2865 HeapFree(GetProcessHeap(), 0, data);
2866 value = data = NULL;
2868 if (lret == ERROR_SUCCESS)
2870 char *unix_file;
2871 char *windows_file;
2872 unix_file = wchars_to_unix_chars(value);
2873 windows_file = wchars_to_unix_chars(data);
2874 if (unix_file != NULL && windows_file != NULL)
2876 struct stat filestats;
2877 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
2879 WINE_TRACE("removing menu related file %s\n", unix_file);
2880 remove(unix_file);
2881 RegDeleteValueW(hkey, value);
2883 else
2884 i++;
2886 else
2888 WINE_ERR("out of memory enumerating menus\n");
2889 lret = ERROR_OUTOFMEMORY;
2891 HeapFree(GetProcessHeap(), 0, unix_file);
2892 HeapFree(GetProcessHeap(), 0, windows_file);
2894 else if (lret != ERROR_NO_MORE_ITEMS)
2895 WINE_ERR("error %d reading registry\n", lret);
2896 HeapFree(GetProcessHeap(), 0, value);
2897 HeapFree(GetProcessHeap(), 0, data);
2899 RegCloseKey(hkey);
2901 else
2902 WINE_ERR("error opening registry key, menu cleanup failed\n");
2905 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
2907 char *utf8lnkPath = NULL;
2908 char *utf8OutputPath = NULL;
2909 WCHAR *winLnkPath = NULL;
2910 IShellLinkW *shellLink = NULL;
2911 IPersistFile *persistFile = NULL;
2912 WCHAR szTmp[MAX_PATH];
2913 WCHAR szPath[MAX_PATH];
2914 WCHAR szArgs[INFOTIPSIZE];
2915 WCHAR szIconPath[MAX_PATH];
2916 int iconId;
2917 IStream *stream = NULL;
2918 HRESULT hr;
2920 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
2921 if (utf8lnkPath == NULL)
2923 WINE_ERR("out of memory converting paths\n");
2924 goto end;
2927 utf8OutputPath = wchars_to_utf8_chars(outputPath);
2928 if (utf8OutputPath == NULL)
2930 WINE_ERR("out of memory converting paths\n");
2931 goto end;
2934 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
2935 if (winLnkPath == NULL)
2937 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
2938 goto end;
2941 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2942 &IID_IShellLinkW, (LPVOID*)&shellLink);
2943 if (FAILED(hr))
2945 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
2946 goto end;
2949 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
2950 if (FAILED(hr))
2952 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
2953 goto end;
2956 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
2957 if (FAILED(hr))
2959 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
2960 goto end;
2963 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2964 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2965 szTmp[0] = 0;
2966 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
2967 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2969 if(!szPath[0])
2971 LPITEMIDLIST pidl = NULL;
2972 IShellLinkW_GetIDList(shellLink, &pidl);
2973 if (pidl && SHGetPathFromIDListW(pidl, szPath))
2974 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2977 if (szIconPath[0])
2979 hr = open_icon(szIconPath, iconId, FALSE, &stream);
2980 if (SUCCEEDED(hr))
2981 hr = write_native_icon(stream, utf8OutputPath, NULL);
2983 else
2985 hr = open_icon(szPath, iconId, FALSE, &stream);
2986 if (SUCCEEDED(hr))
2987 hr = write_native_icon(stream, utf8OutputPath, NULL);
2990 end:
2991 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
2992 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
2993 HeapFree(GetProcessHeap(), 0, winLnkPath);
2994 if (shellLink != NULL)
2995 IShellLinkW_Release(shellLink);
2996 if (persistFile != NULL)
2997 IPersistFile_Release(persistFile);
2998 if (stream != NULL)
2999 IStream_Release(stream);
3002 static WCHAR *next_token( LPWSTR *p )
3004 LPWSTR token = NULL, t = *p;
3006 if( !t )
3007 return NULL;
3009 while( t && !token )
3011 switch( *t )
3013 case ' ':
3014 t++;
3015 continue;
3016 case '"':
3017 /* unquote the token */
3018 token = ++t;
3019 t = strchrW( token, '"' );
3020 if( t )
3021 *t++ = 0;
3022 break;
3023 case 0:
3024 t = NULL;
3025 break;
3026 default:
3027 token = t;
3028 t = strchrW( token, ' ' );
3029 if( t )
3030 *t++ = 0;
3031 break;
3034 *p = t;
3035 return token;
3038 static BOOL init_xdg(void)
3040 WCHAR shellDesktopPath[MAX_PATH];
3041 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3042 if (SUCCEEDED(hr))
3043 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3044 if (xdg_desktop_dir == NULL)
3046 WINE_ERR("error looking up the desktop directory\n");
3047 return FALSE;
3050 if (getenv("XDG_CONFIG_HOME"))
3051 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3052 else
3053 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3054 if (xdg_config_dir)
3056 create_directories(xdg_config_dir);
3057 if (getenv("XDG_DATA_HOME"))
3058 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3059 else
3060 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3061 if (xdg_data_dir)
3063 char *buffer;
3064 create_directories(xdg_data_dir);
3065 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3066 if (buffer)
3068 mkdir(buffer, 0777);
3069 HeapFree(GetProcessHeap(), 0, buffer);
3071 return TRUE;
3073 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3075 WINE_ERR("out of memory\n");
3076 return FALSE;
3079 /***********************************************************************
3081 * wWinMain
3083 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3085 static const WCHAR dash_aW[] = {'-','a',0};
3086 static const WCHAR dash_rW[] = {'-','r',0};
3087 static const WCHAR dash_tW[] = {'-','t',0};
3088 static const WCHAR dash_uW[] = {'-','u',0};
3089 static const WCHAR dash_wW[] = {'-','w',0};
3091 LPWSTR token = NULL, p;
3092 BOOL bWait = FALSE;
3093 BOOL bURL = FALSE;
3094 HRESULT hr;
3095 int ret = 0;
3097 if (!init_xdg())
3098 return 1;
3100 hr = CoInitialize(NULL);
3101 if (FAILED(hr))
3103 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
3104 return 1;
3107 for( p = cmdline; p && *p; )
3109 token = next_token( &p );
3110 if( !token )
3111 break;
3112 if( !strcmpW( token, dash_aW ) )
3114 RefreshFileTypeAssociations();
3115 continue;
3117 if( !strcmpW( token, dash_rW ) )
3119 cleanup_menus();
3120 continue;
3122 if( !strcmpW( token, dash_wW ) )
3123 bWait = TRUE;
3124 else if ( !strcmpW( token, dash_uW ) )
3125 bURL = TRUE;
3126 else if ( !strcmpW( token, dash_tW ) )
3128 WCHAR *lnkFile = next_token( &p );
3129 if (lnkFile)
3131 WCHAR *outputFile = next_token( &p );
3132 if (outputFile)
3133 thumbnail_lnk(lnkFile, outputFile);
3136 else if( token[0] == '-' )
3138 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3140 else
3142 BOOL bRet;
3144 if (bURL)
3145 bRet = Process_URL( token, bWait );
3146 else
3147 bRet = Process_Link( token, bWait );
3148 if (!bRet)
3150 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3151 ret = 1;
3156 CoUninitialize();
3157 return ret;