crypt32: Update Italian translation.
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blobdcf13ac127459d32ecce022bfeaca713bc9a99f3
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 static char *xdg_config_dir;
168 static char *xdg_data_dir;
169 static char *xdg_desktop_dir;
171 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra);
172 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream);
174 /* Utility routines */
175 static unsigned short crc16(const char* string)
177 unsigned short crc = 0;
178 int i, j, xor_poly;
180 for (i = 0; string[i] != 0; i++)
182 char c = string[i];
183 for (j = 0; j < 8; c >>= 1, j++)
185 xor_poly = (c ^ crc) & 1;
186 crc >>= 1;
187 if (xor_poly)
188 crc ^= 0xa001;
191 return crc;
194 static char *strdupA( const char *str )
196 char *ret;
198 if (!str) return NULL;
199 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
200 return ret;
203 static char* heap_printf(const char *format, ...)
205 va_list args;
206 int size = 4096;
207 char *buffer, *ret;
208 int n;
210 va_start(args, format);
211 while (1)
213 buffer = HeapAlloc(GetProcessHeap(), 0, size);
214 if (buffer == NULL)
215 break;
216 n = vsnprintf(buffer, size, format, args);
217 if (n == -1)
218 size *= 2;
219 else if (n >= size)
220 size = n + 1;
221 else
222 break;
223 HeapFree(GetProcessHeap(), 0, buffer);
225 va_end(args);
226 if (!buffer) return NULL;
227 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
228 if (!ret) ret = buffer;
229 return ret;
232 static void write_xml_text(FILE *file, const char *text)
234 int i;
235 for (i = 0; text[i]; i++)
237 if (text[i] == '&')
238 fputs("&amp;", file);
239 else if (text[i] == '<')
240 fputs("&lt;", file);
241 else if (text[i] == '>')
242 fputs("&gt;", file);
243 else if (text[i] == '\'')
244 fputs("&apos;", file);
245 else if (text[i] == '"')
246 fputs("&quot;", file);
247 else
248 fputc(text[i], file);
252 static BOOL create_directories(char *directory)
254 BOOL ret = TRUE;
255 int i;
257 for (i = 0; directory[i]; i++)
259 if (i > 0 && directory[i] == '/')
261 directory[i] = 0;
262 mkdir(directory, 0777);
263 directory[i] = '/';
266 if (mkdir(directory, 0777) && errno != EEXIST)
267 ret = FALSE;
269 return ret;
272 static char* wchars_to_utf8_chars(LPCWSTR string)
274 char *ret;
275 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
276 ret = HeapAlloc(GetProcessHeap(), 0, size);
277 if (ret)
278 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
279 return ret;
282 static char* wchars_to_unix_chars(LPCWSTR string)
284 char *ret;
285 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
286 ret = HeapAlloc(GetProcessHeap(), 0, size);
287 if (ret)
288 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
289 return ret;
292 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
294 WCHAR *ret;
295 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
296 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
297 if (ret)
298 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
299 return ret;
302 /* Icon extraction routines
304 * FIXME: should use PrivateExtractIcons and friends
305 * FIXME: should not use stdio
308 static HRESULT convert_to_native_icon(IStream *icoFile, int *indeces, int numIndeces,
309 const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
311 WCHAR *dosOutputFileName = NULL;
312 IWICImagingFactory *factory = NULL;
313 IWICBitmapDecoder *decoder = NULL;
314 IWICBitmapEncoder *encoder = NULL;
315 IStream *outputFile = NULL;
316 int i;
317 HRESULT hr = E_FAIL;
319 dosOutputFileName = wine_get_dos_file_name(outputFileName);
320 if (dosOutputFileName == NULL)
322 WINE_ERR("error converting %s to DOS file name\n", outputFileName);
323 goto end;
325 hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
326 &IID_IWICImagingFactory, (void**)&factory);
327 if (FAILED(hr))
329 WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
330 goto end;
332 hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
333 WICDecodeMetadataCacheOnDemand, &decoder);
334 if (FAILED(hr))
336 WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
337 goto end;
339 hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
340 &IID_IWICBitmapEncoder, (void**)&encoder);
341 if (FAILED(hr))
343 WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
344 goto end;
346 hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
347 if (FAILED(hr))
349 WINE_ERR("error 0x%08X creating output file\n", hr);
350 goto end;
352 hr = IWICBitmapEncoder_Initialize(encoder, outputFile, GENERIC_WRITE);
353 if (FAILED(hr))
355 WINE_ERR("error 0x%08X initializing encoder\n", hr);
356 goto end;
359 for (i = 0; i < numIndeces; i++)
361 IWICBitmapFrameDecode *sourceFrame = NULL;
362 IWICBitmapSource *sourceBitmap = NULL;
363 IWICBitmapFrameEncode *dstFrame = NULL;
364 IPropertyBag2 *options = NULL;
365 UINT width, height;
367 hr = IWICBitmapDecoder_GetFrame(decoder, indeces[i], &sourceFrame);
368 if (FAILED(hr))
370 WINE_ERR("error 0x%08X getting frame %d\n", hr, indeces[i]);
371 goto endloop;
373 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
374 if (FAILED(hr))
376 WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
377 goto endloop;
379 hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
380 if (FAILED(hr))
382 WINE_ERR("error 0x%08X creating encoder frame\n", hr);
383 goto endloop;
385 hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
386 if (FAILED(hr))
388 WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
389 goto endloop;
391 hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
392 if (FAILED(hr))
394 WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
395 goto endloop;
397 hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
398 if (FAILED(hr))
400 WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
401 goto endloop;
403 hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
404 if (FAILED(hr))
406 WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
407 goto endloop;
409 hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
410 if (FAILED(hr))
412 WINE_ERR("error 0x%08X copying bitmaps\n", hr);
413 goto endloop;
415 hr = IWICBitmapFrameEncode_Commit(dstFrame);
416 if (FAILED(hr))
418 WINE_ERR("error 0x%08X committing frame\n", hr);
419 goto endloop;
421 endloop:
422 if (sourceFrame)
423 IWICBitmapFrameDecode_Release(sourceFrame);
424 if (sourceBitmap)
425 IWICBitmapSource_Release(sourceBitmap);
426 if (dstFrame)
427 IWICBitmapFrameEncode_Release(dstFrame);
430 hr = IWICBitmapEncoder_Commit(encoder);
431 if (FAILED(hr))
433 WINE_ERR("error 0x%08X committing encoder\n", hr);
434 goto end;
437 end:
438 HeapFree(GetProcessHeap(), 0, dosOutputFileName);
439 if (factory)
440 IWICImagingFactory_Release(factory);
441 if (decoder)
442 IWICBitmapDecoder_Release(decoder);
443 if (encoder)
444 IWICBitmapEncoder_Release(encoder);
445 if (outputFile)
446 IStream_Release(outputFile);
447 return hr;
450 static IStream *add_module_icons_to_stream(HMODULE hModule, GRPICONDIR *grpIconDir)
452 int i;
453 SIZE_T iconsSize = 0;
454 BYTE *icons = NULL;
455 ICONDIRENTRY *iconDirEntries = NULL;
456 IStream *stream = NULL;
457 HRESULT hr = E_FAIL;
458 ULONG bytesWritten;
459 ICONDIR iconDir;
460 SIZE_T iconOffset;
461 int validEntries = 0;
462 LARGE_INTEGER zero;
464 for (i = 0; i < grpIconDir->idCount; i++)
465 iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
466 icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
467 if (icons == NULL)
469 WINE_ERR("out of memory allocating icon\n");
470 goto end;
473 iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
474 if (iconDirEntries == NULL)
476 WINE_ERR("out of memory allocating icon dir entries\n");
477 goto end;
480 hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
481 if (FAILED(hr))
483 WINE_ERR("error creating icon stream\n");
484 goto end;
487 iconOffset = 0;
488 for (i = 0; i < grpIconDir->idCount; i++)
490 HRSRC hResInfo;
491 LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
492 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
494 HGLOBAL hResData;
495 if ((hResData = LoadResource(hModule, hResInfo)))
497 BITMAPINFO *pIcon;
498 if ((pIcon = LockResource(hResData)))
500 iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
501 iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
502 iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
503 iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
504 iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
505 iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
506 iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
507 iconDirEntries[validEntries].dwImageOffset = iconOffset;
508 validEntries++;
509 memcpy(&icons[iconOffset], pIcon, grpIconDir->idEntries[i].dwBytesInRes);
510 iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
512 FreeResource(hResData);
517 if (validEntries == 0)
519 WINE_ERR("no valid icon entries\n");
520 goto end;
523 iconDir.idReserved = 0;
524 iconDir.idType = 1;
525 iconDir.idCount = validEntries;
526 hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
527 if (FAILED(hr) || bytesWritten != sizeof(iconDir))
529 WINE_ERR("error 0x%08X writing icon stream\n", hr);
530 goto end;
532 for (i = 0; i < validEntries; i++)
533 iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
534 hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
535 if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
537 WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
538 goto end;
540 hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
541 if (FAILED(hr) || bytesWritten != iconOffset)
543 WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
544 goto end;
546 zero.QuadPart = 0;
547 hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
549 end:
550 HeapFree(GetProcessHeap(), 0, icons);
551 HeapFree(GetProcessHeap(), 0, iconDirEntries);
552 if (FAILED(hr) && stream != NULL)
554 IStream_Release(stream);
555 stream = NULL;
557 return stream;
560 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
562 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
564 if (!sEnumRes->nIndex--)
566 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
567 return FALSE;
569 else
570 return TRUE;
573 static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
575 HMODULE hModule;
576 HRSRC hResInfo;
577 HGLOBAL hResData;
578 GRPICONDIR *pIconDir;
579 ENUMRESSTRUCT sEnumRes;
580 HRESULT hr = E_FAIL;
582 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
583 if (!hModule)
585 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
586 wine_dbgstr_w(szFileName), GetLastError());
587 return HRESULT_FROM_WIN32(GetLastError());
590 if (nIndex < 0)
592 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
593 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
594 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
596 else
598 hResInfo=NULL;
599 sEnumRes.pResInfo = &hResInfo;
600 sEnumRes.nIndex = nIndex;
601 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
602 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
603 sEnumRes.nIndex != -1)
605 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
609 if (hResInfo)
611 if ((hResData = LoadResource(hModule, hResInfo)))
613 if ((pIconDir = LockResource(hResData)))
615 *ppStream = add_module_icons_to_stream(hModule, pIconDir);
616 if (*ppStream)
617 hr = S_OK;
620 FreeResource(hResData);
623 else
625 WINE_WARN("found no icon\n");
626 FreeLibrary(hModule);
627 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
630 FreeLibrary(hModule);
631 return hr;
634 static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
636 ICONDIR iconDir;
637 ULONG bytesRead;
638 HRESULT hr;
640 *ppIconDirEntries = NULL;
642 hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
643 if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
644 (iconDir.idReserved != 0) || (iconDir.idType != 1))
646 WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
647 hr = E_FAIL;
648 goto end;
650 *numEntries = iconDir.idCount;
652 if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
654 hr = E_OUTOFMEMORY;
655 goto end;
657 hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
658 if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
660 if (SUCCEEDED(hr)) hr = E_FAIL;
661 goto end;
664 end:
665 if (FAILED(hr))
666 HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
667 return hr;
670 static HRESULT write_native_icon(IStream *iconStream, const char *icon_name, LPCWSTR szFileName)
672 ICONDIRENTRY *pIconDirEntry = NULL;
673 int numEntries;
674 int nMax = 0, nMaxBits = 0;
675 int nIndex = 0;
676 int i;
677 LARGE_INTEGER position;
678 HRESULT hr;
680 hr = read_ico_direntries(iconStream, &pIconDirEntry, &numEntries);
681 if (FAILED(hr))
682 goto end;
684 for (i = 0; i < numEntries; i++)
686 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
687 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
688 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
690 nIndex = i;
691 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
692 nMaxBits = pIconDirEntry[i].wBitCount;
695 WINE_TRACE("Selected: %d\n", nIndex);
697 position.QuadPart = 0;
698 hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
699 if (FAILED(hr))
700 goto end;
701 hr = convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
703 end:
704 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
705 return hr;
708 static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
710 WCHAR *extension;
711 WCHAR *icon = NULL;
712 WCHAR *comma;
713 WCHAR *executable = NULL;
714 int index = 0;
715 char *output_path = NULL;
716 HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
718 extension = strrchrW(szFileName, '.');
719 if (extension == NULL)
720 goto end;
722 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
723 if (icon)
725 comma = strrchrW(icon, ',');
726 if (comma)
728 *comma = 0;
729 index = atoiW(comma + 1);
731 hr = open_icon(icon, index, FALSE, ppStream);
733 else
735 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, NULL);
736 if (executable)
737 hr = open_icon(executable, 0, FALSE, ppStream);
740 end:
741 HeapFree(GetProcessHeap(), 0, icon);
742 HeapFree(GetProcessHeap(), 0, executable);
743 HeapFree(GetProcessHeap(), 0, output_path);
744 return hr;
747 static HRESULT open_default_icon(IStream **ppStream)
749 static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
751 return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
754 static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream)
756 HRESULT hr;
758 hr = open_module_icon(filename, index, ppStream);
759 if (FAILED(hr))
761 static const WCHAR dot_icoW[] = {'.','i','c','o',0};
762 int len = strlenW(filename);
763 if (len >= 4 && strcmpiW(&filename[len - 4], dot_icoW) == 0)
764 hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
766 if (FAILED(hr))
767 hr = open_file_type_icon(filename, ppStream);
768 if (FAILED(hr) && !bWait)
769 hr = open_default_icon(ppStream);
770 return hr;
773 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
774 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
776 unsigned short crc;
777 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *png_path = NULL;
778 char* s;
779 int n;
780 IStream *stream = NULL;
781 HRESULT hr;
783 /* Where should we save the icon? */
784 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
785 iconsdir = heap_printf("%s/icons", xdg_data_dir);
786 if (iconsdir)
788 if (mkdir(iconsdir, 0777) && errno != EEXIST)
790 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
791 goto end;
794 else
796 WINE_TRACE("no icon created\n");
797 return NULL;
800 /* Determine the icon base name */
801 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
802 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
803 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
804 s=ico_name=ico_path;
805 while (*s!='\0') {
806 if (*s=='/' || *s=='\\') {
807 *s='\\';
808 ico_name=s;
809 } else {
810 *s=tolower(*s);
812 s++;
814 if (*ico_name=='\\') *ico_name++='\0';
815 s=strrchr(ico_name,'.');
816 if (s) *s='\0';
818 /* Compute the source-path hash */
819 crc=crc16(ico_path);
821 if (destFilename)
822 png_path=heap_printf("%s/%s.png",iconsdir,destFilename);
823 else
824 png_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
825 if (png_path == NULL)
827 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
828 return NULL;
831 hr = open_icon( path, index, bWait, &stream );
832 if (SUCCEEDED(hr))
834 hr = write_native_icon( stream, png_path, path );
835 if (SUCCEEDED(hr))
836 goto end;
837 else
838 WINE_ERR("writing native icon for %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(path), index, hr);
840 else
841 WINE_WARN("extracting icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(path), index, hr);
843 HeapFree( GetProcessHeap(), 0, png_path );
844 png_path=NULL;
846 end:
847 HeapFree(GetProcessHeap(), 0, iconsdir);
848 HeapFree(GetProcessHeap(), 0, ico_path);
849 if (stream)
850 IStream_Release(stream);
851 return png_path;
854 static HKEY open_menus_reg_key(void)
856 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
857 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
858 HKEY assocKey;
859 DWORD ret;
860 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
861 if (ret == ERROR_SUCCESS)
862 return assocKey;
863 SetLastError(ret);
864 return NULL;
867 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
869 WCHAR *unix_fileW;
870 WCHAR *windows_fileW;
871 INT size;
872 DWORD ret;
874 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
875 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
876 if (unix_fileW)
878 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
879 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
880 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
881 if (windows_fileW)
883 HKEY hkey;
884 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
885 hkey = open_menus_reg_key();
886 if (hkey)
888 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
889 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
890 RegCloseKey(hkey);
892 else
893 ret = GetLastError();
894 HeapFree(GetProcessHeap(), 0, windows_fileW);
896 else
897 ret = ERROR_NOT_ENOUGH_MEMORY;
898 HeapFree(GetProcessHeap(), 0, unix_fileW);
900 else
901 ret = ERROR_NOT_ENOUGH_MEMORY;
902 return ret;
905 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
906 const char *path, const char *args, const char *descr,
907 const char *workdir, const char *icon)
909 FILE *file;
911 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
912 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
913 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
915 file = fopen(location, "w");
916 if (file == NULL)
917 return FALSE;
919 fprintf(file, "[Desktop Entry]\n");
920 fprintf(file, "Name=%s\n", linkname);
921 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
922 wine_get_config_dir(), path, args);
923 fprintf(file, "Type=Application\n");
924 fprintf(file, "StartupNotify=true\n");
925 if (descr && lstrlenA(descr))
926 fprintf(file, "Comment=%s\n", descr);
927 if (workdir && lstrlenA(workdir))
928 fprintf(file, "Path=%s\n", workdir);
929 if (icon && lstrlenA(icon))
930 fprintf(file, "Icon=%s\n", icon);
932 fclose(file);
934 if (unix_link)
936 DWORD ret = register_menus_entry(location, unix_link);
937 if (ret != ERROR_SUCCESS)
938 return FALSE;
941 return TRUE;
944 static BOOL write_directory_entry(const char *directory, const char *location)
946 FILE *file;
948 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
950 file = fopen(location, "w");
951 if (file == NULL)
952 return FALSE;
954 fprintf(file, "[Desktop Entry]\n");
955 fprintf(file, "Type=Directory\n");
956 if (strcmp(directory, "wine") == 0)
958 fprintf(file, "Name=Wine\n");
959 fprintf(file, "Icon=wine\n");
961 else
963 fprintf(file, "Name=%s\n", directory);
964 fprintf(file, "Icon=folder\n");
967 fclose(file);
968 return TRUE;
971 static BOOL write_menu_file(const char *unix_link, const char *filename)
973 char *tempfilename;
974 FILE *tempfile = NULL;
975 char *lastEntry;
976 char *name = NULL;
977 char *menuPath = NULL;
978 int i;
979 int count = 0;
980 BOOL ret = FALSE;
982 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
984 while (1)
986 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
987 if (tempfilename)
989 int tempfd = mkstemps(tempfilename, 0);
990 if (tempfd >= 0)
992 tempfile = fdopen(tempfd, "w");
993 if (tempfile)
994 break;
995 close(tempfd);
996 goto end;
998 else if (errno == EEXIST)
1000 HeapFree(GetProcessHeap(), 0, tempfilename);
1001 continue;
1003 HeapFree(GetProcessHeap(), 0, tempfilename);
1005 return FALSE;
1008 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1009 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1010 fprintf(tempfile, "<Menu>\n");
1011 fprintf(tempfile, " <Name>Applications</Name>\n");
1013 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1014 if (name == NULL) goto end;
1015 lastEntry = name;
1016 for (i = 0; filename[i]; i++)
1018 name[i] = filename[i];
1019 if (filename[i] == '/')
1021 char *dir_file_name;
1022 struct stat st;
1023 name[i] = 0;
1024 fprintf(tempfile, " <Menu>\n");
1025 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1026 write_xml_text(tempfile, name);
1027 fprintf(tempfile, "</Name>\n");
1028 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1029 write_xml_text(tempfile, name);
1030 fprintf(tempfile, ".directory</Directory>\n");
1031 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1032 xdg_data_dir, count ? "" : "wine-", name);
1033 if (dir_file_name)
1035 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1036 write_directory_entry(lastEntry, dir_file_name);
1037 HeapFree(GetProcessHeap(), 0, dir_file_name);
1039 name[i] = '-';
1040 lastEntry = &name[i+1];
1041 ++count;
1044 name[i] = 0;
1046 fprintf(tempfile, " <Include>\n");
1047 fprintf(tempfile, " <Filename>");
1048 write_xml_text(tempfile, name);
1049 fprintf(tempfile, "</Filename>\n");
1050 fprintf(tempfile, " </Include>\n");
1051 for (i = 0; i < count; i++)
1052 fprintf(tempfile, " </Menu>\n");
1053 fprintf(tempfile, "</Menu>\n");
1055 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1056 if (menuPath == NULL) goto end;
1057 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1058 ret = TRUE;
1060 end:
1061 if (tempfile)
1062 fclose(tempfile);
1063 if (ret)
1064 ret = (rename(tempfilename, menuPath) == 0);
1065 if (!ret && tempfilename)
1066 remove(tempfilename);
1067 HeapFree(GetProcessHeap(), 0, tempfilename);
1068 if (ret)
1069 register_menus_entry(menuPath, unix_link);
1070 HeapFree(GetProcessHeap(), 0, name);
1071 HeapFree(GetProcessHeap(), 0, menuPath);
1072 return ret;
1075 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1076 const char *descr, const char *workdir, const char *icon)
1078 const char *linkname;
1079 char *desktopPath = NULL;
1080 char *desktopDir;
1081 char *filename = NULL;
1082 BOOL ret = TRUE;
1084 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1085 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1086 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1088 linkname = strrchr(link, '/');
1089 if (linkname == NULL)
1090 linkname = link;
1091 else
1092 ++linkname;
1094 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1095 if (!desktopPath)
1097 WINE_WARN("out of memory creating menu entry\n");
1098 ret = FALSE;
1099 goto end;
1101 desktopDir = strrchr(desktopPath, '/');
1102 *desktopDir = 0;
1103 if (!create_directories(desktopPath))
1105 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1106 ret = FALSE;
1107 goto end;
1109 *desktopDir = '/';
1110 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1112 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1113 ret = FALSE;
1114 goto end;
1117 filename = heap_printf("wine/%s.desktop", link);
1118 if (!filename || !write_menu_file(unix_link, filename))
1120 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1121 ret = FALSE;
1124 end:
1125 HeapFree(GetProcessHeap(), 0, desktopPath);
1126 HeapFree(GetProcessHeap(), 0, filename);
1127 return ret;
1130 /* This escapes reserved characters in .desktop files' Exec keys. */
1131 static LPSTR escape(LPCWSTR arg)
1133 int i, j;
1134 WCHAR *escaped_string;
1135 char *utf8_string;
1137 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1138 if (escaped_string == NULL) return NULL;
1139 for (i = j = 0; arg[i]; i++)
1141 switch (arg[i])
1143 case '\\':
1144 escaped_string[j++] = '\\';
1145 escaped_string[j++] = '\\';
1146 escaped_string[j++] = '\\';
1147 escaped_string[j++] = '\\';
1148 break;
1149 case ' ':
1150 case '\t':
1151 case '\n':
1152 case '"':
1153 case '\'':
1154 case '>':
1155 case '<':
1156 case '~':
1157 case '|':
1158 case '&':
1159 case ';':
1160 case '$':
1161 case '*':
1162 case '?':
1163 case '#':
1164 case '(':
1165 case ')':
1166 case '`':
1167 escaped_string[j++] = '\\';
1168 escaped_string[j++] = '\\';
1169 /* fall through */
1170 default:
1171 escaped_string[j++] = arg[i];
1172 break;
1175 escaped_string[j] = 0;
1177 utf8_string = wchars_to_utf8_chars(escaped_string);
1178 if (utf8_string == NULL)
1180 WINE_ERR("out of memory\n");
1181 goto end;
1184 end:
1185 HeapFree(GetProcessHeap(), 0, escaped_string);
1186 return utf8_string;
1189 /* Return a heap-allocated copy of the unix format difference between the two
1190 * Windows-format paths.
1191 * locn is the owning location
1192 * link is within locn
1194 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1196 char *unix_locn, *unix_link;
1197 char *relative = NULL;
1199 unix_locn = wine_get_unix_file_name(locn);
1200 unix_link = wine_get_unix_file_name(link);
1201 if (unix_locn && unix_link)
1203 size_t len_unix_locn, len_unix_link;
1204 len_unix_locn = strlen (unix_locn);
1205 len_unix_link = strlen (unix_link);
1206 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1208 size_t len_rel;
1209 char *p = strrchr (unix_link + len_unix_locn, '/');
1210 p = strrchr (p, '.');
1211 if (p)
1213 *p = '\0';
1214 len_unix_link = p - unix_link;
1216 len_rel = len_unix_link - len_unix_locn;
1217 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1218 if (relative)
1220 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1224 if (!relative)
1225 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1226 HeapFree(GetProcessHeap(), 0, unix_locn);
1227 HeapFree(GetProcessHeap(), 0, unix_link);
1228 return relative;
1231 /***********************************************************************
1233 * GetLinkLocation
1235 * returns TRUE if successful
1236 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1237 * *relative will contain the address of a heap-allocated copy of the portion
1238 * of the filename that is within the specified location, in unix form
1240 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1242 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1243 DWORD len, i, r, filelen;
1244 const DWORD locations[] = {
1245 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1246 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1247 CSIDL_COMMON_STARTMENU };
1249 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1250 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1251 if (filelen==0 || filelen>MAX_PATH)
1252 return FALSE;
1254 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1256 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1257 * expand or our hardcoded list won't match.
1259 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1260 if (filelen==0 || filelen>MAX_PATH)
1261 return FALSE;
1263 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1265 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1267 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1268 continue;
1270 len = lstrlenW(buffer);
1271 if (len >= MAX_PATH)
1272 continue; /* We've just trashed memory! Hopefully we are OK */
1274 if (len > filelen || filename[len]!='\\')
1275 continue;
1276 /* do a lstrcmpinW */
1277 filename[len] = 0;
1278 r = lstrcmpiW( filename, buffer );
1279 filename[len] = '\\';
1280 if ( r )
1281 continue;
1283 /* return the remainder of the string and link type */
1284 *loc = locations[i];
1285 *relative = relative_path (filename, buffer);
1286 return (*relative != NULL);
1289 return FALSE;
1292 /* gets the target path directly or through MSI */
1293 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1294 LPWSTR szArgs, DWORD argsSize)
1296 IShellLinkDataList *dl = NULL;
1297 EXP_DARWIN_LINK *dar = NULL;
1298 HRESULT hr;
1300 szPath[0] = 0;
1301 szArgs[0] = 0;
1303 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1304 if (hr == S_OK && szPath[0])
1306 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1307 return hr;
1310 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1311 if (FAILED(hr))
1312 return hr;
1314 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1315 if (SUCCEEDED(hr))
1317 WCHAR* szCmdline;
1318 DWORD cmdSize;
1320 cmdSize=0;
1321 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1322 if (hr == ERROR_SUCCESS)
1324 cmdSize++;
1325 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1326 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1327 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1328 if (hr == ERROR_SUCCESS)
1330 WCHAR *s, *d;
1331 int bcount, in_quotes;
1333 /* Extract the application path */
1334 bcount=0;
1335 in_quotes=0;
1336 s=szCmdline;
1337 d=szPath;
1338 while (*s)
1340 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1342 /* skip the remaining spaces */
1343 do {
1344 s++;
1345 } while (*s==0x0009 || *s==0x0020);
1346 break;
1348 else if (*s==0x005c)
1350 /* '\\' */
1351 *d++=*s++;
1352 bcount++;
1354 else if (*s==0x0022)
1356 /* '"' */
1357 if ((bcount & 1)==0)
1359 /* Preceded by an even number of '\', this is
1360 * half that number of '\', plus a quote which
1361 * we erase.
1363 d-=bcount/2;
1364 in_quotes=!in_quotes;
1365 s++;
1367 else
1369 /* Preceded by an odd number of '\', this is
1370 * half that number of '\' followed by a '"'
1372 d=d-bcount/2-1;
1373 *d++='"';
1374 s++;
1376 bcount=0;
1378 else
1380 /* a regular character */
1381 *d++=*s++;
1382 bcount=0;
1384 if ((d-szPath) == pathSize)
1386 /* Keep processing the path till we get to the
1387 * arguments, but 'stand still'
1389 d--;
1392 /* Close the application path */
1393 *d=0;
1395 lstrcpynW(szArgs, s, argsSize);
1397 HeapFree( GetProcessHeap(), 0, szCmdline );
1399 LocalFree( dar );
1402 IShellLinkDataList_Release( dl );
1403 return hr;
1406 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1408 HRESULT hr;
1409 WCHAR *value = NULL;
1410 DWORD size = 0;
1411 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1412 if (SUCCEEDED(hr))
1414 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1415 if (value)
1417 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1418 if (FAILED(hr))
1420 HeapFree(GetProcessHeap(), 0, value);
1421 value = NULL;
1425 return value;
1428 static char *slashes_to_minuses(const char *string)
1430 int i;
1431 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1432 if (ret)
1434 for (i = 0; string[i]; i++)
1436 if (string[i] == '/')
1437 ret[i] = '-';
1438 else
1439 ret[i] = string[i];
1441 ret[i] = 0;
1442 return ret;
1444 return NULL;
1447 static BOOL next_line(FILE *file, char **line, int *size)
1449 int pos = 0;
1450 char *cr;
1451 if (*line == NULL)
1453 *size = 4096;
1454 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1456 while (*line != NULL)
1458 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1460 HeapFree(GetProcessHeap(), 0, *line);
1461 *line = NULL;
1462 if (feof(file))
1463 return TRUE;
1464 return FALSE;
1466 pos = strlen(*line);
1467 cr = strchr(*line, '\n');
1468 if (cr == NULL)
1470 char *line2;
1471 (*size) *= 2;
1472 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1473 if (line2)
1474 *line = line2;
1475 else
1477 HeapFree(GetProcessHeap(), 0, *line);
1478 *line = NULL;
1481 else
1483 *cr = 0;
1484 return TRUE;
1487 return FALSE;
1490 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1492 char *globs_filename = NULL;
1493 BOOL ret = TRUE;
1494 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1495 if (globs_filename)
1497 FILE *globs_file = fopen(globs_filename, "r");
1498 if (globs_file) /* doesn't have to exist */
1500 char *line = NULL;
1501 int size = 0;
1502 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1504 char *pos;
1505 struct xdg_mime_type *mime_type_entry = NULL;
1506 if (line[0] != '#' && (pos = strchr(line, ':')))
1508 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1509 if (mime_type_entry)
1511 *pos = 0;
1512 mime_type_entry->mimeType = strdupA(line);
1513 mime_type_entry->glob = strdupA(pos + 1);
1514 if (mime_type_entry->mimeType && mime_type_entry->glob)
1515 list_add_tail(mime_types, &mime_type_entry->entry);
1516 else
1518 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1519 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1520 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1521 ret = FALSE;
1524 else
1525 ret = FALSE;
1528 HeapFree(GetProcessHeap(), 0, line);
1529 fclose(globs_file);
1531 HeapFree(GetProcessHeap(), 0, globs_filename);
1533 else
1534 ret = FALSE;
1535 return ret;
1538 static void free_native_mime_types(struct list *native_mime_types)
1540 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1542 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1544 list_remove(&mime_type_entry->entry);
1545 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1546 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1547 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1549 HeapFree(GetProcessHeap(), 0, native_mime_types);
1552 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1554 char *xdg_data_dirs;
1555 BOOL ret;
1557 *mime_types = NULL;
1559 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1560 if (xdg_data_dirs == NULL)
1561 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1562 else
1563 xdg_data_dirs = strdupA(xdg_data_dirs);
1565 if (xdg_data_dirs)
1567 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1568 if (*mime_types)
1570 const char *begin;
1571 char *end;
1573 list_init(*mime_types);
1574 ret = add_mimes(xdg_data_home, *mime_types);
1575 if (ret)
1577 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1579 *end = '\0';
1580 ret = add_mimes(begin, *mime_types);
1581 *end = ':';
1582 if (!ret)
1583 break;
1585 if (ret)
1586 ret = add_mimes(begin, *mime_types);
1589 else
1590 ret = FALSE;
1591 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1593 else
1594 ret = FALSE;
1595 if (!ret && *mime_types)
1597 free_native_mime_types(*mime_types);
1598 *mime_types = NULL;
1600 return ret;
1603 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1604 char **match)
1606 #ifdef HAVE_FNMATCH
1607 struct xdg_mime_type *mime_type_entry;
1608 int matchLength = 0;
1610 *match = NULL;
1612 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1614 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1616 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1618 *match = mime_type_entry->mimeType;
1619 matchLength = strlen(mime_type_entry->glob);
1624 if (*match != NULL)
1626 *match = strdupA(*match);
1627 if (*match == NULL)
1628 return FALSE;
1630 #else
1631 *match = NULL;
1632 #endif
1633 return TRUE;
1636 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1637 const char *extensionA,
1638 LPCWSTR extensionW,
1639 char **mime_type)
1641 WCHAR *lower_extensionW;
1642 INT len;
1643 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1644 if (ret == FALSE || *mime_type != NULL)
1645 return ret;
1646 len = strlenW(extensionW);
1647 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1648 if (lower_extensionW)
1650 char *lower_extensionA;
1651 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1652 strlwrW(lower_extensionW);
1653 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1654 if (lower_extensionA)
1656 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1657 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1659 else
1661 ret = FALSE;
1662 WINE_FIXME("out of memory\n");
1664 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1666 else
1668 ret = FALSE;
1669 WINE_FIXME("out of memory\n");
1671 return ret;
1674 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1676 DWORD size;
1677 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1679 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1680 if (ret)
1682 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1683 return ret;
1685 HeapFree(GetProcessHeap(), 0, ret);
1687 return NULL;
1690 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
1692 WCHAR *valW = reg_get_valW(key, subkey, name);
1693 if (valW)
1695 char *val = wchars_to_utf8_chars(valW);
1696 HeapFree(GetProcessHeap(), 0, valW);
1697 return val;
1699 return NULL;
1702 static HKEY open_associations_reg_key(void)
1704 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1705 '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};
1706 HKEY assocKey;
1707 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1708 return assocKey;
1709 return NULL;
1712 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1714 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1715 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1716 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1717 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1718 HKEY assocKey;
1719 BOOL ret;
1721 if ((assocKey = open_associations_reg_key()))
1723 CHAR *valueA;
1724 WCHAR *value;
1726 ret = FALSE;
1728 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
1729 if (!valueA || lstrcmpA(valueA, mimeType))
1730 ret = TRUE;
1731 HeapFree(GetProcessHeap(), 0, valueA);
1733 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1734 if (!value || strcmpW(value, progId))
1735 ret = TRUE;
1736 HeapFree(GetProcessHeap(), 0, value);
1738 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
1739 if (!valueA || lstrcmpA(valueA, appName))
1740 ret = TRUE;
1741 HeapFree(GetProcessHeap(), 0, valueA);
1743 value = reg_get_valW(assocKey, extensionW, DocNameW);
1744 if (docName && (!value || strcmpW(value, docName)))
1745 ret = TRUE;
1746 HeapFree(GetProcessHeap(), 0, value);
1748 RegCloseKey(assocKey);
1750 else
1752 WINE_ERR("error opening associations registry key\n");
1753 ret = FALSE;
1755 return ret;
1758 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1760 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1761 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1762 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1763 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1764 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
1765 HKEY assocKey = NULL;
1766 HKEY subkey = NULL;
1767 WCHAR *mimeTypeW = NULL;
1768 WCHAR *appNameW = NULL;
1769 WCHAR *desktopFileW = NULL;
1771 assocKey = open_associations_reg_key();
1772 if (assocKey == NULL)
1774 WINE_ERR("could not open file associations key\n");
1775 goto done;
1778 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
1780 WINE_ERR("could not create extension subkey\n");
1781 goto done;
1784 mimeTypeW = utf8_chars_to_wchars(mimeType);
1785 if (mimeTypeW == NULL)
1787 WINE_ERR("out of memory\n");
1788 goto done;
1791 appNameW = utf8_chars_to_wchars(appName);
1792 if (appNameW == NULL)
1794 WINE_ERR("out of memory\n");
1795 goto done;
1798 desktopFileW = utf8_chars_to_wchars(desktopFile);
1799 if (desktopFileW == NULL)
1801 WINE_ERR("out of memory\n");
1802 goto done;
1805 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
1806 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1807 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
1808 if (docName)
1809 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1810 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
1812 done:
1813 RegCloseKey(assocKey);
1814 RegCloseKey(subkey);
1815 HeapFree(GetProcessHeap(), 0, mimeTypeW);
1816 HeapFree(GetProcessHeap(), 0, appNameW);
1817 HeapFree(GetProcessHeap(), 0, desktopFileW);
1820 static BOOL cleanup_associations(void)
1822 static const WCHAR openW[] = {'o','p','e','n',0};
1823 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
1824 HKEY assocKey;
1825 BOOL hasChanged = FALSE;
1826 if ((assocKey = open_associations_reg_key()))
1828 int i;
1829 BOOL done = FALSE;
1830 for (i = 0; !done; i++)
1832 WCHAR *extensionW = NULL;
1833 DWORD size = 1024;
1834 LSTATUS ret;
1838 HeapFree(GetProcessHeap(), 0, extensionW);
1839 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1840 if (extensionW == NULL)
1842 WINE_ERR("out of memory\n");
1843 ret = ERROR_OUTOFMEMORY;
1844 break;
1846 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1847 size *= 2;
1848 } while (ret == ERROR_MORE_DATA);
1850 if (ret == ERROR_SUCCESS)
1852 WCHAR *command;
1853 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1854 if (command == NULL)
1856 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
1857 if (desktopFile)
1859 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
1860 remove(desktopFile);
1862 RegDeleteKeyW(assocKey, extensionW);
1863 hasChanged = TRUE;
1864 HeapFree(GetProcessHeap(), 0, desktopFile);
1866 HeapFree(GetProcessHeap(), 0, command);
1868 else
1870 if (ret != ERROR_NO_MORE_ITEMS)
1871 WINE_ERR("error %d while reading registry\n", ret);
1872 done = TRUE;
1874 HeapFree(GetProcessHeap(), 0, extensionW);
1876 RegCloseKey(assocKey);
1878 else
1879 WINE_ERR("could not open file associations key\n");
1880 return hasChanged;
1883 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1884 const char *mime_type, const char *comment)
1886 BOOL ret = FALSE;
1887 char *filename;
1889 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1890 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1892 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1893 if (filename)
1895 FILE *packageFile = fopen(filename, "w");
1896 if (packageFile)
1898 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1899 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1900 fprintf(packageFile, " <mime-type type=\"");
1901 write_xml_text(packageFile, mime_type);
1902 fprintf(packageFile, "\">\n");
1903 fprintf(packageFile, " <glob pattern=\"*");
1904 write_xml_text(packageFile, dot_extension);
1905 fprintf(packageFile, "\"/>\n");
1906 if (comment)
1908 fprintf(packageFile, " <comment>");
1909 write_xml_text(packageFile, comment);
1910 fprintf(packageFile, "</comment>\n");
1912 fprintf(packageFile, " </mime-type>\n");
1913 fprintf(packageFile, "</mime-info>\n");
1914 ret = TRUE;
1915 fclose(packageFile);
1917 else
1918 WINE_ERR("error writing file %s\n", filename);
1919 HeapFree(GetProcessHeap(), 0, filename);
1921 else
1922 WINE_ERR("out of memory\n");
1923 return ret;
1926 static BOOL is_extension_blacklisted(LPCWSTR extension)
1928 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1929 static const WCHAR comW[] = {'.','c','o','m',0};
1930 static const WCHAR exeW[] = {'.','e','x','e',0};
1931 static const WCHAR msiW[] = {'.','m','s','i',0};
1933 if (!strcmpiW(extension, comW) ||
1934 !strcmpiW(extension, exeW) ||
1935 !strcmpiW(extension, msiW))
1936 return TRUE;
1937 return FALSE;
1940 static const char* get_special_mime_type(LPCWSTR extension)
1942 static const WCHAR lnkW[] = {'.','l','n','k',0};
1943 if (!strcmpiW(extension, lnkW))
1944 return "application/x-ms-shortcut";
1945 return NULL;
1948 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1949 const char *friendlyAppName, const char *mimeType,
1950 const char *progId)
1952 BOOL ret = FALSE;
1953 FILE *desktop;
1955 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1956 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1957 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1959 desktop = fopen(desktopPath, "w");
1960 if (desktop)
1962 fprintf(desktop, "[Desktop Entry]\n");
1963 fprintf(desktop, "Type=Application\n");
1964 fprintf(desktop, "Name=%s\n", friendlyAppName);
1965 fprintf(desktop, "MimeType=%s\n", mimeType);
1966 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1967 fprintf(desktop, "NoDisplay=true\n");
1968 fprintf(desktop, "StartupNotify=true\n");
1969 ret = TRUE;
1970 fclose(desktop);
1972 else
1973 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1974 return ret;
1977 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1979 static const WCHAR openW[] = {'o','p','e','n',0};
1980 struct list *nativeMimeTypes = NULL;
1981 LSTATUS ret = 0;
1982 int i;
1983 BOOL hasChanged = FALSE;
1985 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1987 WINE_ERR("could not build native MIME types\n");
1988 return FALSE;
1991 for (i = 0; ; i++)
1993 WCHAR *extensionW = NULL;
1994 DWORD size = 1024;
1998 HeapFree(GetProcessHeap(), 0, extensionW);
1999 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2000 if (extensionW == NULL)
2002 WINE_ERR("out of memory\n");
2003 ret = ERROR_OUTOFMEMORY;
2004 break;
2006 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2007 size *= 2;
2008 } while (ret == ERROR_MORE_DATA);
2010 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2012 char *extensionA = NULL;
2013 WCHAR *commandW = NULL;
2014 WCHAR *friendlyDocNameW = NULL;
2015 char *friendlyDocNameA = NULL;
2016 WCHAR *iconW = NULL;
2017 char *iconA = NULL;
2018 WCHAR *contentTypeW = NULL;
2019 char *mimeTypeA = NULL;
2020 WCHAR *friendlyAppNameW = NULL;
2021 char *friendlyAppNameA = NULL;
2022 WCHAR *progIdW = NULL;
2023 char *progIdA = NULL;
2025 extensionA = wchars_to_utf8_chars(extensionW);
2026 if (extensionA == NULL)
2028 WINE_ERR("out of memory\n");
2029 goto end;
2032 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2033 if (friendlyDocNameW)
2035 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2036 if (friendlyDocNameA == NULL)
2038 WINE_ERR("out of memory\n");
2039 goto end;
2043 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2045 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2046 if (contentTypeW)
2047 strlwrW(contentTypeW);
2049 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2050 goto end;
2052 if (mimeTypeA == NULL)
2054 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2055 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2056 else if ((get_special_mime_type(extensionW)))
2057 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2058 else
2059 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2061 if (mimeTypeA != NULL)
2063 /* Gnome seems to ignore the <icon> tag in MIME packages,
2064 * and the default name is more intuitive anyway.
2066 if (iconW)
2068 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2069 if (flattened_mime)
2071 int index = 0;
2072 WCHAR *comma = strrchrW(iconW, ',');
2073 if (comma)
2075 *comma = 0;
2076 index = atoiW(comma + 1);
2078 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2079 HeapFree(GetProcessHeap(), 0, flattened_mime);
2083 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2084 hasChanged = TRUE;
2086 else
2088 WINE_FIXME("out of memory\n");
2089 goto end;
2093 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2094 if (commandW == NULL)
2095 /* no command => no application is associated */
2096 goto end;
2098 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2099 if (friendlyAppNameW)
2101 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2102 if (friendlyAppNameA == NULL)
2104 WINE_ERR("out of memory\n");
2105 goto end;
2108 else
2110 friendlyAppNameA = heap_printf("A Wine application");
2111 if (friendlyAppNameA == NULL)
2113 WINE_ERR("out of memory\n");
2114 goto end;
2118 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2119 if (progIdW)
2121 progIdA = escape(progIdW);
2122 if (progIdA == NULL)
2124 WINE_ERR("out of memory\n");
2125 goto end;
2128 else
2129 goto end; /* no progID => not a file type association */
2131 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2133 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2134 if (desktopPath)
2136 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2138 hasChanged = TRUE;
2139 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2141 HeapFree(GetProcessHeap(), 0, desktopPath);
2145 end:
2146 HeapFree(GetProcessHeap(), 0, extensionA);
2147 HeapFree(GetProcessHeap(), 0, commandW);
2148 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2149 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2150 HeapFree(GetProcessHeap(), 0, iconW);
2151 HeapFree(GetProcessHeap(), 0, iconA);
2152 HeapFree(GetProcessHeap(), 0, contentTypeW);
2153 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2154 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2155 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2156 HeapFree(GetProcessHeap(), 0, progIdW);
2157 HeapFree(GetProcessHeap(), 0, progIdA);
2159 HeapFree(GetProcessHeap(), 0, extensionW);
2160 if (ret != ERROR_SUCCESS)
2161 break;
2164 free_native_mime_types(nativeMimeTypes);
2165 return hasChanged;
2168 static char *get_start_exe_path(void)
2170 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2171 '\\','s','t','a','r','t','.','e','x','e',0};
2172 WCHAR start_path[MAX_PATH];
2173 GetWindowsDirectoryW(start_path, MAX_PATH);
2174 lstrcatW(start_path, startW);
2175 return escape(start_path);
2178 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2180 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2181 '\\','s','t','a','r','t','.','e','x','e',0};
2182 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2183 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2184 WCHAR szTmp[INFOTIPSIZE];
2185 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2186 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2187 int iIconId = 0, r = -1;
2188 DWORD csidl = -1;
2189 HANDLE hsem = NULL;
2190 char *unix_link = NULL;
2191 char *start_path = NULL;
2193 if ( !link )
2195 WINE_ERR("Link name is null\n");
2196 return FALSE;
2199 if( !GetLinkLocation( link, &csidl, &link_name ) )
2201 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2202 return TRUE;
2204 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2206 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2207 return TRUE;
2209 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2211 szTmp[0] = 0;
2212 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2213 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2214 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2216 szTmp[0] = 0;
2217 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2218 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2219 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2221 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2222 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2223 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2224 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2226 szTmp[0] = 0;
2227 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2228 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2229 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2231 if( !szPath[0] )
2233 LPITEMIDLIST pidl = NULL;
2234 IShellLinkW_GetIDList( sl, &pidl );
2235 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2236 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2239 /* extract the icon */
2240 if( szIconPath[0] )
2241 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2242 else
2243 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2245 /* fail - try once again after parent process exit */
2246 if( !icon_name )
2248 if (bWait)
2250 WINE_WARN("Unable to extract icon, deferring.\n");
2251 goto cleanup;
2253 WINE_ERR("failed to extract icon from %s\n",
2254 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2257 unix_link = wine_get_unix_file_name(link);
2258 if (unix_link == NULL)
2260 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2261 goto cleanup;
2264 /* check the path */
2265 if( szPath[0] )
2267 static const WCHAR exeW[] = {'.','e','x','e',0};
2268 WCHAR *p;
2270 /* check for .exe extension */
2271 if (!(p = strrchrW( szPath, '.' )) ||
2272 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2273 lstrcmpiW( p, exeW ))
2275 /* Not .exe - use 'start.exe' to launch this file */
2276 p = szArgs + lstrlenW(szPath) + 2;
2277 if (szArgs[0])
2279 p[0] = ' ';
2280 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2281 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2283 else
2284 p[0] = 0;
2286 szArgs[0] = '"';
2287 lstrcpyW(szArgs + 1, szPath);
2288 p[-1] = '"';
2290 GetWindowsDirectoryW(szPath, MAX_PATH);
2291 lstrcatW(szPath, startW);
2294 /* convert app working dir */
2295 if (szWorkDir[0])
2296 work_dir = wine_get_unix_file_name( szWorkDir );
2298 else
2300 /* if there's no path... try run the link itself */
2301 lstrcpynW(szArgs, link, MAX_PATH);
2302 GetWindowsDirectoryW(szPath, MAX_PATH);
2303 lstrcatW(szPath, startW);
2306 /* escape the path and parameters */
2307 escaped_path = escape(szPath);
2308 escaped_args = escape(szArgs);
2309 description = wchars_to_utf8_chars(szDescription);
2310 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2312 WINE_ERR("out of memory allocating/escaping parameters\n");
2313 goto cleanup;
2316 start_path = get_start_exe_path();
2317 if (start_path == NULL)
2319 WINE_ERR("out of memory\n");
2320 goto cleanup;
2323 /* building multiple menus concurrently has race conditions */
2324 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2325 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2327 WINE_ERR("failed wait for semaphore\n");
2328 goto cleanup;
2331 if (in_desktop_dir(csidl))
2333 char *location;
2334 const char *lastEntry;
2335 lastEntry = strrchr(link_name, '/');
2336 if (lastEntry == NULL)
2337 lastEntry = link_name;
2338 else
2339 ++lastEntry;
2340 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2341 if (location)
2343 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2344 if (r == 0)
2345 chmod(location, 0755);
2346 HeapFree(GetProcessHeap(), 0, location);
2349 else
2351 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2352 if (unix_linkW)
2354 char *escaped_lnk = escape(unix_linkW);
2355 if (escaped_lnk)
2357 char *menuarg = heap_printf("/Unix %s", escaped_lnk);
2358 if (menuarg)
2360 r = !write_menu_entry(unix_link, link_name, start_path, menuarg, description, work_dir, icon_name);
2361 HeapFree(GetProcessHeap(), 0, menuarg);
2363 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2365 HeapFree(GetProcessHeap(), 0, unix_linkW);
2369 ReleaseSemaphore( hsem, 1, NULL );
2371 cleanup:
2372 if (hsem) CloseHandle( hsem );
2373 HeapFree( GetProcessHeap(), 0, icon_name );
2374 HeapFree( GetProcessHeap(), 0, work_dir );
2375 HeapFree( GetProcessHeap(), 0, link_name );
2376 HeapFree( GetProcessHeap(), 0, escaped_args );
2377 HeapFree( GetProcessHeap(), 0, escaped_path );
2378 HeapFree( GetProcessHeap(), 0, description );
2379 HeapFree( GetProcessHeap(), 0, unix_link );
2380 HeapFree( GetProcessHeap(), 0, start_path );
2382 if (r && !bWait)
2383 WINE_ERR("failed to build the menu\n" );
2385 return ( r == 0 );
2388 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2390 char *link_name = NULL;
2391 DWORD csidl = -1;
2392 LPWSTR urlPath;
2393 char *escaped_urlPath = NULL;
2394 HRESULT hr;
2395 HANDLE hSem = NULL;
2396 BOOL ret = TRUE;
2397 int r = -1;
2398 char *unix_link = NULL;
2400 if ( !link )
2402 WINE_ERR("Link name is null\n");
2403 return TRUE;
2406 if( !GetLinkLocation( link, &csidl, &link_name ) )
2408 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2409 return TRUE;
2411 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2413 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2414 ret = TRUE;
2415 goto cleanup;
2417 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2419 hr = url->lpVtbl->GetURL(url, &urlPath);
2420 if (FAILED(hr))
2422 ret = TRUE;
2423 goto cleanup;
2425 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2427 unix_link = wine_get_unix_file_name(link);
2428 if (unix_link == NULL)
2430 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2431 goto cleanup;
2434 escaped_urlPath = escape(urlPath);
2435 if (escaped_urlPath == NULL)
2437 WINE_ERR("couldn't escape url, out of memory\n");
2438 goto cleanup;
2441 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2442 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2444 WINE_ERR("failed wait for semaphore\n");
2445 goto cleanup;
2447 if (in_desktop_dir(csidl))
2449 char *location;
2450 const char *lastEntry;
2451 lastEntry = strrchr(link_name, '/');
2452 if (lastEntry == NULL)
2453 lastEntry = link_name;
2454 else
2455 ++lastEntry;
2456 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2457 if (location)
2459 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2460 if (r == 0)
2461 chmod(location, 0755);
2462 HeapFree(GetProcessHeap(), 0, location);
2465 else
2466 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2467 ret = (r != 0);
2468 ReleaseSemaphore(hSem, 1, NULL);
2470 cleanup:
2471 if (hSem)
2472 CloseHandle(hSem);
2473 HeapFree(GetProcessHeap(), 0, link_name);
2474 CoTaskMemFree( urlPath );
2475 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2476 HeapFree(GetProcessHeap(), 0, unix_link);
2477 return ret;
2480 static BOOL WaitForParentProcess( void )
2482 PROCESSENTRY32 procentry;
2483 HANDLE hsnapshot = NULL, hprocess = NULL;
2484 DWORD ourpid = GetCurrentProcessId();
2485 BOOL ret = FALSE, rc;
2487 WINE_TRACE("Waiting for parent process\n");
2488 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2489 INVALID_HANDLE_VALUE)
2491 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2492 goto done;
2495 procentry.dwSize = sizeof(PROCESSENTRY32);
2496 rc = Process32First( hsnapshot, &procentry );
2497 while (rc)
2499 if (procentry.th32ProcessID == ourpid) break;
2500 rc = Process32Next( hsnapshot, &procentry );
2502 if (!rc)
2504 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2505 goto done;
2508 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2509 NULL)
2511 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2512 GetLastError());
2513 goto done;
2516 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2517 ret = TRUE;
2518 else
2519 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2521 done:
2522 if (hprocess) CloseHandle( hprocess );
2523 if (hsnapshot) CloseHandle( hsnapshot );
2524 return ret;
2527 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2529 IShellLinkW *sl;
2530 IPersistFile *pf;
2531 HRESULT r;
2532 WCHAR fullname[MAX_PATH];
2533 DWORD len;
2535 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2537 if( !linkname[0] )
2539 WINE_ERR("link name missing\n");
2540 return 1;
2543 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2544 if (len==0 || len>MAX_PATH)
2546 WINE_ERR("couldn't get full path of link file\n");
2547 return 1;
2550 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2551 &IID_IShellLinkW, (LPVOID *) &sl );
2552 if( FAILED( r ) )
2554 WINE_ERR("No IID_IShellLink\n");
2555 return 1;
2558 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2559 if( FAILED( r ) )
2561 WINE_ERR("No IID_IPersistFile\n");
2562 return 1;
2565 r = IPersistFile_Load( pf, fullname, STGM_READ );
2566 if( SUCCEEDED( r ) )
2568 /* If something fails (eg. Couldn't extract icon)
2569 * wait for parent process and try again
2571 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2573 WaitForParentProcess();
2574 InvokeShellLinker( sl, fullname, FALSE );
2577 else
2579 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2582 IPersistFile_Release( pf );
2583 IShellLinkW_Release( sl );
2585 return !r;
2588 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2590 IUniformResourceLocatorW *url;
2591 IPersistFile *pf;
2592 HRESULT r;
2593 WCHAR fullname[MAX_PATH];
2594 DWORD len;
2596 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2598 if( !urlname[0] )
2600 WINE_ERR("URL name missing\n");
2601 return 1;
2604 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2605 if (len==0 || len>MAX_PATH)
2607 WINE_ERR("couldn't get full path of URL file\n");
2608 return 1;
2611 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2612 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2613 if( FAILED( r ) )
2615 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2616 return 1;
2619 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2620 if( FAILED( r ) )
2622 WINE_ERR("No IID_IPersistFile\n");
2623 return 1;
2625 r = IPersistFile_Load( pf, fullname, STGM_READ );
2626 if( SUCCEEDED( r ) )
2628 /* If something fails (eg. Couldn't extract icon)
2629 * wait for parent process and try again
2631 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2633 WaitForParentProcess();
2634 InvokeShellLinkerForURL( url, fullname, FALSE );
2638 IPersistFile_Release( pf );
2639 url->lpVtbl->Release( url );
2641 return !r;
2644 static void RefreshFileTypeAssociations(void)
2646 HANDLE hSem = NULL;
2647 char *mime_dir = NULL;
2648 char *packages_dir = NULL;
2649 char *applications_dir = NULL;
2650 BOOL hasChanged;
2652 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2653 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2655 WINE_ERR("failed wait for semaphore\n");
2656 CloseHandle(hSem);
2657 hSem = NULL;
2658 goto end;
2661 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2662 if (mime_dir == NULL)
2664 WINE_ERR("out of memory\n");
2665 goto end;
2667 create_directories(mime_dir);
2669 packages_dir = heap_printf("%s/packages", mime_dir);
2670 if (packages_dir == NULL)
2672 WINE_ERR("out of memory\n");
2673 goto end;
2675 create_directories(packages_dir);
2677 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2678 if (applications_dir == NULL)
2680 WINE_ERR("out of memory\n");
2681 goto end;
2683 create_directories(applications_dir);
2685 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2686 hasChanged |= cleanup_associations();
2687 if (hasChanged)
2689 const char *argv[3];
2691 argv[0] = "update-mime-database";
2692 argv[1] = mime_dir;
2693 argv[2] = NULL;
2694 spawnvp( _P_NOWAIT, argv[0], argv );
2696 argv[0] = "update-desktop-database";
2697 argv[1] = applications_dir;
2698 spawnvp( _P_NOWAIT, argv[0], argv );
2701 end:
2702 if (hSem)
2704 ReleaseSemaphore(hSem, 1, NULL);
2705 CloseHandle(hSem);
2707 HeapFree(GetProcessHeap(), 0, mime_dir);
2708 HeapFree(GetProcessHeap(), 0, packages_dir);
2709 HeapFree(GetProcessHeap(), 0, applications_dir);
2712 static void cleanup_menus(void)
2714 HKEY hkey;
2716 hkey = open_menus_reg_key();
2717 if (hkey)
2719 int i;
2720 LSTATUS lret = ERROR_SUCCESS;
2721 for (i = 0; lret == ERROR_SUCCESS; )
2723 WCHAR *value = NULL;
2724 WCHAR *data = NULL;
2725 DWORD valueSize = 4096;
2726 DWORD dataSize = 4096;
2727 while (1)
2729 lret = ERROR_OUTOFMEMORY;
2730 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
2731 if (value == NULL)
2732 break;
2733 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
2734 if (data == NULL)
2735 break;
2736 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2737 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2738 break;
2739 valueSize *= 2;
2740 dataSize *= 2;
2741 HeapFree(GetProcessHeap(), 0, value);
2742 HeapFree(GetProcessHeap(), 0, data);
2743 value = data = NULL;
2745 if (lret == ERROR_SUCCESS)
2747 char *unix_file;
2748 char *windows_file;
2749 unix_file = wchars_to_unix_chars(value);
2750 windows_file = wchars_to_unix_chars(data);
2751 if (unix_file != NULL && windows_file != NULL)
2753 struct stat filestats;
2754 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
2756 WINE_TRACE("removing menu related file %s\n", unix_file);
2757 remove(unix_file);
2758 RegDeleteValueW(hkey, value);
2760 else
2761 i++;
2763 else
2765 WINE_ERR("out of memory enumerating menus\n");
2766 lret = ERROR_OUTOFMEMORY;
2768 HeapFree(GetProcessHeap(), 0, unix_file);
2769 HeapFree(GetProcessHeap(), 0, windows_file);
2771 else if (lret != ERROR_NO_MORE_ITEMS)
2772 WINE_ERR("error %d reading registry\n", lret);
2773 HeapFree(GetProcessHeap(), 0, value);
2774 HeapFree(GetProcessHeap(), 0, data);
2776 RegCloseKey(hkey);
2778 else
2779 WINE_ERR("error opening registry key, menu cleanup failed\n");
2782 static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
2784 char *utf8lnkPath = NULL;
2785 char *utf8OutputPath = NULL;
2786 WCHAR *winLnkPath = NULL;
2787 IShellLinkW *shellLink = NULL;
2788 IPersistFile *persistFile = NULL;
2789 WCHAR szTmp[MAX_PATH];
2790 WCHAR szPath[MAX_PATH];
2791 WCHAR szArgs[INFOTIPSIZE];
2792 WCHAR szIconPath[MAX_PATH];
2793 int iconId;
2794 IStream *stream = NULL;
2795 HRESULT hr;
2797 utf8lnkPath = wchars_to_utf8_chars(lnkPath);
2798 if (utf8lnkPath == NULL)
2800 WINE_ERR("out of memory converting paths\n");
2801 goto end;
2804 utf8OutputPath = wchars_to_utf8_chars(outputPath);
2805 if (utf8OutputPath == NULL)
2807 WINE_ERR("out of memory converting paths\n");
2808 goto end;
2811 winLnkPath = wine_get_dos_file_name(utf8lnkPath);
2812 if (winLnkPath == NULL)
2814 WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
2815 goto end;
2818 hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2819 &IID_IShellLinkW, (LPVOID*)&shellLink);
2820 if (FAILED(hr))
2822 WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
2823 goto end;
2826 hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
2827 if (FAILED(hr))
2829 WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
2830 goto end;
2833 hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
2834 if (FAILED(hr))
2836 WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
2837 goto end;
2840 get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2841 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2842 szTmp[0] = 0;
2843 IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
2844 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2846 if(!szPath[0])
2848 LPITEMIDLIST pidl = NULL;
2849 IShellLinkW_GetIDList(shellLink, &pidl);
2850 if (pidl && SHGetPathFromIDListW(pidl, szPath))
2851 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2854 if (szIconPath[0])
2856 hr = open_icon(szIconPath, iconId, FALSE, &stream);
2857 if (SUCCEEDED(hr))
2858 hr = write_native_icon(stream, utf8OutputPath, NULL);
2860 else
2862 hr = open_icon(szPath, iconId, FALSE, &stream);
2863 if (SUCCEEDED(hr))
2864 hr = write_native_icon(stream, utf8OutputPath, NULL);
2867 end:
2868 HeapFree(GetProcessHeap(), 0, utf8lnkPath);
2869 HeapFree(GetProcessHeap(), 0, utf8OutputPath);
2870 HeapFree(GetProcessHeap(), 0, winLnkPath);
2871 if (shellLink != NULL)
2872 IShellLinkW_Release(shellLink);
2873 if (persistFile != NULL)
2874 IPersistFile_Release(persistFile);
2875 if (stream != NULL)
2876 IStream_Release(stream);
2879 static WCHAR *next_token( LPWSTR *p )
2881 LPWSTR token = NULL, t = *p;
2883 if( !t )
2884 return NULL;
2886 while( t && !token )
2888 switch( *t )
2890 case ' ':
2891 t++;
2892 continue;
2893 case '"':
2894 /* unquote the token */
2895 token = ++t;
2896 t = strchrW( token, '"' );
2897 if( t )
2898 *t++ = 0;
2899 break;
2900 case 0:
2901 t = NULL;
2902 break;
2903 default:
2904 token = t;
2905 t = strchrW( token, ' ' );
2906 if( t )
2907 *t++ = 0;
2908 break;
2911 *p = t;
2912 return token;
2915 static BOOL init_xdg(void)
2917 WCHAR shellDesktopPath[MAX_PATH];
2918 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2919 if (SUCCEEDED(hr))
2920 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2921 if (xdg_desktop_dir == NULL)
2923 WINE_ERR("error looking up the desktop directory\n");
2924 return FALSE;
2927 if (getenv("XDG_CONFIG_HOME"))
2928 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2929 else
2930 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2931 if (xdg_config_dir)
2933 create_directories(xdg_config_dir);
2934 if (getenv("XDG_DATA_HOME"))
2935 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
2936 else
2937 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2938 if (xdg_data_dir)
2940 char *buffer;
2941 create_directories(xdg_data_dir);
2942 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2943 if (buffer)
2945 mkdir(buffer, 0777);
2946 HeapFree(GetProcessHeap(), 0, buffer);
2948 return TRUE;
2950 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2952 WINE_ERR("out of memory\n");
2953 return FALSE;
2956 /***********************************************************************
2958 * wWinMain
2960 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
2962 static const WCHAR dash_aW[] = {'-','a',0};
2963 static const WCHAR dash_rW[] = {'-','r',0};
2964 static const WCHAR dash_tW[] = {'-','t',0};
2965 static const WCHAR dash_uW[] = {'-','u',0};
2966 static const WCHAR dash_wW[] = {'-','w',0};
2968 LPWSTR token = NULL, p;
2969 BOOL bWait = FALSE;
2970 BOOL bURL = FALSE;
2971 HRESULT hr;
2972 int ret = 0;
2974 if (!init_xdg())
2975 return 1;
2977 hr = CoInitialize(NULL);
2978 if (FAILED(hr))
2980 WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
2981 return 1;
2984 for( p = cmdline; p && *p; )
2986 token = next_token( &p );
2987 if( !token )
2988 break;
2989 if( !strcmpW( token, dash_aW ) )
2991 RefreshFileTypeAssociations();
2992 continue;
2994 if( !strcmpW( token, dash_rW ) )
2996 cleanup_menus();
2997 continue;
2999 if( !strcmpW( token, dash_wW ) )
3000 bWait = TRUE;
3001 else if ( !strcmpW( token, dash_uW ) )
3002 bURL = TRUE;
3003 else if ( !strcmpW( token, dash_tW ) )
3005 WCHAR *lnkFile = next_token( &p );
3006 if (lnkFile)
3008 WCHAR *outputFile = next_token( &p );
3009 if (outputFile)
3010 thumbnail_lnk(lnkFile, outputFile);
3013 else if( token[0] == '-' )
3015 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3017 else
3019 BOOL bRet;
3021 if (bURL)
3022 bRet = Process_URL( token, bWait );
3023 else
3024 bRet = Process_Link( token, bWait );
3025 if (!bRet)
3027 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3028 ret = 1;
3033 CoUninitialize();
3034 return ret;