pop 82b96efacb3a9cb3edb980e14b32deae44651c0c
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
bloba40a657e274a7cf5c17a99d145649fcf7f29a8ba
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 /* Icon extraction routines
177 * FIXME: should use PrivateExtractIcons and friends
178 * FIXME: should not use stdio
181 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
183 /* PNG-specific code */
184 #ifdef SONAME_LIBPNG
186 static void *libpng_handle;
187 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
188 MAKE_FUNCPTR(png_create_info_struct);
189 MAKE_FUNCPTR(png_create_write_struct);
190 MAKE_FUNCPTR(png_destroy_write_struct);
191 MAKE_FUNCPTR(png_get_error_ptr);
192 MAKE_FUNCPTR(png_init_io);
193 MAKE_FUNCPTR(png_set_bgr);
194 MAKE_FUNCPTR(png_set_error_fn);
195 MAKE_FUNCPTR(png_set_text);
196 MAKE_FUNCPTR(png_set_IHDR);
197 MAKE_FUNCPTR(png_write_end);
198 MAKE_FUNCPTR(png_write_info);
199 MAKE_FUNCPTR(png_write_row);
200 #undef MAKE_FUNCPTR
202 static void *load_libpng(void)
204 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
206 #define LOAD_FUNCPTR(f) \
207 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
208 libpng_handle = NULL; \
209 return NULL; \
211 LOAD_FUNCPTR(png_create_info_struct);
212 LOAD_FUNCPTR(png_create_write_struct);
213 LOAD_FUNCPTR(png_destroy_write_struct);
214 LOAD_FUNCPTR(png_get_error_ptr);
215 LOAD_FUNCPTR(png_init_io);
216 LOAD_FUNCPTR(png_set_bgr);
217 LOAD_FUNCPTR(png_set_error_fn);
218 LOAD_FUNCPTR(png_set_IHDR);
219 LOAD_FUNCPTR(png_set_text);
220 LOAD_FUNCPTR(png_write_end);
221 LOAD_FUNCPTR(png_write_info);
222 LOAD_FUNCPTR(png_write_row);
223 #undef LOAD_FUNCPTR
225 return libpng_handle;
228 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
230 jmp_buf *pjmpbuf;
232 /* This uses setjmp/longjmp just like the default. We can't use the
233 * default because there's no way to access the jmp buffer in the png_struct
234 * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
235 WINE_ERR("PNG error: %s\n", wine_dbgstr_an(error_message, -1));
236 pjmpbuf = ppng_get_error_ptr(png_ptr);
237 longjmp(*pjmpbuf, 1);
240 static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
242 WINE_WARN("PNG warning: %s\n", wine_dbgstr_an(warning_message, -1));
245 static BOOL SaveTrueColorIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
247 static const char comment_key[] = "Created from";
248 FILE *fp;
249 png_structp png_ptr;
250 png_infop info_ptr;
251 png_text comment;
252 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
253 BYTE *row, *copy = NULL;
254 const BYTE *pXOR, *pAND = NULL;
255 int nWidth = pIcon->bmiHeader.biWidth;
256 int nHeight = pIcon->bmiHeader.biHeight;
257 int nBpp = pIcon->bmiHeader.biBitCount;
258 jmp_buf jmpbuf;
260 switch (nBpp)
262 case 32:
263 color_type |= PNG_COLOR_MASK_ALPHA;
264 /* fall through */
265 case 24:
266 color_type |= PNG_COLOR_MASK_COLOR;
267 break;
268 default:
269 return FALSE;
272 if (!libpng_handle && !load_libpng())
274 WINE_WARN("Unable to load libpng\n");
275 return FALSE;
278 if (!(fp = fopen(png_filename, "w")))
280 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
281 return FALSE;
284 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
285 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
286 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
287 if (nHeight > nWidth)
289 nHeight /= 2;
290 pAND = pXOR + nHeight * nXORWidthBytes;
293 /* Apply mask if present */
294 if (pAND)
296 RGBQUAD bgColor;
298 /* copy bytes before modifying them */
299 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
300 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
301 pXOR = copy;
303 /* image and mask are upside down reversed */
304 row = copy + (nHeight - 1) * nXORWidthBytes;
306 /* top left corner */
307 bgColor.rgbRed = row[0];
308 bgColor.rgbGreen = row[1];
309 bgColor.rgbBlue = row[2];
310 bgColor.rgbReserved = 0;
312 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
313 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
314 if (MASK(j, i))
316 RGBQUAD *pixel = (RGBQUAD *)row;
317 pixel->rgbBlue = bgColor.rgbBlue;
318 pixel->rgbGreen = bgColor.rgbGreen;
319 pixel->rgbRed = bgColor.rgbRed;
320 if (nBpp == 32)
321 pixel->rgbReserved = bgColor.rgbReserved;
325 comment.text = NULL;
327 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
328 !(info_ptr = ppng_create_info_struct(png_ptr)))
329 goto error;
331 if (setjmp(jmpbuf))
333 /* All future errors jump here */
334 goto error;
336 ppng_set_error_fn(png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
338 ppng_init_io(png_ptr, fp);
339 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
340 color_type,
341 PNG_INTERLACE_NONE,
342 PNG_COMPRESSION_TYPE_DEFAULT,
343 PNG_FILTER_TYPE_DEFAULT);
345 /* Set comment */
346 comment.compression = PNG_TEXT_COMPRESSION_NONE;
347 comment.key = (png_charp)comment_key;
348 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
349 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
350 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
351 comment.text_length = i - 1;
352 ppng_set_text(png_ptr, info_ptr, &comment, 1);
355 ppng_write_info(png_ptr, info_ptr);
356 ppng_set_bgr(png_ptr);
357 for (i = nHeight - 1; i >= 0 ; i--)
358 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
359 ppng_write_end(png_ptr, info_ptr);
361 ppng_destroy_write_struct(&png_ptr, &info_ptr);
362 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
363 fclose(fp);
364 HeapFree(GetProcessHeap(), 0, copy);
365 HeapFree(GetProcessHeap(), 0, comment.text);
366 return TRUE;
368 error:
369 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
370 fclose(fp);
371 unlink(png_filename);
372 HeapFree(GetProcessHeap(), 0, copy);
373 HeapFree(GetProcessHeap(), 0, comment.text);
374 return FALSE;
377 static BOOL SavePalettedIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
379 static const char comment_key[] = "Created from";
380 FILE *pngFile = NULL;
381 int i, j;
382 int nHeight;
383 int nXORWidthBytes;
384 int nANDWidthBytes;
385 BOOL b8BitColors;
386 int nColors;
387 const BYTE *pXOR;
388 const BYTE *pAND;
389 png_structp png_ptr;
390 png_infop info_ptr;
391 png_text comment;
392 jmp_buf jmpbuf;
393 unsigned char *row = NULL;
394 BOOL ret = FALSE;
396 comment.text = NULL;
398 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
400 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
401 goto done;
404 if (!(pngFile = fopen(png_filename, "w")))
406 WINE_TRACE("Unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
407 goto done;
410 nHeight = pIcon->bmiHeader.biHeight / 2;
411 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
412 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
413 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
414 + ((pIcon->bmiHeader.biWidth % 32) > 0));
415 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
416 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
417 : 1 << pIcon->bmiHeader.biBitCount;
418 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
419 pAND = pXOR + nHeight * nXORWidthBytes;
421 row = HeapAlloc(GetProcessHeap(), 0, 4 * pIcon->bmiHeader.biWidth);
422 if (row == NULL)
424 WINE_ERR("out of memory\n");
425 goto done;
428 if (!libpng_handle && !load_libpng())
430 WINE_WARN("Unable to load libpng\n");
431 goto done;
434 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
435 !(info_ptr = ppng_create_info_struct(png_ptr)))
436 goto done;
438 if (setjmp(jmpbuf))
440 /* All future errors jump here */
441 goto done;
443 ppng_set_error_fn(png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
445 ppng_init_io(png_ptr, pngFile);
446 ppng_set_IHDR(png_ptr, info_ptr, pIcon->bmiHeader.biWidth, nHeight, 8,
447 PNG_COLOR_TYPE_RGB_ALPHA,
448 PNG_INTERLACE_NONE,
449 PNG_COMPRESSION_TYPE_DEFAULT,
450 PNG_FILTER_TYPE_DEFAULT);
452 /* Set comment */
453 comment.compression = PNG_TEXT_COMPRESSION_NONE;
454 comment.key = (png_charp)comment_key;
455 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
456 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
457 if (comment.text == NULL)
459 WINE_ERR("out of memory\n");
460 goto done;
462 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
463 comment.text_length = i - 1;
464 ppng_set_text(png_ptr, info_ptr, &comment, 1);
466 ppng_write_info(png_ptr, info_ptr);
467 for (i = 0; i < nHeight; i++)
469 unsigned char *p = row;
470 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
472 if MASK(j,i)
474 *p++ = 0;
475 *p++ = 0;
476 *p++ = 0;
477 *p++ = 0;
479 else
481 #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)
482 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbRed;
483 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbGreen;
484 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbBlue;
485 *p++ = 0xFF;
486 #undef COLOR
489 ppng_write_row(png_ptr, (png_bytep)row);
491 ppng_write_end(png_ptr, info_ptr);
492 ret = TRUE;
494 done:
495 ppng_destroy_write_struct(&png_ptr, &info_ptr);
496 if (pngFile != NULL)
497 fclose(pngFile);
498 HeapFree(GetProcessHeap(), 0, comment.text);
499 HeapFree(GetProcessHeap(), 0, row);
500 return ret;
503 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
505 switch (pIcon->bmiHeader.biBitCount)
507 case 4:
508 case 8:
509 return SavePalettedIconResAsPNG(pIcon, png_filename, commentW);
510 case 24:
511 case 32:
512 return SaveTrueColorIconResAsPNG(pIcon, png_filename, commentW);
513 default:
514 WINE_FIXME("unsupported bpp %d, please report", pIcon->bmiHeader.biBitCount);
515 return FALSE;
518 #endif /* SONAME_LIBPNG */
520 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
522 FILE *fXPMFile;
523 int nHeight;
524 int nXORWidthBytes;
525 int nANDWidthBytes;
526 BOOL b8BitColors;
527 int nColors;
528 const BYTE *pXOR;
529 const BYTE *pAND;
530 BOOL aColorUsed[256] = {0};
531 int nColorsUsed = 0;
532 int i,j;
533 char *comment;
535 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
537 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
538 return FALSE;
541 if (!(fXPMFile = fopen(szXPMFileName, "w")))
543 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
544 return FALSE;
547 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
548 comment = HeapAlloc(GetProcessHeap(), 0, i);
549 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
551 nHeight = pIcon->bmiHeader.biHeight / 2;
552 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
553 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
554 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
555 + ((pIcon->bmiHeader.biWidth % 32) > 0));
556 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
557 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
558 : 1 << pIcon->bmiHeader.biBitCount;
559 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
560 pAND = pXOR + nHeight * nXORWidthBytes;
562 #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)
564 for (i = 0; i < nHeight; i++) {
565 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
566 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
568 aColorUsed[COLOR(j,i)] = TRUE;
569 nColorsUsed++;
574 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
575 goto error;
576 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
577 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
578 goto error;
580 for (i = 0; i < nColors; i++) {
581 if (aColorUsed[i])
582 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
583 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
584 goto error;
586 if (fprintf(fXPMFile, "\" c None\"") <= 0)
587 goto error;
589 for (i = 0; i < nHeight; i++)
591 if (fprintf(fXPMFile, ",\n\"") <= 0)
592 goto error;
593 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
595 if MASK(j,i)
597 if (fprintf(fXPMFile, " ") <= 0)
598 goto error;
600 else
601 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
602 goto error;
604 if (fprintf(fXPMFile, "\"") <= 0)
605 goto error;
607 if (fprintf(fXPMFile, "};\n") <= 0)
608 goto error;
610 #undef MASK
611 #undef COLOR
613 HeapFree(GetProcessHeap(), 0, comment);
614 fclose(fXPMFile);
615 return TRUE;
617 error:
618 HeapFree(GetProcessHeap(), 0, comment);
619 fclose(fXPMFile);
620 unlink( szXPMFileName );
621 return FALSE;
624 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
626 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
628 if (!sEnumRes->nIndex--)
630 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
631 return FALSE;
633 else
634 return TRUE;
637 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
639 HMODULE hModule;
640 HRSRC hResInfo;
641 LPCWSTR lpName = NULL;
642 HGLOBAL hResData;
643 GRPICONDIR *pIconDir;
644 BITMAPINFO *pIcon;
645 ENUMRESSTRUCT sEnumRes;
646 int nMax = 0;
647 int nMaxBits = 0;
648 int i;
649 BOOL ret = FALSE;
651 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
652 if (!hModule)
654 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
655 wine_dbgstr_w(szFileName), GetLastError());
656 return FALSE;
659 if (nIndex < 0)
661 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
662 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
663 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
665 else
667 hResInfo=NULL;
668 sEnumRes.pResInfo = &hResInfo;
669 sEnumRes.nIndex = nIndex;
670 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
671 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
672 sEnumRes.nIndex != -1)
674 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
678 if (hResInfo)
680 if ((hResData = LoadResource(hModule, hResInfo)))
682 if ((pIconDir = LockResource(hResData)))
684 for (i = 0; i < pIconDir->idCount; i++)
686 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
688 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
690 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
691 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
692 nMaxBits = pIconDir->idEntries[i].wBitCount;
698 FreeResource(hResData);
701 else
703 WINE_WARN("found no icon\n");
704 FreeLibrary(hModule);
705 return FALSE;
708 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
710 if ((hResData = LoadResource(hModule, hResInfo)))
712 if ((pIcon = LockResource(hResData)))
714 #ifdef SONAME_LIBPNG
715 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
716 ret = TRUE;
717 else
718 #endif
720 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
721 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
722 ret = TRUE;
726 FreeResource(hResData);
730 FreeLibrary(hModule);
731 return ret;
734 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
736 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
737 !extract_icon16(szFileName, szXPMFileName)*/)
738 return FALSE;
739 return TRUE;
742 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
744 FILE *fICOFile = NULL;
745 ICONDIR iconDir;
746 ICONDIRENTRY *pIconDirEntry = NULL;
747 int nMax = 0, nMaxBits = 0;
748 int nIndex = 0;
749 void *pIcon = NULL;
750 int i;
751 char *filename = NULL;
753 filename = wine_get_unix_file_name(szFileName);
754 if (!(fICOFile = fopen(filename, "r")))
756 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
757 goto error;
760 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
761 (iconDir.idReserved != 0) || (iconDir.idType != 1))
763 WINE_WARN("Invalid ico file format\n");
764 goto error;
767 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
768 goto error;
769 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
770 goto error;
772 for (i = 0; i < iconDir.idCount; i++)
774 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
775 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
776 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
778 nIndex = i;
779 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
780 nMaxBits = pIconDirEntry[i].wBitCount;
783 WINE_TRACE("Selected: %d\n", nIndex);
785 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
786 goto error;
787 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
788 goto error;
789 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
790 goto error;
793 /* Prefer PNG over XPM */
794 #ifdef SONAME_LIBPNG
795 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
796 #endif
798 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
799 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
800 goto error;
803 HeapFree(GetProcessHeap(), 0, pIcon);
804 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
805 fclose(fICOFile);
806 HeapFree(GetProcessHeap(), 0, filename);
807 return 1;
809 error:
810 HeapFree(GetProcessHeap(), 0, pIcon);
811 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
812 if (fICOFile) fclose(fICOFile);
813 HeapFree(GetProcessHeap(), 0, filename);
814 return 0;
817 static BOOL create_default_icon( const char *filename, const char* comment )
819 FILE *fXPM;
820 unsigned int i;
822 if (!(fXPM = fopen(filename, "w"))) return FALSE;
823 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
824 goto error;
825 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
826 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
827 goto error;
829 if (fprintf( fXPM, "};\n" ) <=0)
830 goto error;
831 fclose( fXPM );
832 return TRUE;
833 error:
834 fclose( fXPM );
835 unlink( filename );
836 return FALSE;
840 static unsigned short crc16(const char* string)
842 unsigned short crc = 0;
843 int i, j, xor_poly;
845 for (i = 0; string[i] != 0; i++)
847 char c = string[i];
848 for (j = 0; j < 8; c >>= 1, j++)
850 xor_poly = (c ^ crc) & 1;
851 crc >>= 1;
852 if (xor_poly)
853 crc ^= 0xa001;
856 return crc;
859 static char *strdupA( const char *str )
861 char *ret;
863 if (!str) return NULL;
864 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
865 return ret;
868 static char* heap_printf(const char *format, ...)
870 va_list args;
871 int size = 4096;
872 char *buffer, *ret;
873 int n;
875 va_start(args, format);
876 while (1)
878 buffer = HeapAlloc(GetProcessHeap(), 0, size);
879 if (buffer == NULL)
880 break;
881 n = vsnprintf(buffer, size, format, args);
882 if (n == -1)
883 size *= 2;
884 else if (n >= size)
885 size = n + 1;
886 else
887 break;
888 HeapFree(GetProcessHeap(), 0, buffer);
890 va_end(args);
891 if (!buffer) return NULL;
892 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
893 if (!ret) ret = buffer;
894 return ret;
897 static void write_xml_text(FILE *file, const char *text)
899 int i;
900 for (i = 0; text[i]; i++)
902 if (text[i] == '&')
903 fputs("&amp;", file);
904 else if (text[i] == '<')
905 fputs("&lt;", file);
906 else if (text[i] == '>')
907 fputs("&gt;", file);
908 else if (text[i] == '\'')
909 fputs("&apos;", file);
910 else if (text[i] == '"')
911 fputs("&quot;", file);
912 else
913 fputc(text[i], file);
917 static BOOL create_directories(char *directory)
919 BOOL ret = TRUE;
920 int i;
922 for (i = 0; directory[i]; i++)
924 if (i > 0 && directory[i] == '/')
926 directory[i] = 0;
927 mkdir(directory, 0777);
928 directory[i] = '/';
931 if (mkdir(directory, 0777) && errno != EEXIST)
932 ret = FALSE;
934 return ret;
937 static char* wchars_to_utf8_chars(LPCWSTR string)
939 char *ret;
940 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
941 ret = HeapAlloc(GetProcessHeap(), 0, size);
942 if (ret)
943 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
944 return ret;
947 static char* wchars_to_unix_chars(LPCWSTR string)
949 char *ret;
950 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
951 ret = HeapAlloc(GetProcessHeap(), 0, size);
952 if (ret)
953 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
954 return ret;
957 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
959 WCHAR *ret;
960 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
961 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
962 if (ret)
963 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
964 return ret;
967 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
968 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
970 unsigned short crc;
971 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
972 char* s;
973 int n;
975 /* Where should we save the icon? */
976 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
977 iconsdir = heap_printf("%s/icons", xdg_data_dir);
978 if (iconsdir)
980 if (mkdir(iconsdir, 0777) && errno != EEXIST)
982 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
983 goto end;
986 else
988 WINE_TRACE("no icon created\n");
989 return NULL;
992 /* Determine the icon base name */
993 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
994 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
995 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
996 s=ico_name=ico_path;
997 while (*s!='\0') {
998 if (*s=='/' || *s=='\\') {
999 *s='\\';
1000 ico_name=s;
1001 } else {
1002 *s=tolower(*s);
1004 s++;
1006 if (*ico_name=='\\') *ico_name++='\0';
1007 s=strrchr(ico_name,'.');
1008 if (s) *s='\0';
1010 /* Compute the source-path hash */
1011 crc=crc16(ico_path);
1013 /* Try to treat the source file as an exe */
1014 if (destFilename)
1015 xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
1016 else
1017 xpm_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
1018 if (xpm_path == NULL)
1020 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
1021 return NULL;
1024 if (ExtractFromEXEDLL( path, index, xpm_path ))
1025 goto end;
1027 /* Must be something else, ignore the index in that case */
1028 if (destFilename)
1029 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
1030 else
1031 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
1032 if (ExtractFromICO( path, xpm_path))
1033 goto end;
1034 if (!bWait)
1036 if (destFilename)
1037 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
1038 else
1039 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
1040 if (create_default_icon( xpm_path, ico_path ))
1041 goto end;
1044 HeapFree( GetProcessHeap(), 0, xpm_path );
1045 xpm_path=NULL;
1047 end:
1048 HeapFree(GetProcessHeap(), 0, iconsdir);
1049 HeapFree(GetProcessHeap(), 0, ico_path);
1050 return xpm_path;
1053 static HKEY open_menus_reg_key(void)
1055 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1056 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1057 HKEY assocKey;
1058 DWORD ret;
1059 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1060 if (ret == ERROR_SUCCESS)
1061 return assocKey;
1062 SetLastError(ret);
1063 return NULL;
1066 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1068 WCHAR *unix_fileW;
1069 WCHAR *windows_fileW;
1070 INT size;
1071 DWORD ret;
1073 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1074 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1075 if (unix_fileW)
1077 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1078 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1079 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1080 if (windows_fileW)
1082 HKEY hkey;
1083 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1084 hkey = open_menus_reg_key();
1085 if (hkey)
1087 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1088 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1089 RegCloseKey(hkey);
1091 else
1092 ret = GetLastError();
1093 HeapFree(GetProcessHeap(), 0, windows_fileW);
1095 else
1096 ret = ERROR_NOT_ENOUGH_MEMORY;
1097 HeapFree(GetProcessHeap(), 0, unix_fileW);
1099 else
1100 ret = ERROR_NOT_ENOUGH_MEMORY;
1101 return ret;
1104 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1105 const char *path, const char *args, const char *descr,
1106 const char *workdir, const char *icon)
1108 FILE *file;
1110 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1111 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1112 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1114 file = fopen(location, "w");
1115 if (file == NULL)
1116 return FALSE;
1118 fprintf(file, "[Desktop Entry]\n");
1119 fprintf(file, "Name=%s\n", linkname);
1120 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1121 wine_get_config_dir(), path, args);
1122 fprintf(file, "Type=Application\n");
1123 fprintf(file, "StartupNotify=true\n");
1124 if (descr && lstrlenA(descr))
1125 fprintf(file, "Comment=%s\n", descr);
1126 if (workdir && lstrlenA(workdir))
1127 fprintf(file, "Path=%s\n", workdir);
1128 if (icon && lstrlenA(icon))
1129 fprintf(file, "Icon=%s\n", icon);
1131 fclose(file);
1133 if (unix_link)
1135 DWORD ret = register_menus_entry(location, unix_link);
1136 if (ret != ERROR_SUCCESS)
1137 return FALSE;
1140 return TRUE;
1143 static BOOL write_directory_entry(const char *directory, const char *location)
1145 FILE *file;
1147 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1149 file = fopen(location, "w");
1150 if (file == NULL)
1151 return FALSE;
1153 fprintf(file, "[Desktop Entry]\n");
1154 fprintf(file, "Type=Directory\n");
1155 if (strcmp(directory, "wine") == 0)
1157 fprintf(file, "Name=Wine\n");
1158 fprintf(file, "Icon=wine\n");
1160 else
1162 fprintf(file, "Name=%s\n", directory);
1163 fprintf(file, "Icon=folder\n");
1166 fclose(file);
1167 return TRUE;
1170 static BOOL write_menu_file(const char *unix_link, const char *filename)
1172 char *tempfilename;
1173 FILE *tempfile = NULL;
1174 char *lastEntry;
1175 char *name = NULL;
1176 char *menuPath = NULL;
1177 int i;
1178 int count = 0;
1179 BOOL ret = FALSE;
1181 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1183 while (1)
1185 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1186 if (tempfilename)
1188 int tempfd = mkstemps(tempfilename, 0);
1189 if (tempfd >= 0)
1191 tempfile = fdopen(tempfd, "w");
1192 if (tempfile)
1193 break;
1194 close(tempfd);
1195 goto end;
1197 else if (errno == EEXIST)
1199 HeapFree(GetProcessHeap(), 0, tempfilename);
1200 continue;
1202 HeapFree(GetProcessHeap(), 0, tempfilename);
1204 return FALSE;
1207 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1208 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1209 fprintf(tempfile, "<Menu>\n");
1210 fprintf(tempfile, " <Name>Applications</Name>\n");
1212 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1213 if (name == NULL) goto end;
1214 lastEntry = name;
1215 for (i = 0; filename[i]; i++)
1217 name[i] = filename[i];
1218 if (filename[i] == '/')
1220 char *dir_file_name;
1221 struct stat st;
1222 name[i] = 0;
1223 fprintf(tempfile, " <Menu>\n");
1224 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1225 write_xml_text(tempfile, name);
1226 fprintf(tempfile, "</Name>\n");
1227 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1228 write_xml_text(tempfile, name);
1229 fprintf(tempfile, ".directory</Directory>\n");
1230 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1231 xdg_data_dir, count ? "" : "wine-", name);
1232 if (dir_file_name)
1234 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1235 write_directory_entry(lastEntry, dir_file_name);
1236 HeapFree(GetProcessHeap(), 0, dir_file_name);
1238 name[i] = '-';
1239 lastEntry = &name[i+1];
1240 ++count;
1243 name[i] = 0;
1245 fprintf(tempfile, " <Include>\n");
1246 fprintf(tempfile, " <Filename>");
1247 write_xml_text(tempfile, name);
1248 fprintf(tempfile, "</Filename>\n");
1249 fprintf(tempfile, " </Include>\n");
1250 for (i = 0; i < count; i++)
1251 fprintf(tempfile, " </Menu>\n");
1252 fprintf(tempfile, "</Menu>\n");
1254 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1255 if (menuPath == NULL) goto end;
1256 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1257 ret = TRUE;
1259 end:
1260 if (tempfile)
1261 fclose(tempfile);
1262 if (ret)
1263 ret = (rename(tempfilename, menuPath) == 0);
1264 if (!ret && tempfilename)
1265 remove(tempfilename);
1266 HeapFree(GetProcessHeap(), 0, tempfilename);
1267 if (ret)
1268 register_menus_entry(menuPath, unix_link);
1269 HeapFree(GetProcessHeap(), 0, name);
1270 HeapFree(GetProcessHeap(), 0, menuPath);
1271 return ret;
1274 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1275 const char *descr, const char *workdir, const char *icon)
1277 const char *linkname;
1278 char *desktopPath = NULL;
1279 char *desktopDir;
1280 char *filename = NULL;
1281 BOOL ret = TRUE;
1283 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1284 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1285 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1287 linkname = strrchr(link, '/');
1288 if (linkname == NULL)
1289 linkname = link;
1290 else
1291 ++linkname;
1293 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1294 if (!desktopPath)
1296 WINE_WARN("out of memory creating menu entry\n");
1297 ret = FALSE;
1298 goto end;
1300 desktopDir = strrchr(desktopPath, '/');
1301 *desktopDir = 0;
1302 if (!create_directories(desktopPath))
1304 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1305 ret = FALSE;
1306 goto end;
1308 *desktopDir = '/';
1309 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1311 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1312 ret = FALSE;
1313 goto end;
1316 filename = heap_printf("wine/%s.desktop", link);
1317 if (!filename || !write_menu_file(unix_link, filename))
1319 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1320 ret = FALSE;
1323 end:
1324 HeapFree(GetProcessHeap(), 0, desktopPath);
1325 HeapFree(GetProcessHeap(), 0, filename);
1326 return ret;
1329 /* This escapes reserved characters in .desktop files' Exec keys. */
1330 static LPSTR escape(LPCWSTR arg)
1332 int i, j;
1333 WCHAR *escaped_string;
1334 char *utf8_string;
1336 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1337 if (escaped_string == NULL) return NULL;
1338 for (i = j = 0; arg[i]; i++)
1340 switch (arg[i])
1342 case '\\':
1343 escaped_string[j++] = '\\';
1344 escaped_string[j++] = '\\';
1345 escaped_string[j++] = '\\';
1346 escaped_string[j++] = '\\';
1347 break;
1348 case ' ':
1349 case '\t':
1350 case '\n':
1351 case '"':
1352 case '\'':
1353 case '>':
1354 case '<':
1355 case '~':
1356 case '|':
1357 case '&':
1358 case ';':
1359 case '$':
1360 case '*':
1361 case '?':
1362 case '#':
1363 case '(':
1364 case ')':
1365 case '`':
1366 escaped_string[j++] = '\\';
1367 escaped_string[j++] = '\\';
1368 /* fall through */
1369 default:
1370 escaped_string[j++] = arg[i];
1371 break;
1374 escaped_string[j] = 0;
1376 utf8_string = wchars_to_utf8_chars(escaped_string);
1377 if (utf8_string == NULL)
1379 WINE_ERR("out of memory\n");
1380 goto end;
1383 end:
1384 HeapFree(GetProcessHeap(), 0, escaped_string);
1385 return utf8_string;
1388 /* Return a heap-allocated copy of the unix format difference between the two
1389 * Windows-format paths.
1390 * locn is the owning location
1391 * link is within locn
1393 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1395 char *unix_locn, *unix_link;
1396 char *relative = NULL;
1398 unix_locn = wine_get_unix_file_name(locn);
1399 unix_link = wine_get_unix_file_name(link);
1400 if (unix_locn && unix_link)
1402 size_t len_unix_locn, len_unix_link;
1403 len_unix_locn = strlen (unix_locn);
1404 len_unix_link = strlen (unix_link);
1405 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1407 size_t len_rel;
1408 char *p = strrchr (unix_link + len_unix_locn, '/');
1409 p = strrchr (p, '.');
1410 if (p)
1412 *p = '\0';
1413 len_unix_link = p - unix_link;
1415 len_rel = len_unix_link - len_unix_locn;
1416 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1417 if (relative)
1419 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1423 if (!relative)
1424 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1425 HeapFree(GetProcessHeap(), 0, unix_locn);
1426 HeapFree(GetProcessHeap(), 0, unix_link);
1427 return relative;
1430 /***********************************************************************
1432 * GetLinkLocation
1434 * returns TRUE if successful
1435 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1436 * *relative will contain the address of a heap-allocated copy of the portion
1437 * of the filename that is within the specified location, in unix form
1439 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1441 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1442 DWORD len, i, r, filelen;
1443 const DWORD locations[] = {
1444 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1445 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1446 CSIDL_COMMON_STARTMENU };
1448 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1449 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1450 if (filelen==0 || filelen>MAX_PATH)
1451 return FALSE;
1453 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1455 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1456 * expand or our hardcoded list won't match.
1458 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1459 if (filelen==0 || filelen>MAX_PATH)
1460 return FALSE;
1462 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1464 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1466 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1467 continue;
1469 len = lstrlenW(buffer);
1470 if (len >= MAX_PATH)
1471 continue; /* We've just trashed memory! Hopefully we are OK */
1473 if (len > filelen || filename[len]!='\\')
1474 continue;
1475 /* do a lstrcmpinW */
1476 filename[len] = 0;
1477 r = lstrcmpiW( filename, buffer );
1478 filename[len] = '\\';
1479 if ( r )
1480 continue;
1482 /* return the remainder of the string and link type */
1483 *loc = locations[i];
1484 *relative = relative_path (filename, buffer);
1485 return (*relative != NULL);
1488 return FALSE;
1491 /* gets the target path directly or through MSI */
1492 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1493 LPWSTR szArgs, DWORD argsSize)
1495 IShellLinkDataList *dl = NULL;
1496 EXP_DARWIN_LINK *dar = NULL;
1497 HRESULT hr;
1499 szPath[0] = 0;
1500 szArgs[0] = 0;
1502 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1503 if (hr == S_OK && szPath[0])
1505 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1506 return hr;
1509 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1510 if (FAILED(hr))
1511 return hr;
1513 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1514 if (SUCCEEDED(hr))
1516 WCHAR* szCmdline;
1517 DWORD cmdSize;
1519 cmdSize=0;
1520 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1521 if (hr == ERROR_SUCCESS)
1523 cmdSize++;
1524 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1525 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1526 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1527 if (hr == ERROR_SUCCESS)
1529 WCHAR *s, *d;
1530 int bcount, in_quotes;
1532 /* Extract the application path */
1533 bcount=0;
1534 in_quotes=0;
1535 s=szCmdline;
1536 d=szPath;
1537 while (*s)
1539 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1541 /* skip the remaining spaces */
1542 do {
1543 s++;
1544 } while (*s==0x0009 || *s==0x0020);
1545 break;
1547 else if (*s==0x005c)
1549 /* '\\' */
1550 *d++=*s++;
1551 bcount++;
1553 else if (*s==0x0022)
1555 /* '"' */
1556 if ((bcount & 1)==0)
1558 /* Preceded by an even number of '\', this is
1559 * half that number of '\', plus a quote which
1560 * we erase.
1562 d-=bcount/2;
1563 in_quotes=!in_quotes;
1564 s++;
1566 else
1568 /* Preceded by an odd number of '\', this is
1569 * half that number of '\' followed by a '"'
1571 d=d-bcount/2-1;
1572 *d++='"';
1573 s++;
1575 bcount=0;
1577 else
1579 /* a regular character */
1580 *d++=*s++;
1581 bcount=0;
1583 if ((d-szPath) == pathSize)
1585 /* Keep processing the path till we get to the
1586 * arguments, but 'stand still'
1588 d--;
1591 /* Close the application path */
1592 *d=0;
1594 lstrcpynW(szArgs, s, argsSize);
1596 HeapFree( GetProcessHeap(), 0, szCmdline );
1598 LocalFree( dar );
1601 IShellLinkDataList_Release( dl );
1602 return hr;
1605 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1607 HRESULT hr;
1608 WCHAR *value = NULL;
1609 DWORD size = 0;
1610 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1611 if (SUCCEEDED(hr))
1613 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1614 if (value)
1616 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1617 if (FAILED(hr))
1619 HeapFree(GetProcessHeap(), 0, value);
1620 value = NULL;
1624 return value;
1627 static char *slashes_to_minuses(const char *string)
1629 int i;
1630 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1631 if (ret)
1633 for (i = 0; string[i]; i++)
1635 if (string[i] == '/')
1636 ret[i] = '-';
1637 else
1638 ret[i] = string[i];
1640 ret[i] = 0;
1641 return ret;
1643 return NULL;
1646 static BOOL next_line(FILE *file, char **line, int *size)
1648 int pos = 0;
1649 char *cr;
1650 if (*line == NULL)
1652 *size = 4096;
1653 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1655 while (*line != NULL)
1657 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1659 HeapFree(GetProcessHeap(), 0, *line);
1660 *line = NULL;
1661 if (feof(file))
1662 return TRUE;
1663 return FALSE;
1665 pos = strlen(*line);
1666 cr = strchr(*line, '\n');
1667 if (cr == NULL)
1669 char *line2;
1670 (*size) *= 2;
1671 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1672 if (line2)
1673 *line = line2;
1674 else
1676 HeapFree(GetProcessHeap(), 0, *line);
1677 *line = NULL;
1680 else
1682 *cr = 0;
1683 return TRUE;
1686 return FALSE;
1689 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1691 char *globs_filename = NULL;
1692 BOOL ret = TRUE;
1693 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1694 if (globs_filename)
1696 FILE *globs_file = fopen(globs_filename, "r");
1697 if (globs_file) /* doesn't have to exist */
1699 char *line = NULL;
1700 int size = 0;
1701 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1703 char *pos;
1704 struct xdg_mime_type *mime_type_entry = NULL;
1705 if (line[0] != '#' && (pos = strchr(line, ':')))
1707 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1708 if (mime_type_entry)
1710 *pos = 0;
1711 mime_type_entry->mimeType = strdupA(line);
1712 mime_type_entry->glob = strdupA(pos + 1);
1713 if (mime_type_entry->mimeType && mime_type_entry->glob)
1714 list_add_tail(mime_types, &mime_type_entry->entry);
1715 else
1717 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1718 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1719 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1720 ret = FALSE;
1723 else
1724 ret = FALSE;
1727 HeapFree(GetProcessHeap(), 0, line);
1728 fclose(globs_file);
1730 HeapFree(GetProcessHeap(), 0, globs_filename);
1732 else
1733 ret = FALSE;
1734 return ret;
1737 static void free_native_mime_types(struct list *native_mime_types)
1739 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1741 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1743 list_remove(&mime_type_entry->entry);
1744 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1745 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1746 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1748 HeapFree(GetProcessHeap(), 0, native_mime_types);
1751 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1753 char *xdg_data_dirs;
1754 BOOL ret;
1756 *mime_types = NULL;
1758 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1759 if (xdg_data_dirs == NULL)
1760 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1761 else
1762 xdg_data_dirs = strdupA(xdg_data_dirs);
1764 if (xdg_data_dirs)
1766 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1767 if (*mime_types)
1769 const char *begin;
1770 char *end;
1772 list_init(*mime_types);
1773 ret = add_mimes(xdg_data_home, *mime_types);
1774 if (ret)
1776 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1778 *end = '\0';
1779 ret = add_mimes(begin, *mime_types);
1780 *end = ':';
1781 if (!ret)
1782 break;
1784 if (ret)
1785 ret = add_mimes(begin, *mime_types);
1788 else
1789 ret = FALSE;
1790 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1792 else
1793 ret = FALSE;
1794 if (!ret && *mime_types)
1796 free_native_mime_types(*mime_types);
1797 *mime_types = NULL;
1799 return ret;
1802 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1803 char **match)
1805 #ifdef HAVE_FNMATCH
1806 struct xdg_mime_type *mime_type_entry;
1807 int matchLength = 0;
1809 *match = NULL;
1811 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1813 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1815 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1817 *match = mime_type_entry->mimeType;
1818 matchLength = strlen(mime_type_entry->glob);
1823 if (*match != NULL)
1825 *match = strdupA(*match);
1826 if (*match == NULL)
1827 return FALSE;
1829 #else
1830 *match = NULL;
1831 #endif
1832 return TRUE;
1835 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1836 const char *extensionA,
1837 LPCWSTR extensionW,
1838 char **mime_type)
1840 WCHAR *lower_extensionW;
1841 INT len;
1842 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1843 if (ret == FALSE || *mime_type != NULL)
1844 return ret;
1845 len = strlenW(extensionW);
1846 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1847 if (lower_extensionW)
1849 char *lower_extensionA;
1850 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1851 strlwrW(lower_extensionW);
1852 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1853 if (lower_extensionA)
1855 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1856 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1858 else
1860 ret = FALSE;
1861 WINE_FIXME("out of memory\n");
1863 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1865 else
1867 ret = FALSE;
1868 WINE_FIXME("out of memory\n");
1870 return ret;
1873 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1875 DWORD size;
1876 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1878 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1879 if (ret)
1881 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1882 return ret;
1884 HeapFree(GetProcessHeap(), 0, ret);
1886 return NULL;
1889 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
1891 WCHAR *valW = reg_get_valW(key, subkey, name);
1892 if (valW)
1894 char *val = wchars_to_utf8_chars(valW);
1895 HeapFree(GetProcessHeap(), 0, valW);
1896 return val;
1898 return NULL;
1901 static HKEY open_associations_reg_key(void)
1903 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1904 '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};
1905 HKEY assocKey;
1906 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1907 return assocKey;
1908 return NULL;
1911 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1913 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1914 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1915 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1916 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1917 HKEY assocKey;
1918 BOOL ret;
1920 if ((assocKey = open_associations_reg_key()))
1922 CHAR *valueA;
1923 WCHAR *value;
1925 ret = FALSE;
1927 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
1928 if (!valueA || lstrcmpA(valueA, mimeType))
1929 ret = TRUE;
1930 HeapFree(GetProcessHeap(), 0, valueA);
1932 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1933 if (!value || strcmpW(value, progId))
1934 ret = TRUE;
1935 HeapFree(GetProcessHeap(), 0, value);
1937 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
1938 if (!valueA || lstrcmpA(valueA, appName))
1939 ret = TRUE;
1940 HeapFree(GetProcessHeap(), 0, valueA);
1942 value = reg_get_valW(assocKey, extensionW, DocNameW);
1943 if (docName && (!value || strcmpW(value, docName)))
1944 ret = TRUE;
1945 HeapFree(GetProcessHeap(), 0, value);
1947 RegCloseKey(assocKey);
1949 else
1951 WINE_ERR("error opening associations registry key\n");
1952 ret = FALSE;
1954 return ret;
1957 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1959 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1960 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1961 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1962 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1963 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
1964 HKEY assocKey = NULL;
1965 HKEY subkey = NULL;
1966 WCHAR *mimeTypeW = NULL;
1967 WCHAR *appNameW = NULL;
1968 WCHAR *desktopFileW = NULL;
1970 assocKey = open_associations_reg_key();
1971 if (assocKey == NULL)
1973 WINE_ERR("could not open file associations key\n");
1974 goto done;
1977 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
1979 WINE_ERR("could not create extension subkey\n");
1980 goto done;
1983 mimeTypeW = utf8_chars_to_wchars(mimeType);
1984 if (mimeTypeW == NULL)
1986 WINE_ERR("out of memory\n");
1987 goto done;
1990 appNameW = utf8_chars_to_wchars(appName);
1991 if (appNameW == NULL)
1993 WINE_ERR("out of memory\n");
1994 goto done;
1997 desktopFileW = utf8_chars_to_wchars(desktopFile);
1998 if (desktopFileW == NULL)
2000 WINE_ERR("out of memory\n");
2001 goto done;
2004 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2005 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2006 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2007 if (docName)
2008 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
2009 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2011 done:
2012 RegCloseKey(assocKey);
2013 RegCloseKey(subkey);
2014 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2015 HeapFree(GetProcessHeap(), 0, appNameW);
2016 HeapFree(GetProcessHeap(), 0, desktopFileW);
2019 static BOOL cleanup_associations(void)
2021 static const WCHAR openW[] = {'o','p','e','n',0};
2022 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2023 HKEY assocKey;
2024 BOOL hasChanged = FALSE;
2025 if ((assocKey = open_associations_reg_key()))
2027 int i;
2028 BOOL done = FALSE;
2029 for (i = 0; !done; i++)
2031 WCHAR *extensionW = NULL;
2032 DWORD size = 1024;
2033 LSTATUS ret;
2037 HeapFree(GetProcessHeap(), 0, extensionW);
2038 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2039 if (extensionW == NULL)
2041 WINE_ERR("out of memory\n");
2042 ret = ERROR_OUTOFMEMORY;
2043 break;
2045 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2046 size *= 2;
2047 } while (ret == ERROR_MORE_DATA);
2049 if (ret == ERROR_SUCCESS)
2051 WCHAR *command;
2052 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2053 if (command == NULL)
2055 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2056 if (desktopFile)
2058 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2059 remove(desktopFile);
2061 RegDeleteKeyW(assocKey, extensionW);
2062 hasChanged = TRUE;
2063 HeapFree(GetProcessHeap(), 0, desktopFile);
2065 HeapFree(GetProcessHeap(), 0, command);
2067 else
2069 if (ret != ERROR_NO_MORE_ITEMS)
2070 WINE_ERR("error %d while reading registry\n", ret);
2071 done = TRUE;
2073 HeapFree(GetProcessHeap(), 0, extensionW);
2075 RegCloseKey(assocKey);
2077 else
2078 WINE_ERR("could not open file associations key\n");
2079 return hasChanged;
2082 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2083 const char *mime_type, const char *comment)
2085 BOOL ret = FALSE;
2086 char *filename;
2088 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2089 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2091 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2092 if (filename)
2094 FILE *packageFile = fopen(filename, "w");
2095 if (packageFile)
2097 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2098 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2099 fprintf(packageFile, " <mime-type type=\"");
2100 write_xml_text(packageFile, mime_type);
2101 fprintf(packageFile, "\">\n");
2102 fprintf(packageFile, " <glob pattern=\"*");
2103 write_xml_text(packageFile, dot_extension);
2104 fprintf(packageFile, "\"/>\n");
2105 if (comment)
2107 fprintf(packageFile, " <comment>");
2108 write_xml_text(packageFile, comment);
2109 fprintf(packageFile, "</comment>\n");
2111 fprintf(packageFile, " </mime-type>\n");
2112 fprintf(packageFile, "</mime-info>\n");
2113 ret = TRUE;
2114 fclose(packageFile);
2116 else
2117 WINE_ERR("error writing file %s\n", filename);
2118 HeapFree(GetProcessHeap(), 0, filename);
2120 else
2121 WINE_ERR("out of memory\n");
2122 return ret;
2125 static BOOL is_extension_blacklisted(LPCWSTR extension)
2127 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2128 static const WCHAR comW[] = {'.','c','o','m',0};
2129 static const WCHAR exeW[] = {'.','e','x','e',0};
2130 static const WCHAR msiW[] = {'.','m','s','i',0};
2132 if (!strcmpiW(extension, comW) ||
2133 !strcmpiW(extension, exeW) ||
2134 !strcmpiW(extension, msiW))
2135 return TRUE;
2136 return FALSE;
2139 static const char* get_special_mime_type(LPCWSTR extension)
2141 static const WCHAR lnkW[] = {'.','l','n','k',0};
2142 if (!strcmpiW(extension, lnkW))
2143 return "application/x-ms-shortcut";
2144 return NULL;
2147 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2148 const char *friendlyAppName, const char *mimeType,
2149 const char *progId)
2151 BOOL ret = FALSE;
2152 FILE *desktop;
2154 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
2155 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2156 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
2158 desktop = fopen(desktopPath, "w");
2159 if (desktop)
2161 fprintf(desktop, "[Desktop Entry]\n");
2162 fprintf(desktop, "Type=Application\n");
2163 fprintf(desktop, "Name=%s\n", friendlyAppName);
2164 fprintf(desktop, "MimeType=%s\n", mimeType);
2165 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
2166 fprintf(desktop, "NoDisplay=true\n");
2167 fprintf(desktop, "StartupNotify=true\n");
2168 ret = TRUE;
2169 fclose(desktop);
2171 else
2172 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2173 return ret;
2176 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2178 static const WCHAR openW[] = {'o','p','e','n',0};
2179 struct list *nativeMimeTypes = NULL;
2180 LSTATUS ret = 0;
2181 int i;
2182 BOOL hasChanged = FALSE;
2184 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2186 WINE_ERR("could not build native MIME types\n");
2187 return FALSE;
2190 for (i = 0; ; i++)
2192 WCHAR *extensionW = NULL;
2193 DWORD size = 1024;
2197 HeapFree(GetProcessHeap(), 0, extensionW);
2198 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2199 if (extensionW == NULL)
2201 WINE_ERR("out of memory\n");
2202 ret = ERROR_OUTOFMEMORY;
2203 break;
2205 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2206 size *= 2;
2207 } while (ret == ERROR_MORE_DATA);
2209 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2211 char *extensionA = NULL;
2212 WCHAR *commandW = NULL;
2213 WCHAR *friendlyDocNameW = NULL;
2214 char *friendlyDocNameA = NULL;
2215 WCHAR *iconW = NULL;
2216 char *iconA = NULL;
2217 WCHAR *contentTypeW = NULL;
2218 char *mimeTypeA = NULL;
2219 WCHAR *friendlyAppNameW = NULL;
2220 char *friendlyAppNameA = NULL;
2221 WCHAR *progIdW = NULL;
2222 char *progIdA = NULL;
2224 extensionA = wchars_to_utf8_chars(extensionW);
2225 if (extensionA == NULL)
2227 WINE_ERR("out of memory\n");
2228 goto end;
2231 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2232 if (friendlyDocNameW)
2234 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2235 if (friendlyDocNameA == NULL)
2237 WINE_ERR("out of memory\n");
2238 goto end;
2242 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2244 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2245 if (contentTypeW)
2246 strlwrW(contentTypeW);
2248 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2249 goto end;
2251 if (mimeTypeA == NULL)
2253 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2254 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2255 else if ((get_special_mime_type(extensionW)))
2256 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2257 else
2258 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2260 if (mimeTypeA != NULL)
2262 /* Gnome seems to ignore the <icon> tag in MIME packages,
2263 * and the default name is more intuitive anyway.
2265 if (iconW)
2267 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2268 if (flattened_mime)
2270 int index = 0;
2271 WCHAR *comma = strrchrW(iconW, ',');
2272 if (comma)
2274 *comma = 0;
2275 index = atoiW(comma + 1);
2277 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2278 HeapFree(GetProcessHeap(), 0, flattened_mime);
2282 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2283 hasChanged = TRUE;
2285 else
2287 WINE_FIXME("out of memory\n");
2288 goto end;
2292 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2293 if (commandW == NULL)
2294 /* no command => no application is associated */
2295 goto end;
2297 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2298 if (friendlyAppNameW)
2300 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2301 if (friendlyAppNameA == NULL)
2303 WINE_ERR("out of memory\n");
2304 goto end;
2307 else
2309 friendlyAppNameA = heap_printf("A Wine application");
2310 if (friendlyAppNameA == NULL)
2312 WINE_ERR("out of memory\n");
2313 goto end;
2317 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2318 if (progIdW)
2320 progIdA = escape(progIdW);
2321 if (progIdA == NULL)
2323 WINE_ERR("out of memory\n");
2324 goto end;
2327 else
2328 goto end; /* no progID => not a file type association */
2330 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2332 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2333 if (desktopPath)
2335 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2337 hasChanged = TRUE;
2338 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2340 HeapFree(GetProcessHeap(), 0, desktopPath);
2344 end:
2345 HeapFree(GetProcessHeap(), 0, extensionA);
2346 HeapFree(GetProcessHeap(), 0, commandW);
2347 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2348 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2349 HeapFree(GetProcessHeap(), 0, iconW);
2350 HeapFree(GetProcessHeap(), 0, iconA);
2351 HeapFree(GetProcessHeap(), 0, contentTypeW);
2352 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2353 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2354 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2355 HeapFree(GetProcessHeap(), 0, progIdW);
2356 HeapFree(GetProcessHeap(), 0, progIdA);
2358 HeapFree(GetProcessHeap(), 0, extensionW);
2359 if (ret != ERROR_SUCCESS)
2360 break;
2363 free_native_mime_types(nativeMimeTypes);
2364 return hasChanged;
2367 static char *get_start_exe_path(void)
2369 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2370 '\\','s','t','a','r','t','.','e','x','e',0};
2371 WCHAR start_path[MAX_PATH];
2372 GetWindowsDirectoryW(start_path, MAX_PATH);
2373 lstrcatW(start_path, startW);
2374 return escape(start_path);
2377 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2379 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2380 '\\','s','t','a','r','t','.','e','x','e',0};
2381 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2382 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2383 WCHAR szTmp[INFOTIPSIZE];
2384 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2385 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2386 int iIconId = 0, r = -1;
2387 DWORD csidl = -1;
2388 HANDLE hsem = NULL;
2389 char *unix_link = NULL;
2390 char *start_path = NULL;
2392 if ( !link )
2394 WINE_ERR("Link name is null\n");
2395 return FALSE;
2398 if( !GetLinkLocation( link, &csidl, &link_name ) )
2400 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2401 return TRUE;
2403 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2405 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2406 return TRUE;
2408 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2410 szTmp[0] = 0;
2411 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2412 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2413 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2415 szTmp[0] = 0;
2416 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2417 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2418 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2420 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2421 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2422 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2423 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2425 szTmp[0] = 0;
2426 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2427 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2428 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2430 if( !szPath[0] )
2432 LPITEMIDLIST pidl = NULL;
2433 IShellLinkW_GetIDList( sl, &pidl );
2434 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2435 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2438 /* extract the icon */
2439 if( szIconPath[0] )
2440 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2441 else
2442 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2444 /* fail - try once again after parent process exit */
2445 if( !icon_name )
2447 if (bWait)
2449 WINE_WARN("Unable to extract icon, deferring.\n");
2450 goto cleanup;
2452 WINE_ERR("failed to extract icon from %s\n",
2453 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2456 unix_link = wine_get_unix_file_name(link);
2457 if (unix_link == NULL)
2459 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2460 goto cleanup;
2463 /* check the path */
2464 if( szPath[0] )
2466 static const WCHAR exeW[] = {'.','e','x','e',0};
2467 WCHAR *p;
2469 /* check for .exe extension */
2470 if (!(p = strrchrW( szPath, '.' )) ||
2471 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2472 lstrcmpiW( p, exeW ))
2474 /* Not .exe - use 'start.exe' to launch this file */
2475 p = szArgs + lstrlenW(szPath) + 2;
2476 if (szArgs[0])
2478 p[0] = ' ';
2479 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2480 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2482 else
2483 p[0] = 0;
2485 szArgs[0] = '"';
2486 lstrcpyW(szArgs + 1, szPath);
2487 p[-1] = '"';
2489 GetWindowsDirectoryW(szPath, MAX_PATH);
2490 lstrcatW(szPath, startW);
2493 /* convert app working dir */
2494 if (szWorkDir[0])
2495 work_dir = wine_get_unix_file_name( szWorkDir );
2497 else
2499 /* if there's no path... try run the link itself */
2500 lstrcpynW(szArgs, link, MAX_PATH);
2501 GetWindowsDirectoryW(szPath, MAX_PATH);
2502 lstrcatW(szPath, startW);
2505 /* escape the path and parameters */
2506 escaped_path = escape(szPath);
2507 escaped_args = escape(szArgs);
2508 description = wchars_to_utf8_chars(szDescription);
2509 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2511 WINE_ERR("out of memory allocating/escaping parameters\n");
2512 goto cleanup;
2515 start_path = get_start_exe_path();
2516 if (start_path == NULL)
2518 WINE_ERR("out of memory\n");
2519 goto cleanup;
2522 /* building multiple menus concurrently has race conditions */
2523 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2524 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2526 WINE_ERR("failed wait for semaphore\n");
2527 goto cleanup;
2530 if (in_desktop_dir(csidl))
2532 char *location;
2533 const char *lastEntry;
2534 lastEntry = strrchr(link_name, '/');
2535 if (lastEntry == NULL)
2536 lastEntry = link_name;
2537 else
2538 ++lastEntry;
2539 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2540 if (location)
2542 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2543 if (r == 0)
2544 chmod(location, 0755);
2545 HeapFree(GetProcessHeap(), 0, location);
2548 else
2550 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2551 if (unix_linkW)
2553 char *escaped_lnk = escape(unix_linkW);
2554 if (escaped_lnk)
2556 char *menuarg = heap_printf("/Unix %s", escaped_lnk);
2557 if (menuarg)
2559 r = !write_menu_entry(unix_link, link_name, start_path, menuarg, description, work_dir, icon_name);
2560 HeapFree(GetProcessHeap(), 0, menuarg);
2562 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2564 HeapFree(GetProcessHeap(), 0, unix_linkW);
2568 ReleaseSemaphore( hsem, 1, NULL );
2570 cleanup:
2571 if (hsem) CloseHandle( hsem );
2572 HeapFree( GetProcessHeap(), 0, icon_name );
2573 HeapFree( GetProcessHeap(), 0, work_dir );
2574 HeapFree( GetProcessHeap(), 0, link_name );
2575 HeapFree( GetProcessHeap(), 0, escaped_args );
2576 HeapFree( GetProcessHeap(), 0, escaped_path );
2577 HeapFree( GetProcessHeap(), 0, description );
2578 HeapFree( GetProcessHeap(), 0, unix_link );
2579 HeapFree( GetProcessHeap(), 0, start_path );
2581 if (r && !bWait)
2582 WINE_ERR("failed to build the menu\n" );
2584 return ( r == 0 );
2587 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2589 char *link_name = NULL;
2590 DWORD csidl = -1;
2591 LPWSTR urlPath;
2592 char *escaped_urlPath = NULL;
2593 HRESULT hr;
2594 HANDLE hSem = NULL;
2595 BOOL ret = TRUE;
2596 int r = -1;
2597 char *unix_link = NULL;
2599 if ( !link )
2601 WINE_ERR("Link name is null\n");
2602 return TRUE;
2605 if( !GetLinkLocation( link, &csidl, &link_name ) )
2607 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2608 return TRUE;
2610 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2612 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2613 ret = TRUE;
2614 goto cleanup;
2616 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2618 hr = url->lpVtbl->GetURL(url, &urlPath);
2619 if (FAILED(hr))
2621 ret = TRUE;
2622 goto cleanup;
2624 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2626 unix_link = wine_get_unix_file_name(link);
2627 if (unix_link == NULL)
2629 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2630 goto cleanup;
2633 escaped_urlPath = escape(urlPath);
2634 if (escaped_urlPath == NULL)
2636 WINE_ERR("couldn't escape url, out of memory\n");
2637 goto cleanup;
2640 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2641 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2643 WINE_ERR("failed wait for semaphore\n");
2644 goto cleanup;
2646 if (in_desktop_dir(csidl))
2648 char *location;
2649 const char *lastEntry;
2650 lastEntry = strrchr(link_name, '/');
2651 if (lastEntry == NULL)
2652 lastEntry = link_name;
2653 else
2654 ++lastEntry;
2655 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2656 if (location)
2658 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2659 if (r == 0)
2660 chmod(location, 0755);
2661 HeapFree(GetProcessHeap(), 0, location);
2664 else
2665 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2666 ret = (r != 0);
2667 ReleaseSemaphore(hSem, 1, NULL);
2669 cleanup:
2670 if (hSem)
2671 CloseHandle(hSem);
2672 HeapFree(GetProcessHeap(), 0, link_name);
2673 CoTaskMemFree( urlPath );
2674 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2675 HeapFree(GetProcessHeap(), 0, unix_link);
2676 return ret;
2679 static BOOL WaitForParentProcess( void )
2681 PROCESSENTRY32 procentry;
2682 HANDLE hsnapshot = NULL, hprocess = NULL;
2683 DWORD ourpid = GetCurrentProcessId();
2684 BOOL ret = FALSE, rc;
2686 WINE_TRACE("Waiting for parent process\n");
2687 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2688 INVALID_HANDLE_VALUE)
2690 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2691 goto done;
2694 procentry.dwSize = sizeof(PROCESSENTRY32);
2695 rc = Process32First( hsnapshot, &procentry );
2696 while (rc)
2698 if (procentry.th32ProcessID == ourpid) break;
2699 rc = Process32Next( hsnapshot, &procentry );
2701 if (!rc)
2703 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2704 goto done;
2707 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2708 NULL)
2710 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2711 GetLastError());
2712 goto done;
2715 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2716 ret = TRUE;
2717 else
2718 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2720 done:
2721 if (hprocess) CloseHandle( hprocess );
2722 if (hsnapshot) CloseHandle( hsnapshot );
2723 return ret;
2726 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2728 IShellLinkW *sl;
2729 IPersistFile *pf;
2730 HRESULT r;
2731 WCHAR fullname[MAX_PATH];
2732 DWORD len;
2734 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2736 if( !linkname[0] )
2738 WINE_ERR("link name missing\n");
2739 return 1;
2742 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2743 if (len==0 || len>MAX_PATH)
2745 WINE_ERR("couldn't get full path of link file\n");
2746 return 1;
2749 r = CoInitialize( NULL );
2750 if( FAILED( r ) )
2752 WINE_ERR("CoInitialize failed\n");
2753 return 1;
2756 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2757 &IID_IShellLinkW, (LPVOID *) &sl );
2758 if( FAILED( r ) )
2760 WINE_ERR("No IID_IShellLink\n");
2761 return 1;
2764 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2765 if( FAILED( r ) )
2767 WINE_ERR("No IID_IPersistFile\n");
2768 return 1;
2771 r = IPersistFile_Load( pf, fullname, STGM_READ );
2772 if( SUCCEEDED( r ) )
2774 /* If something fails (eg. Couldn't extract icon)
2775 * wait for parent process and try again
2777 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2779 WaitForParentProcess();
2780 InvokeShellLinker( sl, fullname, FALSE );
2783 else
2785 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2788 IPersistFile_Release( pf );
2789 IShellLinkW_Release( sl );
2791 CoUninitialize();
2793 return !r;
2796 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2798 IUniformResourceLocatorW *url;
2799 IPersistFile *pf;
2800 HRESULT r;
2801 WCHAR fullname[MAX_PATH];
2802 DWORD len;
2804 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2806 if( !urlname[0] )
2808 WINE_ERR("URL name missing\n");
2809 return 1;
2812 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2813 if (len==0 || len>MAX_PATH)
2815 WINE_ERR("couldn't get full path of URL file\n");
2816 return 1;
2819 r = CoInitialize( NULL );
2820 if( FAILED( r ) )
2822 WINE_ERR("CoInitialize failed\n");
2823 return 1;
2826 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2827 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2828 if( FAILED( r ) )
2830 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2831 return 1;
2834 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2835 if( FAILED( r ) )
2837 WINE_ERR("No IID_IPersistFile\n");
2838 return 1;
2840 r = IPersistFile_Load( pf, fullname, STGM_READ );
2841 if( SUCCEEDED( r ) )
2843 /* If something fails (eg. Couldn't extract icon)
2844 * wait for parent process and try again
2846 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2848 WaitForParentProcess();
2849 InvokeShellLinkerForURL( url, fullname, FALSE );
2853 IPersistFile_Release( pf );
2854 url->lpVtbl->Release( url );
2856 CoUninitialize();
2858 return !r;
2861 static void RefreshFileTypeAssociations(void)
2863 HANDLE hSem = NULL;
2864 char *mime_dir = NULL;
2865 char *packages_dir = NULL;
2866 char *applications_dir = NULL;
2867 BOOL hasChanged;
2869 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2870 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2872 WINE_ERR("failed wait for semaphore\n");
2873 CloseHandle(hSem);
2874 hSem = NULL;
2875 goto end;
2878 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2879 if (mime_dir == NULL)
2881 WINE_ERR("out of memory\n");
2882 goto end;
2884 create_directories(mime_dir);
2886 packages_dir = heap_printf("%s/packages", mime_dir);
2887 if (packages_dir == NULL)
2889 WINE_ERR("out of memory\n");
2890 goto end;
2892 create_directories(packages_dir);
2894 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2895 if (applications_dir == NULL)
2897 WINE_ERR("out of memory\n");
2898 goto end;
2900 create_directories(applications_dir);
2902 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2903 hasChanged |= cleanup_associations();
2904 if (hasChanged)
2906 const char *argv[3];
2908 argv[0] = "update-mime-database";
2909 argv[1] = mime_dir;
2910 argv[2] = NULL;
2911 spawnvp( _P_NOWAIT, argv[0], argv );
2913 argv[0] = "update-desktop-database";
2914 argv[1] = applications_dir;
2915 spawnvp( _P_NOWAIT, argv[0], argv );
2918 end:
2919 if (hSem)
2921 ReleaseSemaphore(hSem, 1, NULL);
2922 CloseHandle(hSem);
2924 HeapFree(GetProcessHeap(), 0, mime_dir);
2925 HeapFree(GetProcessHeap(), 0, packages_dir);
2926 HeapFree(GetProcessHeap(), 0, applications_dir);
2929 static void cleanup_menus(void)
2931 HKEY hkey;
2933 hkey = open_menus_reg_key();
2934 if (hkey)
2936 int i;
2937 LSTATUS lret = ERROR_SUCCESS;
2938 for (i = 0; lret == ERROR_SUCCESS; )
2940 WCHAR *value = NULL;
2941 WCHAR *data = NULL;
2942 DWORD valueSize = 4096;
2943 DWORD dataSize = 4096;
2944 while (1)
2946 lret = ERROR_OUTOFMEMORY;
2947 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
2948 if (value == NULL)
2949 break;
2950 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
2951 if (data == NULL)
2952 break;
2953 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2954 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2955 break;
2956 valueSize *= 2;
2957 dataSize *= 2;
2958 HeapFree(GetProcessHeap(), 0, value);
2959 HeapFree(GetProcessHeap(), 0, data);
2960 value = data = NULL;
2962 if (lret == ERROR_SUCCESS)
2964 char *unix_file;
2965 char *windows_file;
2966 unix_file = wchars_to_unix_chars(value);
2967 windows_file = wchars_to_unix_chars(data);
2968 if (unix_file != NULL && windows_file != NULL)
2970 struct stat filestats;
2971 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
2973 WINE_TRACE("removing menu related file %s\n", unix_file);
2974 remove(unix_file);
2975 RegDeleteValueW(hkey, value);
2977 else
2978 i++;
2980 else
2982 WINE_ERR("out of memory enumerating menus\n");
2983 lret = ERROR_OUTOFMEMORY;
2985 HeapFree(GetProcessHeap(), 0, unix_file);
2986 HeapFree(GetProcessHeap(), 0, windows_file);
2988 else if (lret != ERROR_NO_MORE_ITEMS)
2989 WINE_ERR("error %d reading registry\n", lret);
2990 HeapFree(GetProcessHeap(), 0, value);
2991 HeapFree(GetProcessHeap(), 0, data);
2993 RegCloseKey(hkey);
2995 else
2996 WINE_ERR("error opening registry key, menu cleanup failed\n");
2999 static WCHAR *next_token( LPWSTR *p )
3001 LPWSTR token = NULL, t = *p;
3003 if( !t )
3004 return NULL;
3006 while( t && !token )
3008 switch( *t )
3010 case ' ':
3011 t++;
3012 continue;
3013 case '"':
3014 /* unquote the token */
3015 token = ++t;
3016 t = strchrW( token, '"' );
3017 if( t )
3018 *t++ = 0;
3019 break;
3020 case 0:
3021 t = NULL;
3022 break;
3023 default:
3024 token = t;
3025 t = strchrW( token, ' ' );
3026 if( t )
3027 *t++ = 0;
3028 break;
3031 *p = t;
3032 return token;
3035 static BOOL init_xdg(void)
3037 WCHAR shellDesktopPath[MAX_PATH];
3038 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3039 if (SUCCEEDED(hr))
3040 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3041 if (xdg_desktop_dir == NULL)
3043 WINE_ERR("error looking up the desktop directory\n");
3044 return FALSE;
3047 if (getenv("XDG_CONFIG_HOME"))
3048 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3049 else
3050 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3051 if (xdg_config_dir)
3053 create_directories(xdg_config_dir);
3054 if (getenv("XDG_DATA_HOME"))
3055 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3056 else
3057 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3058 if (xdg_data_dir)
3060 char *buffer;
3061 create_directories(xdg_data_dir);
3062 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3063 if (buffer)
3065 mkdir(buffer, 0777);
3066 HeapFree(GetProcessHeap(), 0, buffer);
3068 return TRUE;
3070 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3072 WINE_ERR("out of memory\n");
3073 return FALSE;
3076 /***********************************************************************
3078 * wWinMain
3080 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3082 static const WCHAR dash_aW[] = {'-','a',0};
3083 static const WCHAR dash_rW[] = {'-','r',0};
3084 static const WCHAR dash_uW[] = {'-','u',0};
3085 static const WCHAR dash_wW[] = {'-','w',0};
3087 LPWSTR token = NULL, p;
3088 BOOL bWait = FALSE;
3089 BOOL bURL = FALSE;
3090 int ret = 0;
3092 if (!init_xdg())
3093 return 1;
3095 for( p = cmdline; p && *p; )
3097 token = next_token( &p );
3098 if( !token )
3099 break;
3100 if( !strcmpW( token, dash_aW ) )
3102 RefreshFileTypeAssociations();
3103 continue;
3105 if( !strcmpW( token, dash_rW ) )
3107 cleanup_menus();
3108 continue;
3110 if( !strcmpW( token, dash_wW ) )
3111 bWait = TRUE;
3112 else if ( !strcmpW( token, dash_uW ) )
3113 bURL = TRUE;
3114 else if( token[0] == '-' )
3116 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3118 else
3120 BOOL bRet;
3122 if (bURL)
3123 bRet = Process_URL( token, bWait );
3124 else
3125 bRet = Process_Link( token, bWait );
3126 if (!bRet)
3128 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3129 ret = 1;
3134 return ret;