shell32: Update the Danish translation.
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blob3abfc39a429025f63f3056d46707fe0918702ae1
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>
94 #include "wine/unicode.h"
95 #include "wine/debug.h"
96 #include "wine/library.h"
97 #include "wine/list.h"
98 #include "wine.xpm"
100 #ifdef HAVE_PNG_H
101 #undef FAR
102 #include <png.h>
103 #endif
105 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
107 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
108 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
109 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
110 (csidl)==CSIDL_COMMON_STARTMENU)
112 /* link file formats */
114 #include "pshpack1.h"
116 typedef struct
118 BYTE bWidth;
119 BYTE bHeight;
120 BYTE bColorCount;
121 BYTE bReserved;
122 WORD wPlanes;
123 WORD wBitCount;
124 DWORD dwBytesInRes;
125 WORD nID;
126 } GRPICONDIRENTRY;
128 typedef struct
130 WORD idReserved;
131 WORD idType;
132 WORD idCount;
133 GRPICONDIRENTRY idEntries[1];
134 } GRPICONDIR;
136 typedef struct
138 BYTE bWidth;
139 BYTE bHeight;
140 BYTE bColorCount;
141 BYTE bReserved;
142 WORD wPlanes;
143 WORD wBitCount;
144 DWORD dwBytesInRes;
145 DWORD dwImageOffset;
146 } ICONDIRENTRY;
148 typedef struct
150 WORD idReserved;
151 WORD idType;
152 WORD idCount;
153 } ICONDIR;
156 #include "poppack.h"
158 typedef struct
160 HRSRC *pResInfo;
161 int nIndex;
162 } ENUMRESSTRUCT;
164 struct xdg_mime_type
166 char *mimeType;
167 char *glob;
168 struct list entry;
171 static char *xdg_config_dir;
172 static char *xdg_data_dir;
173 static char *xdg_desktop_dir;
175 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra);
176 static char *extract_icon(LPCWSTR path, int index, const char *destFilename, BOOL bWait);
178 /* Icon extraction routines
180 * FIXME: should use PrivateExtractIcons and friends
181 * FIXME: should not use stdio
184 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
186 /* PNG-specific code */
187 #ifdef SONAME_LIBPNG
189 static void *libpng_handle;
190 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
191 MAKE_FUNCPTR(png_create_info_struct);
192 MAKE_FUNCPTR(png_create_write_struct);
193 MAKE_FUNCPTR(png_destroy_write_struct);
194 MAKE_FUNCPTR(png_get_error_ptr);
195 MAKE_FUNCPTR(png_init_io);
196 MAKE_FUNCPTR(png_set_bgr);
197 MAKE_FUNCPTR(png_set_error_fn);
198 MAKE_FUNCPTR(png_set_text);
199 MAKE_FUNCPTR(png_set_IHDR);
200 MAKE_FUNCPTR(png_write_end);
201 MAKE_FUNCPTR(png_write_info);
202 MAKE_FUNCPTR(png_write_row);
203 #undef MAKE_FUNCPTR
205 static void *load_libpng(void)
207 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
209 #define LOAD_FUNCPTR(f) \
210 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
211 libpng_handle = NULL; \
212 return NULL; \
214 LOAD_FUNCPTR(png_create_info_struct);
215 LOAD_FUNCPTR(png_create_write_struct);
216 LOAD_FUNCPTR(png_destroy_write_struct);
217 LOAD_FUNCPTR(png_get_error_ptr);
218 LOAD_FUNCPTR(png_init_io);
219 LOAD_FUNCPTR(png_set_bgr);
220 LOAD_FUNCPTR(png_set_error_fn);
221 LOAD_FUNCPTR(png_set_IHDR);
222 LOAD_FUNCPTR(png_set_text);
223 LOAD_FUNCPTR(png_write_end);
224 LOAD_FUNCPTR(png_write_info);
225 LOAD_FUNCPTR(png_write_row);
226 #undef LOAD_FUNCPTR
228 return libpng_handle;
231 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
233 jmp_buf *pjmpbuf;
235 /* This uses setjmp/longjmp just like the default. We can't use the
236 * default because there's no way to access the jmp buffer in the png_struct
237 * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
238 WINE_ERR("PNG error: %s\n", wine_dbgstr_an(error_message, -1));
239 pjmpbuf = ppng_get_error_ptr(png_ptr);
240 longjmp(*pjmpbuf, 1);
243 static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
245 WINE_WARN("PNG warning: %s\n", wine_dbgstr_an(warning_message, -1));
248 static BOOL SaveTrueColorIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
250 static const char comment_key[] = "Created from";
251 FILE *fp;
252 png_structp png_ptr;
253 png_infop info_ptr;
254 png_text comment;
255 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
256 BYTE *row, *copy = NULL;
257 const BYTE *pXOR, *pAND = NULL;
258 int nWidth = pIcon->bmiHeader.biWidth;
259 int nHeight = pIcon->bmiHeader.biHeight;
260 int nBpp = pIcon->bmiHeader.biBitCount;
261 jmp_buf jmpbuf;
263 switch (nBpp)
265 case 32:
266 color_type |= PNG_COLOR_MASK_ALPHA;
267 /* fall through */
268 case 24:
269 color_type |= PNG_COLOR_MASK_COLOR;
270 break;
271 default:
272 return FALSE;
275 if (!libpng_handle && !load_libpng())
277 WINE_WARN("Unable to load libpng\n");
278 return FALSE;
281 if (!(fp = fopen(png_filename, "w")))
283 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
284 return FALSE;
287 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
288 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
289 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
290 if (nHeight > nWidth)
292 nHeight /= 2;
293 pAND = pXOR + nHeight * nXORWidthBytes;
296 /* Apply mask if present */
297 if (pAND)
299 RGBQUAD bgColor;
301 /* copy bytes before modifying them */
302 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
303 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
304 pXOR = copy;
306 /* image and mask are upside down reversed */
307 row = copy + (nHeight - 1) * nXORWidthBytes;
309 /* top left corner */
310 bgColor.rgbRed = row[0];
311 bgColor.rgbGreen = row[1];
312 bgColor.rgbBlue = row[2];
313 bgColor.rgbReserved = 0;
315 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
316 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
317 if (MASK(j, i))
319 RGBQUAD *pixel = (RGBQUAD *)row;
320 pixel->rgbBlue = bgColor.rgbBlue;
321 pixel->rgbGreen = bgColor.rgbGreen;
322 pixel->rgbRed = bgColor.rgbRed;
323 if (nBpp == 32)
324 pixel->rgbReserved = bgColor.rgbReserved;
328 comment.text = NULL;
330 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
331 !(info_ptr = ppng_create_info_struct(png_ptr)))
332 goto error;
334 if (setjmp(jmpbuf))
336 /* All future errors jump here */
337 goto error;
339 ppng_set_error_fn(png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
341 ppng_init_io(png_ptr, fp);
342 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
343 color_type,
344 PNG_INTERLACE_NONE,
345 PNG_COMPRESSION_TYPE_DEFAULT,
346 PNG_FILTER_TYPE_DEFAULT);
348 /* Set comment */
349 comment.compression = PNG_TEXT_COMPRESSION_NONE;
350 comment.key = (png_charp)comment_key;
351 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
352 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
353 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
354 comment.text_length = i - 1;
355 ppng_set_text(png_ptr, info_ptr, &comment, 1);
358 ppng_write_info(png_ptr, info_ptr);
359 ppng_set_bgr(png_ptr);
360 for (i = nHeight - 1; i >= 0 ; i--)
361 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
362 ppng_write_end(png_ptr, info_ptr);
364 ppng_destroy_write_struct(&png_ptr, &info_ptr);
365 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
366 fclose(fp);
367 HeapFree(GetProcessHeap(), 0, copy);
368 HeapFree(GetProcessHeap(), 0, comment.text);
369 return TRUE;
371 error:
372 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
373 fclose(fp);
374 unlink(png_filename);
375 HeapFree(GetProcessHeap(), 0, copy);
376 HeapFree(GetProcessHeap(), 0, comment.text);
377 return FALSE;
380 static BOOL SavePalettedIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
382 static const char comment_key[] = "Created from";
383 FILE *pngFile = NULL;
384 int i, j;
385 int nHeight;
386 int nXORWidthBytes;
387 int nANDWidthBytes;
388 BOOL b8BitColors;
389 int nColors;
390 const BYTE *pXOR;
391 const BYTE *pAND;
392 png_structp png_ptr;
393 png_infop info_ptr;
394 png_text comment;
395 jmp_buf jmpbuf;
396 unsigned char *row = NULL;
397 BOOL ret = FALSE;
399 comment.text = NULL;
401 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
403 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
404 goto done;
407 if (!(pngFile = fopen(png_filename, "w")))
409 WINE_TRACE("Unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
410 goto done;
413 nHeight = pIcon->bmiHeader.biHeight / 2;
414 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
415 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
416 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
417 + ((pIcon->bmiHeader.biWidth % 32) > 0));
418 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
419 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
420 : 1 << pIcon->bmiHeader.biBitCount;
421 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
422 pAND = pXOR + nHeight * nXORWidthBytes;
424 row = HeapAlloc(GetProcessHeap(), 0, 4 * pIcon->bmiHeader.biWidth);
425 if (row == NULL)
427 WINE_ERR("out of memory\n");
428 goto done;
431 if (!libpng_handle && !load_libpng())
433 WINE_WARN("Unable to load libpng\n");
434 goto done;
437 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
438 !(info_ptr = ppng_create_info_struct(png_ptr)))
439 goto done;
441 if (setjmp(jmpbuf))
443 /* All future errors jump here */
444 goto done;
446 ppng_set_error_fn(png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
448 ppng_init_io(png_ptr, pngFile);
449 ppng_set_IHDR(png_ptr, info_ptr, pIcon->bmiHeader.biWidth, nHeight, 8,
450 PNG_COLOR_TYPE_RGB_ALPHA,
451 PNG_INTERLACE_NONE,
452 PNG_COMPRESSION_TYPE_DEFAULT,
453 PNG_FILTER_TYPE_DEFAULT);
455 /* Set comment */
456 comment.compression = PNG_TEXT_COMPRESSION_NONE;
457 comment.key = (png_charp)comment_key;
458 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
459 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
460 if (comment.text == NULL)
462 WINE_ERR("out of memory\n");
463 goto done;
465 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
466 comment.text_length = i - 1;
467 ppng_set_text(png_ptr, info_ptr, &comment, 1);
469 ppng_write_info(png_ptr, info_ptr);
470 for (i = 0; i < nHeight; i++)
472 unsigned char *p = row;
473 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
475 if MASK(j,i)
477 *p++ = 0;
478 *p++ = 0;
479 *p++ = 0;
480 *p++ = 0;
482 else
484 #define COLOR(x,y) (b8BitColors ? pXOR[(x) + (nHeight - (y) - 1) * nXORWidthBytes] : (x) % 2 ? pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF : (pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF0) >> 4)
485 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbRed;
486 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbGreen;
487 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbBlue;
488 *p++ = 0xFF;
489 #undef COLOR
492 ppng_write_row(png_ptr, (png_bytep)row);
494 ppng_write_end(png_ptr, info_ptr);
495 ret = TRUE;
497 done:
498 ppng_destroy_write_struct(&png_ptr, &info_ptr);
499 if (pngFile != NULL)
500 fclose(pngFile);
501 HeapFree(GetProcessHeap(), 0, comment.text);
502 HeapFree(GetProcessHeap(), 0, row);
503 return ret;
506 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
508 switch (pIcon->bmiHeader.biBitCount)
510 case 4:
511 case 8:
512 return SavePalettedIconResAsPNG(pIcon, png_filename, commentW);
513 case 24:
514 case 32:
515 return SaveTrueColorIconResAsPNG(pIcon, png_filename, commentW);
516 default:
517 WINE_FIXME("unsupported bpp %d, please report", pIcon->bmiHeader.biBitCount);
518 return FALSE;
521 #endif /* SONAME_LIBPNG */
523 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
525 FILE *fXPMFile;
526 int nHeight;
527 int nXORWidthBytes;
528 int nANDWidthBytes;
529 BOOL b8BitColors;
530 int nColors;
531 const BYTE *pXOR;
532 const BYTE *pAND;
533 BOOL aColorUsed[256] = {0};
534 int nColorsUsed = 0;
535 int i,j;
536 char *comment;
538 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
540 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
541 return FALSE;
544 if (!(fXPMFile = fopen(szXPMFileName, "w")))
546 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
547 return FALSE;
550 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
551 comment = HeapAlloc(GetProcessHeap(), 0, i);
552 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
554 nHeight = pIcon->bmiHeader.biHeight / 2;
555 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
556 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
557 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
558 + ((pIcon->bmiHeader.biWidth % 32) > 0));
559 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
560 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
561 : 1 << pIcon->bmiHeader.biBitCount;
562 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
563 pAND = pXOR + nHeight * nXORWidthBytes;
565 #define COLOR(x,y) (b8BitColors ? pXOR[(x) + (nHeight - (y) - 1) * nXORWidthBytes] : (x) % 2 ? pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF : (pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF0) >> 4)
567 for (i = 0; i < nHeight; i++) {
568 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
569 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
571 aColorUsed[COLOR(j,i)] = TRUE;
572 nColorsUsed++;
577 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
578 goto error;
579 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
580 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
581 goto error;
583 for (i = 0; i < nColors; i++) {
584 if (aColorUsed[i])
585 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
586 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
587 goto error;
589 if (fprintf(fXPMFile, "\" c None\"") <= 0)
590 goto error;
592 for (i = 0; i < nHeight; i++)
594 if (fprintf(fXPMFile, ",\n\"") <= 0)
595 goto error;
596 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
598 if MASK(j,i)
600 if (fprintf(fXPMFile, " ") <= 0)
601 goto error;
603 else
604 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
605 goto error;
607 if (fprintf(fXPMFile, "\"") <= 0)
608 goto error;
610 if (fprintf(fXPMFile, "};\n") <= 0)
611 goto error;
613 #undef MASK
614 #undef COLOR
616 HeapFree(GetProcessHeap(), 0, comment);
617 fclose(fXPMFile);
618 return TRUE;
620 error:
621 HeapFree(GetProcessHeap(), 0, comment);
622 fclose(fXPMFile);
623 unlink( szXPMFileName );
624 return FALSE;
627 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
629 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
631 if (!sEnumRes->nIndex--)
633 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
634 return FALSE;
636 else
637 return TRUE;
640 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
642 HMODULE hModule;
643 HRSRC hResInfo;
644 LPCWSTR lpName = NULL;
645 HGLOBAL hResData;
646 GRPICONDIR *pIconDir;
647 BITMAPINFO *pIcon;
648 ENUMRESSTRUCT sEnumRes;
649 int nMax = 0;
650 int nMaxBits = 0;
651 int i;
652 BOOL ret = FALSE;
654 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
655 if (!hModule)
657 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
658 wine_dbgstr_w(szFileName), GetLastError());
659 return FALSE;
662 if (nIndex < 0)
664 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
665 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
666 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
668 else
670 hResInfo=NULL;
671 sEnumRes.pResInfo = &hResInfo;
672 sEnumRes.nIndex = nIndex;
673 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
674 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
675 sEnumRes.nIndex != -1)
677 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
681 if (hResInfo)
683 if ((hResData = LoadResource(hModule, hResInfo)))
685 if ((pIconDir = LockResource(hResData)))
687 for (i = 0; i < pIconDir->idCount; i++)
689 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
691 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
693 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
694 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
695 nMaxBits = pIconDir->idEntries[i].wBitCount;
701 FreeResource(hResData);
704 else
706 WINE_WARN("found no icon\n");
707 FreeLibrary(hModule);
708 return FALSE;
711 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
713 if ((hResData = LoadResource(hModule, hResInfo)))
715 if ((pIcon = LockResource(hResData)))
717 #ifdef SONAME_LIBPNG
718 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
719 ret = TRUE;
720 else
721 #endif
723 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
724 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
725 ret = TRUE;
729 FreeResource(hResData);
733 FreeLibrary(hModule);
734 return ret;
737 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
739 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
740 !extract_icon16(szFileName, szXPMFileName)*/)
741 return FALSE;
742 return TRUE;
745 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
747 FILE *fICOFile = NULL;
748 ICONDIR iconDir;
749 ICONDIRENTRY *pIconDirEntry = NULL;
750 int nMax = 0, nMaxBits = 0;
751 int nIndex = 0;
752 void *pIcon = NULL;
753 int i;
754 char *filename = NULL;
756 filename = wine_get_unix_file_name(szFileName);
757 if (!(fICOFile = fopen(filename, "r")))
759 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
760 goto error;
763 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
764 (iconDir.idReserved != 0) || (iconDir.idType != 1))
766 WINE_WARN("Invalid ico file format\n");
767 goto error;
770 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
771 goto error;
772 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
773 goto error;
775 for (i = 0; i < iconDir.idCount; i++)
777 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
778 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
779 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
781 nIndex = i;
782 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
783 nMaxBits = pIconDirEntry[i].wBitCount;
786 WINE_TRACE("Selected: %d\n", nIndex);
788 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
789 goto error;
790 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
791 goto error;
792 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
793 goto error;
796 /* Prefer PNG over XPM */
797 #ifdef SONAME_LIBPNG
798 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
799 #endif
801 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
802 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
803 goto error;
806 HeapFree(GetProcessHeap(), 0, pIcon);
807 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
808 fclose(fICOFile);
809 HeapFree(GetProcessHeap(), 0, filename);
810 return 1;
812 error:
813 HeapFree(GetProcessHeap(), 0, pIcon);
814 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
815 if (fICOFile) fclose(fICOFile);
816 HeapFree(GetProcessHeap(), 0, filename);
817 return 0;
820 static int ExtractFromFileType(LPCWSTR szFileName, char *szXPMFileName)
822 int ret = 0;
823 WCHAR *extension;
824 WCHAR *icon = NULL;
825 WCHAR *comma;
826 WCHAR *executable = NULL;
827 int index = 0;
828 char *output_path = NULL;
830 extension = strrchrW(szFileName, '.');
831 if (extension == NULL)
832 goto end;
834 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
835 if (icon)
837 comma = strrchrW(icon, ',');
838 if (comma)
840 *comma = 0;
841 index = atoiW(comma + 1);
843 output_path = extract_icon(icon, index, NULL, FALSE);
844 WINE_TRACE("defaulticon %s -> icon %s\n", wine_dbgstr_w(icon), wine_dbgstr_a(output_path));
846 else
848 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, NULL);
849 if (executable)
850 output_path = extract_icon(executable, 0, NULL, FALSE);
851 WINE_TRACE("executable %s -> icon %s\n", wine_dbgstr_w(executable), wine_dbgstr_a(output_path));
853 if (output_path)
854 ret = (rename(output_path, szXPMFileName) == 0);
856 end:
857 HeapFree(GetProcessHeap(), 0, icon);
858 HeapFree(GetProcessHeap(), 0, executable);
859 HeapFree(GetProcessHeap(), 0, output_path);
860 return ret;
863 static BOOL create_default_icon( const char *filename, const char* comment )
865 FILE *fXPM;
866 unsigned int i;
868 if (!(fXPM = fopen(filename, "w"))) return FALSE;
869 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
870 goto error;
871 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
872 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
873 goto error;
875 if (fprintf( fXPM, "};\n" ) <=0)
876 goto error;
877 fclose( fXPM );
878 return TRUE;
879 error:
880 fclose( fXPM );
881 unlink( filename );
882 return FALSE;
886 static unsigned short crc16(const char* string)
888 unsigned short crc = 0;
889 int i, j, xor_poly;
891 for (i = 0; string[i] != 0; i++)
893 char c = string[i];
894 for (j = 0; j < 8; c >>= 1, j++)
896 xor_poly = (c ^ crc) & 1;
897 crc >>= 1;
898 if (xor_poly)
899 crc ^= 0xa001;
902 return crc;
905 static char *strdupA( const char *str )
907 char *ret;
909 if (!str) return NULL;
910 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
911 return ret;
914 static char* heap_printf(const char *format, ...)
916 va_list args;
917 int size = 4096;
918 char *buffer, *ret;
919 int n;
921 va_start(args, format);
922 while (1)
924 buffer = HeapAlloc(GetProcessHeap(), 0, size);
925 if (buffer == NULL)
926 break;
927 n = vsnprintf(buffer, size, format, args);
928 if (n == -1)
929 size *= 2;
930 else if (n >= size)
931 size = n + 1;
932 else
933 break;
934 HeapFree(GetProcessHeap(), 0, buffer);
936 va_end(args);
937 if (!buffer) return NULL;
938 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
939 if (!ret) ret = buffer;
940 return ret;
943 static void write_xml_text(FILE *file, const char *text)
945 int i;
946 for (i = 0; text[i]; i++)
948 if (text[i] == '&')
949 fputs("&amp;", file);
950 else if (text[i] == '<')
951 fputs("&lt;", file);
952 else if (text[i] == '>')
953 fputs("&gt;", file);
954 else if (text[i] == '\'')
955 fputs("&apos;", file);
956 else if (text[i] == '"')
957 fputs("&quot;", file);
958 else
959 fputc(text[i], file);
963 static BOOL create_directories(char *directory)
965 BOOL ret = TRUE;
966 int i;
968 for (i = 0; directory[i]; i++)
970 if (i > 0 && directory[i] == '/')
972 directory[i] = 0;
973 mkdir(directory, 0777);
974 directory[i] = '/';
977 if (mkdir(directory, 0777) && errno != EEXIST)
978 ret = FALSE;
980 return ret;
983 static char* wchars_to_utf8_chars(LPCWSTR string)
985 char *ret;
986 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
987 ret = HeapAlloc(GetProcessHeap(), 0, size);
988 if (ret)
989 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
990 return ret;
993 static char* wchars_to_unix_chars(LPCWSTR string)
995 char *ret;
996 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
997 ret = HeapAlloc(GetProcessHeap(), 0, size);
998 if (ret)
999 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
1000 return ret;
1003 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
1005 WCHAR *ret;
1006 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
1007 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1008 if (ret)
1009 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
1010 return ret;
1013 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1014 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
1016 unsigned short crc;
1017 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
1018 char* s;
1019 int n;
1021 /* Where should we save the icon? */
1022 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
1023 iconsdir = heap_printf("%s/icons", xdg_data_dir);
1024 if (iconsdir)
1026 if (mkdir(iconsdir, 0777) && errno != EEXIST)
1028 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
1029 goto end;
1032 else
1034 WINE_TRACE("no icon created\n");
1035 return NULL;
1038 /* Determine the icon base name */
1039 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
1040 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
1041 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
1042 s=ico_name=ico_path;
1043 while (*s!='\0') {
1044 if (*s=='/' || *s=='\\') {
1045 *s='\\';
1046 ico_name=s;
1047 } else {
1048 *s=tolower(*s);
1050 s++;
1052 if (*ico_name=='\\') *ico_name++='\0';
1053 s=strrchr(ico_name,'.');
1054 if (s) *s='\0';
1056 /* Compute the source-path hash */
1057 crc=crc16(ico_path);
1059 /* Try to treat the source file as an exe */
1060 if (destFilename)
1061 xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
1062 else
1063 xpm_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
1064 if (xpm_path == NULL)
1066 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
1067 return NULL;
1070 if (ExtractFromEXEDLL( path, index, xpm_path ))
1071 goto end;
1073 /* Must be something else, ignore the index in that case */
1074 if (destFilename)
1075 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
1076 else
1077 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
1078 if (ExtractFromICO( path, xpm_path))
1079 goto end;
1080 if (ExtractFromFileType( path, xpm_path ))
1081 goto end;
1082 if (!bWait)
1084 if (destFilename)
1085 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
1086 else
1087 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
1088 if (create_default_icon( xpm_path, ico_path ))
1089 goto end;
1092 HeapFree( GetProcessHeap(), 0, xpm_path );
1093 xpm_path=NULL;
1095 end:
1096 HeapFree(GetProcessHeap(), 0, iconsdir);
1097 HeapFree(GetProcessHeap(), 0, ico_path);
1098 return xpm_path;
1101 static HKEY open_menus_reg_key(void)
1103 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1104 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1105 HKEY assocKey;
1106 DWORD ret;
1107 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1108 if (ret == ERROR_SUCCESS)
1109 return assocKey;
1110 SetLastError(ret);
1111 return NULL;
1114 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1116 WCHAR *unix_fileW;
1117 WCHAR *windows_fileW;
1118 INT size;
1119 DWORD ret;
1121 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1122 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1123 if (unix_fileW)
1125 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1126 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1127 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1128 if (windows_fileW)
1130 HKEY hkey;
1131 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1132 hkey = open_menus_reg_key();
1133 if (hkey)
1135 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1136 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1137 RegCloseKey(hkey);
1139 else
1140 ret = GetLastError();
1141 HeapFree(GetProcessHeap(), 0, windows_fileW);
1143 else
1144 ret = ERROR_NOT_ENOUGH_MEMORY;
1145 HeapFree(GetProcessHeap(), 0, unix_fileW);
1147 else
1148 ret = ERROR_NOT_ENOUGH_MEMORY;
1149 return ret;
1152 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1153 const char *path, const char *args, const char *descr,
1154 const char *workdir, const char *icon)
1156 FILE *file;
1158 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1159 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1160 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1162 file = fopen(location, "w");
1163 if (file == NULL)
1164 return FALSE;
1166 fprintf(file, "[Desktop Entry]\n");
1167 fprintf(file, "Name=%s\n", linkname);
1168 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1169 wine_get_config_dir(), path, args);
1170 fprintf(file, "Type=Application\n");
1171 fprintf(file, "StartupNotify=true\n");
1172 if (descr && lstrlenA(descr))
1173 fprintf(file, "Comment=%s\n", descr);
1174 if (workdir && lstrlenA(workdir))
1175 fprintf(file, "Path=%s\n", workdir);
1176 if (icon && lstrlenA(icon))
1177 fprintf(file, "Icon=%s\n", icon);
1179 fclose(file);
1181 if (unix_link)
1183 DWORD ret = register_menus_entry(location, unix_link);
1184 if (ret != ERROR_SUCCESS)
1185 return FALSE;
1188 return TRUE;
1191 static BOOL write_directory_entry(const char *directory, const char *location)
1193 FILE *file;
1195 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1197 file = fopen(location, "w");
1198 if (file == NULL)
1199 return FALSE;
1201 fprintf(file, "[Desktop Entry]\n");
1202 fprintf(file, "Type=Directory\n");
1203 if (strcmp(directory, "wine") == 0)
1205 fprintf(file, "Name=Wine\n");
1206 fprintf(file, "Icon=wine\n");
1208 else
1210 fprintf(file, "Name=%s\n", directory);
1211 fprintf(file, "Icon=folder\n");
1214 fclose(file);
1215 return TRUE;
1218 static BOOL write_menu_file(const char *unix_link, const char *filename)
1220 char *tempfilename;
1221 FILE *tempfile = NULL;
1222 char *lastEntry;
1223 char *name = NULL;
1224 char *menuPath = NULL;
1225 int i;
1226 int count = 0;
1227 BOOL ret = FALSE;
1229 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1231 while (1)
1233 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1234 if (tempfilename)
1236 int tempfd = mkstemps(tempfilename, 0);
1237 if (tempfd >= 0)
1239 tempfile = fdopen(tempfd, "w");
1240 if (tempfile)
1241 break;
1242 close(tempfd);
1243 goto end;
1245 else if (errno == EEXIST)
1247 HeapFree(GetProcessHeap(), 0, tempfilename);
1248 continue;
1250 HeapFree(GetProcessHeap(), 0, tempfilename);
1252 return FALSE;
1255 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1256 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1257 fprintf(tempfile, "<Menu>\n");
1258 fprintf(tempfile, " <Name>Applications</Name>\n");
1260 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1261 if (name == NULL) goto end;
1262 lastEntry = name;
1263 for (i = 0; filename[i]; i++)
1265 name[i] = filename[i];
1266 if (filename[i] == '/')
1268 char *dir_file_name;
1269 struct stat st;
1270 name[i] = 0;
1271 fprintf(tempfile, " <Menu>\n");
1272 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1273 write_xml_text(tempfile, name);
1274 fprintf(tempfile, "</Name>\n");
1275 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1276 write_xml_text(tempfile, name);
1277 fprintf(tempfile, ".directory</Directory>\n");
1278 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1279 xdg_data_dir, count ? "" : "wine-", name);
1280 if (dir_file_name)
1282 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1283 write_directory_entry(lastEntry, dir_file_name);
1284 HeapFree(GetProcessHeap(), 0, dir_file_name);
1286 name[i] = '-';
1287 lastEntry = &name[i+1];
1288 ++count;
1291 name[i] = 0;
1293 fprintf(tempfile, " <Include>\n");
1294 fprintf(tempfile, " <Filename>");
1295 write_xml_text(tempfile, name);
1296 fprintf(tempfile, "</Filename>\n");
1297 fprintf(tempfile, " </Include>\n");
1298 for (i = 0; i < count; i++)
1299 fprintf(tempfile, " </Menu>\n");
1300 fprintf(tempfile, "</Menu>\n");
1302 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1303 if (menuPath == NULL) goto end;
1304 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1305 ret = TRUE;
1307 end:
1308 if (tempfile)
1309 fclose(tempfile);
1310 if (ret)
1311 ret = (rename(tempfilename, menuPath) == 0);
1312 if (!ret && tempfilename)
1313 remove(tempfilename);
1314 HeapFree(GetProcessHeap(), 0, tempfilename);
1315 if (ret)
1316 register_menus_entry(menuPath, unix_link);
1317 HeapFree(GetProcessHeap(), 0, name);
1318 HeapFree(GetProcessHeap(), 0, menuPath);
1319 return ret;
1322 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1323 const char *descr, const char *workdir, const char *icon)
1325 const char *linkname;
1326 char *desktopPath = NULL;
1327 char *desktopDir;
1328 char *filename = NULL;
1329 BOOL ret = TRUE;
1331 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1332 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1333 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1335 linkname = strrchr(link, '/');
1336 if (linkname == NULL)
1337 linkname = link;
1338 else
1339 ++linkname;
1341 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1342 if (!desktopPath)
1344 WINE_WARN("out of memory creating menu entry\n");
1345 ret = FALSE;
1346 goto end;
1348 desktopDir = strrchr(desktopPath, '/');
1349 *desktopDir = 0;
1350 if (!create_directories(desktopPath))
1352 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1353 ret = FALSE;
1354 goto end;
1356 *desktopDir = '/';
1357 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1359 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1360 ret = FALSE;
1361 goto end;
1364 filename = heap_printf("wine/%s.desktop", link);
1365 if (!filename || !write_menu_file(unix_link, filename))
1367 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1368 ret = FALSE;
1371 end:
1372 HeapFree(GetProcessHeap(), 0, desktopPath);
1373 HeapFree(GetProcessHeap(), 0, filename);
1374 return ret;
1377 /* This escapes reserved characters in .desktop files' Exec keys. */
1378 static LPSTR escape(LPCWSTR arg)
1380 int i, j;
1381 WCHAR *escaped_string;
1382 char *utf8_string;
1384 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1385 if (escaped_string == NULL) return NULL;
1386 for (i = j = 0; arg[i]; i++)
1388 switch (arg[i])
1390 case '\\':
1391 escaped_string[j++] = '\\';
1392 escaped_string[j++] = '\\';
1393 escaped_string[j++] = '\\';
1394 escaped_string[j++] = '\\';
1395 break;
1396 case ' ':
1397 case '\t':
1398 case '\n':
1399 case '"':
1400 case '\'':
1401 case '>':
1402 case '<':
1403 case '~':
1404 case '|':
1405 case '&':
1406 case ';':
1407 case '$':
1408 case '*':
1409 case '?':
1410 case '#':
1411 case '(':
1412 case ')':
1413 case '`':
1414 escaped_string[j++] = '\\';
1415 escaped_string[j++] = '\\';
1416 /* fall through */
1417 default:
1418 escaped_string[j++] = arg[i];
1419 break;
1422 escaped_string[j] = 0;
1424 utf8_string = wchars_to_utf8_chars(escaped_string);
1425 if (utf8_string == NULL)
1427 WINE_ERR("out of memory\n");
1428 goto end;
1431 end:
1432 HeapFree(GetProcessHeap(), 0, escaped_string);
1433 return utf8_string;
1436 /* Return a heap-allocated copy of the unix format difference between the two
1437 * Windows-format paths.
1438 * locn is the owning location
1439 * link is within locn
1441 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1443 char *unix_locn, *unix_link;
1444 char *relative = NULL;
1446 unix_locn = wine_get_unix_file_name(locn);
1447 unix_link = wine_get_unix_file_name(link);
1448 if (unix_locn && unix_link)
1450 size_t len_unix_locn, len_unix_link;
1451 len_unix_locn = strlen (unix_locn);
1452 len_unix_link = strlen (unix_link);
1453 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1455 size_t len_rel;
1456 char *p = strrchr (unix_link + len_unix_locn, '/');
1457 p = strrchr (p, '.');
1458 if (p)
1460 *p = '\0';
1461 len_unix_link = p - unix_link;
1463 len_rel = len_unix_link - len_unix_locn;
1464 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1465 if (relative)
1467 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1471 if (!relative)
1472 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1473 HeapFree(GetProcessHeap(), 0, unix_locn);
1474 HeapFree(GetProcessHeap(), 0, unix_link);
1475 return relative;
1478 /***********************************************************************
1480 * GetLinkLocation
1482 * returns TRUE if successful
1483 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1484 * *relative will contain the address of a heap-allocated copy of the portion
1485 * of the filename that is within the specified location, in unix form
1487 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1489 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1490 DWORD len, i, r, filelen;
1491 const DWORD locations[] = {
1492 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1493 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1494 CSIDL_COMMON_STARTMENU };
1496 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1497 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1498 if (filelen==0 || filelen>MAX_PATH)
1499 return FALSE;
1501 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1503 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1504 * expand or our hardcoded list won't match.
1506 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1507 if (filelen==0 || filelen>MAX_PATH)
1508 return FALSE;
1510 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1512 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1514 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1515 continue;
1517 len = lstrlenW(buffer);
1518 if (len >= MAX_PATH)
1519 continue; /* We've just trashed memory! Hopefully we are OK */
1521 if (len > filelen || filename[len]!='\\')
1522 continue;
1523 /* do a lstrcmpinW */
1524 filename[len] = 0;
1525 r = lstrcmpiW( filename, buffer );
1526 filename[len] = '\\';
1527 if ( r )
1528 continue;
1530 /* return the remainder of the string and link type */
1531 *loc = locations[i];
1532 *relative = relative_path (filename, buffer);
1533 return (*relative != NULL);
1536 return FALSE;
1539 /* gets the target path directly or through MSI */
1540 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1541 LPWSTR szArgs, DWORD argsSize)
1543 IShellLinkDataList *dl = NULL;
1544 EXP_DARWIN_LINK *dar = NULL;
1545 HRESULT hr;
1547 szPath[0] = 0;
1548 szArgs[0] = 0;
1550 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1551 if (hr == S_OK && szPath[0])
1553 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1554 return hr;
1557 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1558 if (FAILED(hr))
1559 return hr;
1561 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1562 if (SUCCEEDED(hr))
1564 WCHAR* szCmdline;
1565 DWORD cmdSize;
1567 cmdSize=0;
1568 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1569 if (hr == ERROR_SUCCESS)
1571 cmdSize++;
1572 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1573 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1574 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1575 if (hr == ERROR_SUCCESS)
1577 WCHAR *s, *d;
1578 int bcount, in_quotes;
1580 /* Extract the application path */
1581 bcount=0;
1582 in_quotes=0;
1583 s=szCmdline;
1584 d=szPath;
1585 while (*s)
1587 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1589 /* skip the remaining spaces */
1590 do {
1591 s++;
1592 } while (*s==0x0009 || *s==0x0020);
1593 break;
1595 else if (*s==0x005c)
1597 /* '\\' */
1598 *d++=*s++;
1599 bcount++;
1601 else if (*s==0x0022)
1603 /* '"' */
1604 if ((bcount & 1)==0)
1606 /* Preceded by an even number of '\', this is
1607 * half that number of '\', plus a quote which
1608 * we erase.
1610 d-=bcount/2;
1611 in_quotes=!in_quotes;
1612 s++;
1614 else
1616 /* Preceded by an odd number of '\', this is
1617 * half that number of '\' followed by a '"'
1619 d=d-bcount/2-1;
1620 *d++='"';
1621 s++;
1623 bcount=0;
1625 else
1627 /* a regular character */
1628 *d++=*s++;
1629 bcount=0;
1631 if ((d-szPath) == pathSize)
1633 /* Keep processing the path till we get to the
1634 * arguments, but 'stand still'
1636 d--;
1639 /* Close the application path */
1640 *d=0;
1642 lstrcpynW(szArgs, s, argsSize);
1644 HeapFree( GetProcessHeap(), 0, szCmdline );
1646 LocalFree( dar );
1649 IShellLinkDataList_Release( dl );
1650 return hr;
1653 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1655 HRESULT hr;
1656 WCHAR *value = NULL;
1657 DWORD size = 0;
1658 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1659 if (SUCCEEDED(hr))
1661 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1662 if (value)
1664 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1665 if (FAILED(hr))
1667 HeapFree(GetProcessHeap(), 0, value);
1668 value = NULL;
1672 return value;
1675 static char *slashes_to_minuses(const char *string)
1677 int i;
1678 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1679 if (ret)
1681 for (i = 0; string[i]; i++)
1683 if (string[i] == '/')
1684 ret[i] = '-';
1685 else
1686 ret[i] = string[i];
1688 ret[i] = 0;
1689 return ret;
1691 return NULL;
1694 static BOOL next_line(FILE *file, char **line, int *size)
1696 int pos = 0;
1697 char *cr;
1698 if (*line == NULL)
1700 *size = 4096;
1701 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1703 while (*line != NULL)
1705 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1707 HeapFree(GetProcessHeap(), 0, *line);
1708 *line = NULL;
1709 if (feof(file))
1710 return TRUE;
1711 return FALSE;
1713 pos = strlen(*line);
1714 cr = strchr(*line, '\n');
1715 if (cr == NULL)
1717 char *line2;
1718 (*size) *= 2;
1719 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1720 if (line2)
1721 *line = line2;
1722 else
1724 HeapFree(GetProcessHeap(), 0, *line);
1725 *line = NULL;
1728 else
1730 *cr = 0;
1731 return TRUE;
1734 return FALSE;
1737 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1739 char *globs_filename = NULL;
1740 BOOL ret = TRUE;
1741 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1742 if (globs_filename)
1744 FILE *globs_file = fopen(globs_filename, "r");
1745 if (globs_file) /* doesn't have to exist */
1747 char *line = NULL;
1748 int size = 0;
1749 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1751 char *pos;
1752 struct xdg_mime_type *mime_type_entry = NULL;
1753 if (line[0] != '#' && (pos = strchr(line, ':')))
1755 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1756 if (mime_type_entry)
1758 *pos = 0;
1759 mime_type_entry->mimeType = strdupA(line);
1760 mime_type_entry->glob = strdupA(pos + 1);
1761 if (mime_type_entry->mimeType && mime_type_entry->glob)
1762 list_add_tail(mime_types, &mime_type_entry->entry);
1763 else
1765 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1766 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1767 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1768 ret = FALSE;
1771 else
1772 ret = FALSE;
1775 HeapFree(GetProcessHeap(), 0, line);
1776 fclose(globs_file);
1778 HeapFree(GetProcessHeap(), 0, globs_filename);
1780 else
1781 ret = FALSE;
1782 return ret;
1785 static void free_native_mime_types(struct list *native_mime_types)
1787 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1789 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1791 list_remove(&mime_type_entry->entry);
1792 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1793 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1794 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1796 HeapFree(GetProcessHeap(), 0, native_mime_types);
1799 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1801 char *xdg_data_dirs;
1802 BOOL ret;
1804 *mime_types = NULL;
1806 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1807 if (xdg_data_dirs == NULL)
1808 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1809 else
1810 xdg_data_dirs = strdupA(xdg_data_dirs);
1812 if (xdg_data_dirs)
1814 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1815 if (*mime_types)
1817 const char *begin;
1818 char *end;
1820 list_init(*mime_types);
1821 ret = add_mimes(xdg_data_home, *mime_types);
1822 if (ret)
1824 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1826 *end = '\0';
1827 ret = add_mimes(begin, *mime_types);
1828 *end = ':';
1829 if (!ret)
1830 break;
1832 if (ret)
1833 ret = add_mimes(begin, *mime_types);
1836 else
1837 ret = FALSE;
1838 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1840 else
1841 ret = FALSE;
1842 if (!ret && *mime_types)
1844 free_native_mime_types(*mime_types);
1845 *mime_types = NULL;
1847 return ret;
1850 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1851 char **match)
1853 #ifdef HAVE_FNMATCH
1854 struct xdg_mime_type *mime_type_entry;
1855 int matchLength = 0;
1857 *match = NULL;
1859 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1861 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1863 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1865 *match = mime_type_entry->mimeType;
1866 matchLength = strlen(mime_type_entry->glob);
1871 if (*match != NULL)
1873 *match = strdupA(*match);
1874 if (*match == NULL)
1875 return FALSE;
1877 #else
1878 *match = NULL;
1879 #endif
1880 return TRUE;
1883 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1884 const char *extensionA,
1885 LPCWSTR extensionW,
1886 char **mime_type)
1888 WCHAR *lower_extensionW;
1889 INT len;
1890 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1891 if (ret == FALSE || *mime_type != NULL)
1892 return ret;
1893 len = strlenW(extensionW);
1894 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1895 if (lower_extensionW)
1897 char *lower_extensionA;
1898 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1899 strlwrW(lower_extensionW);
1900 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1901 if (lower_extensionA)
1903 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1904 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1906 else
1908 ret = FALSE;
1909 WINE_FIXME("out of memory\n");
1911 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1913 else
1915 ret = FALSE;
1916 WINE_FIXME("out of memory\n");
1918 return ret;
1921 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1923 DWORD size;
1924 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1926 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1927 if (ret)
1929 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1930 return ret;
1932 HeapFree(GetProcessHeap(), 0, ret);
1934 return NULL;
1937 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
1939 WCHAR *valW = reg_get_valW(key, subkey, name);
1940 if (valW)
1942 char *val = wchars_to_utf8_chars(valW);
1943 HeapFree(GetProcessHeap(), 0, valW);
1944 return val;
1946 return NULL;
1949 static HKEY open_associations_reg_key(void)
1951 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1952 '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};
1953 HKEY assocKey;
1954 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1955 return assocKey;
1956 return NULL;
1959 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1961 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1962 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1963 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1964 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1965 HKEY assocKey;
1966 BOOL ret;
1968 if ((assocKey = open_associations_reg_key()))
1970 CHAR *valueA;
1971 WCHAR *value;
1973 ret = FALSE;
1975 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
1976 if (!valueA || lstrcmpA(valueA, mimeType))
1977 ret = TRUE;
1978 HeapFree(GetProcessHeap(), 0, valueA);
1980 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1981 if (!value || strcmpW(value, progId))
1982 ret = TRUE;
1983 HeapFree(GetProcessHeap(), 0, value);
1985 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
1986 if (!valueA || lstrcmpA(valueA, appName))
1987 ret = TRUE;
1988 HeapFree(GetProcessHeap(), 0, valueA);
1990 value = reg_get_valW(assocKey, extensionW, DocNameW);
1991 if (docName && (!value || strcmpW(value, docName)))
1992 ret = TRUE;
1993 HeapFree(GetProcessHeap(), 0, value);
1995 RegCloseKey(assocKey);
1997 else
1999 WINE_ERR("error opening associations registry key\n");
2000 ret = FALSE;
2002 return ret;
2005 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
2007 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2008 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
2009 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2010 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2011 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2012 HKEY assocKey = NULL;
2013 HKEY subkey = NULL;
2014 WCHAR *mimeTypeW = NULL;
2015 WCHAR *appNameW = NULL;
2016 WCHAR *desktopFileW = NULL;
2018 assocKey = open_associations_reg_key();
2019 if (assocKey == NULL)
2021 WINE_ERR("could not open file associations key\n");
2022 goto done;
2025 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2027 WINE_ERR("could not create extension subkey\n");
2028 goto done;
2031 mimeTypeW = utf8_chars_to_wchars(mimeType);
2032 if (mimeTypeW == NULL)
2034 WINE_ERR("out of memory\n");
2035 goto done;
2038 appNameW = utf8_chars_to_wchars(appName);
2039 if (appNameW == NULL)
2041 WINE_ERR("out of memory\n");
2042 goto done;
2045 desktopFileW = utf8_chars_to_wchars(desktopFile);
2046 if (desktopFileW == NULL)
2048 WINE_ERR("out of memory\n");
2049 goto done;
2052 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2053 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2054 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2055 if (docName)
2056 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
2057 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2059 done:
2060 RegCloseKey(assocKey);
2061 RegCloseKey(subkey);
2062 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2063 HeapFree(GetProcessHeap(), 0, appNameW);
2064 HeapFree(GetProcessHeap(), 0, desktopFileW);
2067 static BOOL cleanup_associations(void)
2069 static const WCHAR openW[] = {'o','p','e','n',0};
2070 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2071 HKEY assocKey;
2072 BOOL hasChanged = FALSE;
2073 if ((assocKey = open_associations_reg_key()))
2075 int i;
2076 BOOL done = FALSE;
2077 for (i = 0; !done; i++)
2079 WCHAR *extensionW = NULL;
2080 DWORD size = 1024;
2081 LSTATUS ret;
2085 HeapFree(GetProcessHeap(), 0, extensionW);
2086 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2087 if (extensionW == NULL)
2089 WINE_ERR("out of memory\n");
2090 ret = ERROR_OUTOFMEMORY;
2091 break;
2093 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2094 size *= 2;
2095 } while (ret == ERROR_MORE_DATA);
2097 if (ret == ERROR_SUCCESS)
2099 WCHAR *command;
2100 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2101 if (command == NULL)
2103 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2104 if (desktopFile)
2106 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2107 remove(desktopFile);
2109 RegDeleteKeyW(assocKey, extensionW);
2110 hasChanged = TRUE;
2111 HeapFree(GetProcessHeap(), 0, desktopFile);
2113 HeapFree(GetProcessHeap(), 0, command);
2115 else
2117 if (ret != ERROR_NO_MORE_ITEMS)
2118 WINE_ERR("error %d while reading registry\n", ret);
2119 done = TRUE;
2121 HeapFree(GetProcessHeap(), 0, extensionW);
2123 RegCloseKey(assocKey);
2125 else
2126 WINE_ERR("could not open file associations key\n");
2127 return hasChanged;
2130 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2131 const char *mime_type, const char *comment)
2133 BOOL ret = FALSE;
2134 char *filename;
2136 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2137 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2139 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2140 if (filename)
2142 FILE *packageFile = fopen(filename, "w");
2143 if (packageFile)
2145 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2146 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2147 fprintf(packageFile, " <mime-type type=\"");
2148 write_xml_text(packageFile, mime_type);
2149 fprintf(packageFile, "\">\n");
2150 fprintf(packageFile, " <glob pattern=\"*");
2151 write_xml_text(packageFile, dot_extension);
2152 fprintf(packageFile, "\"/>\n");
2153 if (comment)
2155 fprintf(packageFile, " <comment>");
2156 write_xml_text(packageFile, comment);
2157 fprintf(packageFile, "</comment>\n");
2159 fprintf(packageFile, " </mime-type>\n");
2160 fprintf(packageFile, "</mime-info>\n");
2161 ret = TRUE;
2162 fclose(packageFile);
2164 else
2165 WINE_ERR("error writing file %s\n", filename);
2166 HeapFree(GetProcessHeap(), 0, filename);
2168 else
2169 WINE_ERR("out of memory\n");
2170 return ret;
2173 static BOOL is_extension_blacklisted(LPCWSTR extension)
2175 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2176 static const WCHAR comW[] = {'.','c','o','m',0};
2177 static const WCHAR exeW[] = {'.','e','x','e',0};
2178 static const WCHAR msiW[] = {'.','m','s','i',0};
2180 if (!strcmpiW(extension, comW) ||
2181 !strcmpiW(extension, exeW) ||
2182 !strcmpiW(extension, msiW))
2183 return TRUE;
2184 return FALSE;
2187 static const char* get_special_mime_type(LPCWSTR extension)
2189 static const WCHAR lnkW[] = {'.','l','n','k',0};
2190 if (!strcmpiW(extension, lnkW))
2191 return "application/x-ms-shortcut";
2192 return NULL;
2195 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2196 const char *friendlyAppName, const char *mimeType,
2197 const char *progId)
2199 BOOL ret = FALSE;
2200 FILE *desktop;
2202 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
2203 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2204 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
2206 desktop = fopen(desktopPath, "w");
2207 if (desktop)
2209 fprintf(desktop, "[Desktop Entry]\n");
2210 fprintf(desktop, "Type=Application\n");
2211 fprintf(desktop, "Name=%s\n", friendlyAppName);
2212 fprintf(desktop, "MimeType=%s\n", mimeType);
2213 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
2214 fprintf(desktop, "NoDisplay=true\n");
2215 fprintf(desktop, "StartupNotify=true\n");
2216 ret = TRUE;
2217 fclose(desktop);
2219 else
2220 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2221 return ret;
2224 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2226 static const WCHAR openW[] = {'o','p','e','n',0};
2227 struct list *nativeMimeTypes = NULL;
2228 LSTATUS ret = 0;
2229 int i;
2230 BOOL hasChanged = FALSE;
2232 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2234 WINE_ERR("could not build native MIME types\n");
2235 return FALSE;
2238 for (i = 0; ; i++)
2240 WCHAR *extensionW = NULL;
2241 DWORD size = 1024;
2245 HeapFree(GetProcessHeap(), 0, extensionW);
2246 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2247 if (extensionW == NULL)
2249 WINE_ERR("out of memory\n");
2250 ret = ERROR_OUTOFMEMORY;
2251 break;
2253 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2254 size *= 2;
2255 } while (ret == ERROR_MORE_DATA);
2257 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2259 char *extensionA = NULL;
2260 WCHAR *commandW = NULL;
2261 WCHAR *friendlyDocNameW = NULL;
2262 char *friendlyDocNameA = NULL;
2263 WCHAR *iconW = NULL;
2264 char *iconA = NULL;
2265 WCHAR *contentTypeW = NULL;
2266 char *mimeTypeA = NULL;
2267 WCHAR *friendlyAppNameW = NULL;
2268 char *friendlyAppNameA = NULL;
2269 WCHAR *progIdW = NULL;
2270 char *progIdA = NULL;
2272 extensionA = wchars_to_utf8_chars(extensionW);
2273 if (extensionA == NULL)
2275 WINE_ERR("out of memory\n");
2276 goto end;
2279 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2280 if (friendlyDocNameW)
2282 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2283 if (friendlyDocNameA == NULL)
2285 WINE_ERR("out of memory\n");
2286 goto end;
2290 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2292 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2293 if (contentTypeW)
2294 strlwrW(contentTypeW);
2296 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2297 goto end;
2299 if (mimeTypeA == NULL)
2301 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2302 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2303 else if ((get_special_mime_type(extensionW)))
2304 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2305 else
2306 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2308 if (mimeTypeA != NULL)
2310 /* Gnome seems to ignore the <icon> tag in MIME packages,
2311 * and the default name is more intuitive anyway.
2313 if (iconW)
2315 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2316 if (flattened_mime)
2318 int index = 0;
2319 WCHAR *comma = strrchrW(iconW, ',');
2320 if (comma)
2322 *comma = 0;
2323 index = atoiW(comma + 1);
2325 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2326 HeapFree(GetProcessHeap(), 0, flattened_mime);
2330 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2331 hasChanged = TRUE;
2333 else
2335 WINE_FIXME("out of memory\n");
2336 goto end;
2340 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2341 if (commandW == NULL)
2342 /* no command => no application is associated */
2343 goto end;
2345 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2346 if (friendlyAppNameW)
2348 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2349 if (friendlyAppNameA == NULL)
2351 WINE_ERR("out of memory\n");
2352 goto end;
2355 else
2357 friendlyAppNameA = heap_printf("A Wine application");
2358 if (friendlyAppNameA == NULL)
2360 WINE_ERR("out of memory\n");
2361 goto end;
2365 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2366 if (progIdW)
2368 progIdA = escape(progIdW);
2369 if (progIdA == NULL)
2371 WINE_ERR("out of memory\n");
2372 goto end;
2375 else
2376 goto end; /* no progID => not a file type association */
2378 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2380 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2381 if (desktopPath)
2383 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2385 hasChanged = TRUE;
2386 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2388 HeapFree(GetProcessHeap(), 0, desktopPath);
2392 end:
2393 HeapFree(GetProcessHeap(), 0, extensionA);
2394 HeapFree(GetProcessHeap(), 0, commandW);
2395 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2396 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2397 HeapFree(GetProcessHeap(), 0, iconW);
2398 HeapFree(GetProcessHeap(), 0, iconA);
2399 HeapFree(GetProcessHeap(), 0, contentTypeW);
2400 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2401 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2402 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2403 HeapFree(GetProcessHeap(), 0, progIdW);
2404 HeapFree(GetProcessHeap(), 0, progIdA);
2406 HeapFree(GetProcessHeap(), 0, extensionW);
2407 if (ret != ERROR_SUCCESS)
2408 break;
2411 free_native_mime_types(nativeMimeTypes);
2412 return hasChanged;
2415 static char *get_start_exe_path(void)
2417 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2418 '\\','s','t','a','r','t','.','e','x','e',0};
2419 WCHAR start_path[MAX_PATH];
2420 GetWindowsDirectoryW(start_path, MAX_PATH);
2421 lstrcatW(start_path, startW);
2422 return escape(start_path);
2425 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2427 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2428 '\\','s','t','a','r','t','.','e','x','e',0};
2429 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2430 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2431 WCHAR szTmp[INFOTIPSIZE];
2432 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2433 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2434 int iIconId = 0, r = -1;
2435 DWORD csidl = -1;
2436 HANDLE hsem = NULL;
2437 char *unix_link = NULL;
2438 char *start_path = NULL;
2440 if ( !link )
2442 WINE_ERR("Link name is null\n");
2443 return FALSE;
2446 if( !GetLinkLocation( link, &csidl, &link_name ) )
2448 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2449 return TRUE;
2451 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2453 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2454 return TRUE;
2456 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2458 szTmp[0] = 0;
2459 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2460 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2461 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2463 szTmp[0] = 0;
2464 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2465 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2466 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2468 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2469 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2470 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2471 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2473 szTmp[0] = 0;
2474 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2475 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2476 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2478 if( !szPath[0] )
2480 LPITEMIDLIST pidl = NULL;
2481 IShellLinkW_GetIDList( sl, &pidl );
2482 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2483 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2486 /* extract the icon */
2487 if( szIconPath[0] )
2488 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2489 else
2490 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2492 /* fail - try once again after parent process exit */
2493 if( !icon_name )
2495 if (bWait)
2497 WINE_WARN("Unable to extract icon, deferring.\n");
2498 goto cleanup;
2500 WINE_ERR("failed to extract icon from %s\n",
2501 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2504 unix_link = wine_get_unix_file_name(link);
2505 if (unix_link == NULL)
2507 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2508 goto cleanup;
2511 /* check the path */
2512 if( szPath[0] )
2514 static const WCHAR exeW[] = {'.','e','x','e',0};
2515 WCHAR *p;
2517 /* check for .exe extension */
2518 if (!(p = strrchrW( szPath, '.' )) ||
2519 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2520 lstrcmpiW( p, exeW ))
2522 /* Not .exe - use 'start.exe' to launch this file */
2523 p = szArgs + lstrlenW(szPath) + 2;
2524 if (szArgs[0])
2526 p[0] = ' ';
2527 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2528 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2530 else
2531 p[0] = 0;
2533 szArgs[0] = '"';
2534 lstrcpyW(szArgs + 1, szPath);
2535 p[-1] = '"';
2537 GetWindowsDirectoryW(szPath, MAX_PATH);
2538 lstrcatW(szPath, startW);
2541 /* convert app working dir */
2542 if (szWorkDir[0])
2543 work_dir = wine_get_unix_file_name( szWorkDir );
2545 else
2547 /* if there's no path... try run the link itself */
2548 lstrcpynW(szArgs, link, MAX_PATH);
2549 GetWindowsDirectoryW(szPath, MAX_PATH);
2550 lstrcatW(szPath, startW);
2553 /* escape the path and parameters */
2554 escaped_path = escape(szPath);
2555 escaped_args = escape(szArgs);
2556 description = wchars_to_utf8_chars(szDescription);
2557 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2559 WINE_ERR("out of memory allocating/escaping parameters\n");
2560 goto cleanup;
2563 start_path = get_start_exe_path();
2564 if (start_path == NULL)
2566 WINE_ERR("out of memory\n");
2567 goto cleanup;
2570 /* building multiple menus concurrently has race conditions */
2571 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2572 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2574 WINE_ERR("failed wait for semaphore\n");
2575 goto cleanup;
2578 if (in_desktop_dir(csidl))
2580 char *location;
2581 const char *lastEntry;
2582 lastEntry = strrchr(link_name, '/');
2583 if (lastEntry == NULL)
2584 lastEntry = link_name;
2585 else
2586 ++lastEntry;
2587 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2588 if (location)
2590 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2591 if (r == 0)
2592 chmod(location, 0755);
2593 HeapFree(GetProcessHeap(), 0, location);
2596 else
2598 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2599 if (unix_linkW)
2601 char *escaped_lnk = escape(unix_linkW);
2602 if (escaped_lnk)
2604 char *menuarg = heap_printf("/Unix %s", escaped_lnk);
2605 if (menuarg)
2607 r = !write_menu_entry(unix_link, link_name, start_path, menuarg, description, work_dir, icon_name);
2608 HeapFree(GetProcessHeap(), 0, menuarg);
2610 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2612 HeapFree(GetProcessHeap(), 0, unix_linkW);
2616 ReleaseSemaphore( hsem, 1, NULL );
2618 cleanup:
2619 if (hsem) CloseHandle( hsem );
2620 HeapFree( GetProcessHeap(), 0, icon_name );
2621 HeapFree( GetProcessHeap(), 0, work_dir );
2622 HeapFree( GetProcessHeap(), 0, link_name );
2623 HeapFree( GetProcessHeap(), 0, escaped_args );
2624 HeapFree( GetProcessHeap(), 0, escaped_path );
2625 HeapFree( GetProcessHeap(), 0, description );
2626 HeapFree( GetProcessHeap(), 0, unix_link );
2627 HeapFree( GetProcessHeap(), 0, start_path );
2629 if (r && !bWait)
2630 WINE_ERR("failed to build the menu\n" );
2632 return ( r == 0 );
2635 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2637 char *link_name = NULL;
2638 DWORD csidl = -1;
2639 LPWSTR urlPath;
2640 char *escaped_urlPath = NULL;
2641 HRESULT hr;
2642 HANDLE hSem = NULL;
2643 BOOL ret = TRUE;
2644 int r = -1;
2645 char *unix_link = NULL;
2647 if ( !link )
2649 WINE_ERR("Link name is null\n");
2650 return TRUE;
2653 if( !GetLinkLocation( link, &csidl, &link_name ) )
2655 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2656 return TRUE;
2658 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2660 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2661 ret = TRUE;
2662 goto cleanup;
2664 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2666 hr = url->lpVtbl->GetURL(url, &urlPath);
2667 if (FAILED(hr))
2669 ret = TRUE;
2670 goto cleanup;
2672 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2674 unix_link = wine_get_unix_file_name(link);
2675 if (unix_link == NULL)
2677 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2678 goto cleanup;
2681 escaped_urlPath = escape(urlPath);
2682 if (escaped_urlPath == NULL)
2684 WINE_ERR("couldn't escape url, out of memory\n");
2685 goto cleanup;
2688 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2689 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2691 WINE_ERR("failed wait for semaphore\n");
2692 goto cleanup;
2694 if (in_desktop_dir(csidl))
2696 char *location;
2697 const char *lastEntry;
2698 lastEntry = strrchr(link_name, '/');
2699 if (lastEntry == NULL)
2700 lastEntry = link_name;
2701 else
2702 ++lastEntry;
2703 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2704 if (location)
2706 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2707 if (r == 0)
2708 chmod(location, 0755);
2709 HeapFree(GetProcessHeap(), 0, location);
2712 else
2713 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2714 ret = (r != 0);
2715 ReleaseSemaphore(hSem, 1, NULL);
2717 cleanup:
2718 if (hSem)
2719 CloseHandle(hSem);
2720 HeapFree(GetProcessHeap(), 0, link_name);
2721 CoTaskMemFree( urlPath );
2722 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2723 HeapFree(GetProcessHeap(), 0, unix_link);
2724 return ret;
2727 static BOOL WaitForParentProcess( void )
2729 PROCESSENTRY32 procentry;
2730 HANDLE hsnapshot = NULL, hprocess = NULL;
2731 DWORD ourpid = GetCurrentProcessId();
2732 BOOL ret = FALSE, rc;
2734 WINE_TRACE("Waiting for parent process\n");
2735 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2736 INVALID_HANDLE_VALUE)
2738 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2739 goto done;
2742 procentry.dwSize = sizeof(PROCESSENTRY32);
2743 rc = Process32First( hsnapshot, &procentry );
2744 while (rc)
2746 if (procentry.th32ProcessID == ourpid) break;
2747 rc = Process32Next( hsnapshot, &procentry );
2749 if (!rc)
2751 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2752 goto done;
2755 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2756 NULL)
2758 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2759 GetLastError());
2760 goto done;
2763 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2764 ret = TRUE;
2765 else
2766 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2768 done:
2769 if (hprocess) CloseHandle( hprocess );
2770 if (hsnapshot) CloseHandle( hsnapshot );
2771 return ret;
2774 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2776 IShellLinkW *sl;
2777 IPersistFile *pf;
2778 HRESULT r;
2779 WCHAR fullname[MAX_PATH];
2780 DWORD len;
2782 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2784 if( !linkname[0] )
2786 WINE_ERR("link name missing\n");
2787 return 1;
2790 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2791 if (len==0 || len>MAX_PATH)
2793 WINE_ERR("couldn't get full path of link file\n");
2794 return 1;
2797 r = CoInitialize( NULL );
2798 if( FAILED( r ) )
2800 WINE_ERR("CoInitialize failed\n");
2801 return 1;
2804 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2805 &IID_IShellLinkW, (LPVOID *) &sl );
2806 if( FAILED( r ) )
2808 WINE_ERR("No IID_IShellLink\n");
2809 return 1;
2812 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2813 if( FAILED( r ) )
2815 WINE_ERR("No IID_IPersistFile\n");
2816 return 1;
2819 r = IPersistFile_Load( pf, fullname, STGM_READ );
2820 if( SUCCEEDED( r ) )
2822 /* If something fails (eg. Couldn't extract icon)
2823 * wait for parent process and try again
2825 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2827 WaitForParentProcess();
2828 InvokeShellLinker( sl, fullname, FALSE );
2831 else
2833 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2836 IPersistFile_Release( pf );
2837 IShellLinkW_Release( sl );
2839 CoUninitialize();
2841 return !r;
2844 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2846 IUniformResourceLocatorW *url;
2847 IPersistFile *pf;
2848 HRESULT r;
2849 WCHAR fullname[MAX_PATH];
2850 DWORD len;
2852 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2854 if( !urlname[0] )
2856 WINE_ERR("URL name missing\n");
2857 return 1;
2860 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2861 if (len==0 || len>MAX_PATH)
2863 WINE_ERR("couldn't get full path of URL file\n");
2864 return 1;
2867 r = CoInitialize( NULL );
2868 if( FAILED( r ) )
2870 WINE_ERR("CoInitialize failed\n");
2871 return 1;
2874 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2875 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2876 if( FAILED( r ) )
2878 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2879 return 1;
2882 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2883 if( FAILED( r ) )
2885 WINE_ERR("No IID_IPersistFile\n");
2886 return 1;
2888 r = IPersistFile_Load( pf, fullname, STGM_READ );
2889 if( SUCCEEDED( r ) )
2891 /* If something fails (eg. Couldn't extract icon)
2892 * wait for parent process and try again
2894 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2896 WaitForParentProcess();
2897 InvokeShellLinkerForURL( url, fullname, FALSE );
2901 IPersistFile_Release( pf );
2902 url->lpVtbl->Release( url );
2904 CoUninitialize();
2906 return !r;
2909 static void RefreshFileTypeAssociations(void)
2911 HANDLE hSem = NULL;
2912 char *mime_dir = NULL;
2913 char *packages_dir = NULL;
2914 char *applications_dir = NULL;
2915 BOOL hasChanged;
2917 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2918 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2920 WINE_ERR("failed wait for semaphore\n");
2921 CloseHandle(hSem);
2922 hSem = NULL;
2923 goto end;
2926 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2927 if (mime_dir == NULL)
2929 WINE_ERR("out of memory\n");
2930 goto end;
2932 create_directories(mime_dir);
2934 packages_dir = heap_printf("%s/packages", mime_dir);
2935 if (packages_dir == NULL)
2937 WINE_ERR("out of memory\n");
2938 goto end;
2940 create_directories(packages_dir);
2942 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2943 if (applications_dir == NULL)
2945 WINE_ERR("out of memory\n");
2946 goto end;
2948 create_directories(applications_dir);
2950 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2951 hasChanged |= cleanup_associations();
2952 if (hasChanged)
2954 const char *argv[3];
2956 argv[0] = "update-mime-database";
2957 argv[1] = mime_dir;
2958 argv[2] = NULL;
2959 spawnvp( _P_NOWAIT, argv[0], argv );
2961 argv[0] = "update-desktop-database";
2962 argv[1] = applications_dir;
2963 spawnvp( _P_NOWAIT, argv[0], argv );
2966 end:
2967 if (hSem)
2969 ReleaseSemaphore(hSem, 1, NULL);
2970 CloseHandle(hSem);
2972 HeapFree(GetProcessHeap(), 0, mime_dir);
2973 HeapFree(GetProcessHeap(), 0, packages_dir);
2974 HeapFree(GetProcessHeap(), 0, applications_dir);
2977 static void cleanup_menus(void)
2979 HKEY hkey;
2981 hkey = open_menus_reg_key();
2982 if (hkey)
2984 int i;
2985 LSTATUS lret = ERROR_SUCCESS;
2986 for (i = 0; lret == ERROR_SUCCESS; )
2988 WCHAR *value = NULL;
2989 WCHAR *data = NULL;
2990 DWORD valueSize = 4096;
2991 DWORD dataSize = 4096;
2992 while (1)
2994 lret = ERROR_OUTOFMEMORY;
2995 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
2996 if (value == NULL)
2997 break;
2998 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
2999 if (data == NULL)
3000 break;
3001 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3002 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
3003 break;
3004 valueSize *= 2;
3005 dataSize *= 2;
3006 HeapFree(GetProcessHeap(), 0, value);
3007 HeapFree(GetProcessHeap(), 0, data);
3008 value = data = NULL;
3010 if (lret == ERROR_SUCCESS)
3012 char *unix_file;
3013 char *windows_file;
3014 unix_file = wchars_to_unix_chars(value);
3015 windows_file = wchars_to_unix_chars(data);
3016 if (unix_file != NULL && windows_file != NULL)
3018 struct stat filestats;
3019 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3021 WINE_TRACE("removing menu related file %s\n", unix_file);
3022 remove(unix_file);
3023 RegDeleteValueW(hkey, value);
3025 else
3026 i++;
3028 else
3030 WINE_ERR("out of memory enumerating menus\n");
3031 lret = ERROR_OUTOFMEMORY;
3033 HeapFree(GetProcessHeap(), 0, unix_file);
3034 HeapFree(GetProcessHeap(), 0, windows_file);
3036 else if (lret != ERROR_NO_MORE_ITEMS)
3037 WINE_ERR("error %d reading registry\n", lret);
3038 HeapFree(GetProcessHeap(), 0, value);
3039 HeapFree(GetProcessHeap(), 0, data);
3041 RegCloseKey(hkey);
3043 else
3044 WINE_ERR("error opening registry key, menu cleanup failed\n");
3047 static WCHAR *next_token( LPWSTR *p )
3049 LPWSTR token = NULL, t = *p;
3051 if( !t )
3052 return NULL;
3054 while( t && !token )
3056 switch( *t )
3058 case ' ':
3059 t++;
3060 continue;
3061 case '"':
3062 /* unquote the token */
3063 token = ++t;
3064 t = strchrW( token, '"' );
3065 if( t )
3066 *t++ = 0;
3067 break;
3068 case 0:
3069 t = NULL;
3070 break;
3071 default:
3072 token = t;
3073 t = strchrW( token, ' ' );
3074 if( t )
3075 *t++ = 0;
3076 break;
3079 *p = t;
3080 return token;
3083 static BOOL init_xdg(void)
3085 WCHAR shellDesktopPath[MAX_PATH];
3086 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3087 if (SUCCEEDED(hr))
3088 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3089 if (xdg_desktop_dir == NULL)
3091 WINE_ERR("error looking up the desktop directory\n");
3092 return FALSE;
3095 if (getenv("XDG_CONFIG_HOME"))
3096 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3097 else
3098 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3099 if (xdg_config_dir)
3101 create_directories(xdg_config_dir);
3102 if (getenv("XDG_DATA_HOME"))
3103 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3104 else
3105 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3106 if (xdg_data_dir)
3108 char *buffer;
3109 create_directories(xdg_data_dir);
3110 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3111 if (buffer)
3113 mkdir(buffer, 0777);
3114 HeapFree(GetProcessHeap(), 0, buffer);
3116 return TRUE;
3118 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3120 WINE_ERR("out of memory\n");
3121 return FALSE;
3124 /***********************************************************************
3126 * wWinMain
3128 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3130 static const WCHAR dash_aW[] = {'-','a',0};
3131 static const WCHAR dash_rW[] = {'-','r',0};
3132 static const WCHAR dash_uW[] = {'-','u',0};
3133 static const WCHAR dash_wW[] = {'-','w',0};
3135 LPWSTR token = NULL, p;
3136 BOOL bWait = FALSE;
3137 BOOL bURL = FALSE;
3138 int ret = 0;
3140 if (!init_xdg())
3141 return 1;
3143 for( p = cmdline; p && *p; )
3145 token = next_token( &p );
3146 if( !token )
3147 break;
3148 if( !strcmpW( token, dash_aW ) )
3150 RefreshFileTypeAssociations();
3151 continue;
3153 if( !strcmpW( token, dash_rW ) )
3155 cleanup_menus();
3156 continue;
3158 if( !strcmpW( token, dash_wW ) )
3159 bWait = TRUE;
3160 else if ( !strcmpW( token, dash_uW ) )
3161 bURL = TRUE;
3162 else if( token[0] == '-' )
3164 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3166 else
3168 BOOL bRet;
3170 if (bURL)
3171 bRet = Process_URL( token, bWait );
3172 else
3173 bRet = Process_Link( token, bWait );
3174 if (!bRet)
3176 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3177 ret = 1;
3182 return ret;