wininet: Implement InternetQueryOption(INTERNET_OPTION_CONTEXT_VALUE).
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blob413e5ded155445510ed2e421dddb1038217d2ab7
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 return SavePalettedIconResAsPNG(pIcon, png_filename, commentW);
509 case 8:
510 return SavePalettedIconResAsPNG(pIcon, png_filename, commentW);
511 case 24:
512 return SaveTrueColorIconResAsPNG(pIcon, png_filename, commentW);
513 case 32:
514 return SaveTrueColorIconResAsPNG(pIcon, png_filename, commentW);
515 default:
516 WINE_FIXME("unsupported bpp %d, please report", pIcon->bmiHeader.biBitCount);
517 return FALSE;
520 #endif /* SONAME_LIBPNG */
522 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
524 FILE *fXPMFile;
525 int nHeight;
526 int nXORWidthBytes;
527 int nANDWidthBytes;
528 BOOL b8BitColors;
529 int nColors;
530 const BYTE *pXOR;
531 const BYTE *pAND;
532 BOOL aColorUsed[256] = {0};
533 int nColorsUsed = 0;
534 int i,j;
535 char *comment;
537 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
539 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
540 return FALSE;
543 if (!(fXPMFile = fopen(szXPMFileName, "w")))
545 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
546 return FALSE;
549 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
550 comment = HeapAlloc(GetProcessHeap(), 0, i);
551 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
553 nHeight = pIcon->bmiHeader.biHeight / 2;
554 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
555 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
556 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
557 + ((pIcon->bmiHeader.biWidth % 32) > 0));
558 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
559 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
560 : 1 << pIcon->bmiHeader.biBitCount;
561 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
562 pAND = pXOR + nHeight * nXORWidthBytes;
564 #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)
566 for (i = 0; i < nHeight; i++) {
567 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
568 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
570 aColorUsed[COLOR(j,i)] = TRUE;
571 nColorsUsed++;
576 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
577 goto error;
578 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
579 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
580 goto error;
582 for (i = 0; i < nColors; i++) {
583 if (aColorUsed[i])
584 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
585 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
586 goto error;
588 if (fprintf(fXPMFile, "\" c None\"") <= 0)
589 goto error;
591 for (i = 0; i < nHeight; i++)
593 if (fprintf(fXPMFile, ",\n\"") <= 0)
594 goto error;
595 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
597 if MASK(j,i)
599 if (fprintf(fXPMFile, " ") <= 0)
600 goto error;
602 else
603 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
604 goto error;
606 if (fprintf(fXPMFile, "\"") <= 0)
607 goto error;
609 if (fprintf(fXPMFile, "};\n") <= 0)
610 goto error;
612 #undef MASK
613 #undef COLOR
615 HeapFree(GetProcessHeap(), 0, comment);
616 fclose(fXPMFile);
617 return TRUE;
619 error:
620 HeapFree(GetProcessHeap(), 0, comment);
621 fclose(fXPMFile);
622 unlink( szXPMFileName );
623 return FALSE;
626 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
628 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
630 if (!sEnumRes->nIndex--)
632 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
633 return FALSE;
635 else
636 return TRUE;
639 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
641 HMODULE hModule;
642 HRSRC hResInfo;
643 LPCWSTR lpName = NULL;
644 HGLOBAL hResData;
645 GRPICONDIR *pIconDir;
646 BITMAPINFO *pIcon;
647 ENUMRESSTRUCT sEnumRes;
648 int nMax = 0;
649 int nMaxBits = 0;
650 int i;
651 BOOL ret = FALSE;
653 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
654 if (!hModule)
656 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
657 wine_dbgstr_w(szFileName), GetLastError());
658 return FALSE;
661 if (nIndex < 0)
663 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
664 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
665 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
667 else
669 hResInfo=NULL;
670 sEnumRes.pResInfo = &hResInfo;
671 sEnumRes.nIndex = nIndex;
672 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
673 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
674 sEnumRes.nIndex != -1)
676 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
680 if (hResInfo)
682 if ((hResData = LoadResource(hModule, hResInfo)))
684 if ((pIconDir = LockResource(hResData)))
686 for (i = 0; i < pIconDir->idCount; i++)
688 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
690 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
692 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
693 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
694 nMaxBits = pIconDir->idEntries[i].wBitCount;
700 FreeResource(hResData);
703 else
705 WINE_WARN("found no icon\n");
706 FreeLibrary(hModule);
707 return FALSE;
710 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
712 if ((hResData = LoadResource(hModule, hResInfo)))
714 if ((pIcon = LockResource(hResData)))
716 #ifdef SONAME_LIBPNG
717 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
718 ret = TRUE;
719 else
720 #endif
722 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
723 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
724 ret = TRUE;
728 FreeResource(hResData);
732 FreeLibrary(hModule);
733 return ret;
736 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
738 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
739 !extract_icon16(szFileName, szXPMFileName)*/)
740 return FALSE;
741 return TRUE;
744 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
746 FILE *fICOFile = NULL;
747 ICONDIR iconDir;
748 ICONDIRENTRY *pIconDirEntry = NULL;
749 int nMax = 0, nMaxBits = 0;
750 int nIndex = 0;
751 void *pIcon = NULL;
752 int i;
753 char *filename = NULL;
755 filename = wine_get_unix_file_name(szFileName);
756 if (!(fICOFile = fopen(filename, "r")))
758 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
759 goto error;
762 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
763 (iconDir.idReserved != 0) || (iconDir.idType != 1))
765 WINE_WARN("Invalid ico file format\n");
766 goto error;
769 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
770 goto error;
771 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
772 goto error;
774 for (i = 0; i < iconDir.idCount; i++)
776 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
777 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
778 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
780 nIndex = i;
781 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
782 nMaxBits = pIconDirEntry[i].wBitCount;
785 WINE_TRACE("Selected: %d\n", nIndex);
787 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
788 goto error;
789 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
790 goto error;
791 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
792 goto error;
795 /* Prefer PNG over XPM */
796 #ifdef SONAME_LIBPNG
797 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
798 #endif
800 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
801 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
802 goto error;
805 HeapFree(GetProcessHeap(), 0, pIcon);
806 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
807 fclose(fICOFile);
808 HeapFree(GetProcessHeap(), 0, filename);
809 return 1;
811 error:
812 HeapFree(GetProcessHeap(), 0, pIcon);
813 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
814 if (fICOFile) fclose(fICOFile);
815 HeapFree(GetProcessHeap(), 0, filename);
816 return 0;
819 static BOOL create_default_icon( const char *filename, const char* comment )
821 FILE *fXPM;
822 unsigned int i;
824 if (!(fXPM = fopen(filename, "w"))) return FALSE;
825 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
826 goto error;
827 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
828 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
829 goto error;
831 if (fprintf( fXPM, "};\n" ) <=0)
832 goto error;
833 fclose( fXPM );
834 return TRUE;
835 error:
836 fclose( fXPM );
837 unlink( filename );
838 return FALSE;
842 static unsigned short crc16(const char* string)
844 unsigned short crc = 0;
845 int i, j, xor_poly;
847 for (i = 0; string[i] != 0; i++)
849 char c = string[i];
850 for (j = 0; j < 8; c >>= 1, j++)
852 xor_poly = (c ^ crc) & 1;
853 crc >>= 1;
854 if (xor_poly)
855 crc ^= 0xa001;
858 return crc;
861 static char *strdupA( const char *str )
863 char *ret;
865 if (!str) return NULL;
866 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
867 return ret;
870 static char* heap_printf(const char *format, ...)
872 va_list args;
873 int size = 4096;
874 char *buffer, *ret;
875 int n;
877 va_start(args, format);
878 while (1)
880 buffer = HeapAlloc(GetProcessHeap(), 0, size);
881 if (buffer == NULL)
882 break;
883 n = vsnprintf(buffer, size, format, args);
884 if (n == -1)
885 size *= 2;
886 else if (n >= size)
887 size = n + 1;
888 else
889 break;
890 HeapFree(GetProcessHeap(), 0, buffer);
892 va_end(args);
893 if (!buffer) return NULL;
894 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
895 if (!ret) ret = buffer;
896 return ret;
899 static void write_xml_text(FILE *file, const char *text)
901 int i;
902 for (i = 0; text[i]; i++)
904 if (text[i] == '&')
905 fputs("&amp;", file);
906 else if (text[i] == '<')
907 fputs("&lt;", file);
908 else if (text[i] == '>')
909 fputs("&gt;", file);
910 else if (text[i] == '\'')
911 fputs("&apos;", file);
912 else if (text[i] == '"')
913 fputs("&quot;", file);
914 else
915 fputc(text[i], file);
919 static BOOL create_directories(char *directory)
921 BOOL ret = TRUE;
922 int i;
924 for (i = 0; directory[i]; i++)
926 if (i > 0 && directory[i] == '/')
928 directory[i] = 0;
929 mkdir(directory, 0777);
930 directory[i] = '/';
933 if (mkdir(directory, 0777) && errno != EEXIST)
934 ret = FALSE;
936 return ret;
939 static char* wchars_to_utf8_chars(LPCWSTR string)
941 char *ret;
942 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
943 ret = HeapAlloc(GetProcessHeap(), 0, size);
944 if (ret)
945 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
946 return ret;
949 static char* wchars_to_unix_chars(LPCWSTR string)
951 char *ret;
952 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
953 ret = HeapAlloc(GetProcessHeap(), 0, size);
954 if (ret)
955 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
956 return ret;
959 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
961 WCHAR *ret;
962 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
963 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
964 if (ret)
965 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
966 return ret;
969 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
970 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
972 unsigned short crc;
973 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
974 char* s;
975 int n;
977 /* Where should we save the icon? */
978 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
979 iconsdir = heap_printf("%s/icons", xdg_data_dir);
980 if (iconsdir)
982 if (mkdir(iconsdir, 0777) && errno != EEXIST)
984 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
985 goto end;
988 else
990 WINE_TRACE("no icon created\n");
991 return NULL;
994 /* Determine the icon base name */
995 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
996 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
997 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
998 s=ico_name=ico_path;
999 while (*s!='\0') {
1000 if (*s=='/' || *s=='\\') {
1001 *s='\\';
1002 ico_name=s;
1003 } else {
1004 *s=tolower(*s);
1006 s++;
1008 if (*ico_name=='\\') *ico_name++='\0';
1009 s=strrchr(ico_name,'.');
1010 if (s) *s='\0';
1012 /* Compute the source-path hash */
1013 crc=crc16(ico_path);
1015 /* Try to treat the source file as an exe */
1016 if (destFilename)
1017 xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
1018 else
1019 xpm_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
1020 if (xpm_path == NULL)
1022 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
1023 return NULL;
1026 if (ExtractFromEXEDLL( path, index, xpm_path ))
1027 goto end;
1029 /* Must be something else, ignore the index in that case */
1030 if (destFilename)
1031 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
1032 else
1033 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
1034 if (ExtractFromICO( path, xpm_path))
1035 goto end;
1036 if (!bWait)
1038 if (destFilename)
1039 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
1040 else
1041 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
1042 if (create_default_icon( xpm_path, ico_path ))
1043 goto end;
1046 HeapFree( GetProcessHeap(), 0, xpm_path );
1047 xpm_path=NULL;
1049 end:
1050 HeapFree(GetProcessHeap(), 0, iconsdir);
1051 HeapFree(GetProcessHeap(), 0, ico_path);
1052 return xpm_path;
1055 static HKEY open_menus_reg_key(void)
1057 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1058 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1059 HKEY assocKey;
1060 DWORD ret;
1061 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1062 if (ret == ERROR_SUCCESS)
1063 return assocKey;
1064 SetLastError(ret);
1065 return NULL;
1068 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1070 WCHAR *unix_fileW;
1071 WCHAR *windows_fileW;
1072 INT size;
1073 DWORD ret;
1075 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1076 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1077 if (unix_fileW)
1079 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1080 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1081 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1082 if (windows_fileW)
1084 HKEY hkey;
1085 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1086 hkey = open_menus_reg_key();
1087 if (hkey)
1089 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1090 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1091 RegCloseKey(hkey);
1093 else
1094 ret = GetLastError();
1095 HeapFree(GetProcessHeap(), 0, windows_fileW);
1097 else
1098 ret = ERROR_NOT_ENOUGH_MEMORY;
1099 HeapFree(GetProcessHeap(), 0, unix_fileW);
1101 else
1102 ret = ERROR_NOT_ENOUGH_MEMORY;
1103 return ret;
1106 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1107 const char *path, const char *args, const char *descr,
1108 const char *workdir, const char *icon)
1110 FILE *file;
1112 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1113 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1114 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1116 file = fopen(location, "w");
1117 if (file == NULL)
1118 return FALSE;
1120 fprintf(file, "[Desktop Entry]\n");
1121 fprintf(file, "Name=%s\n", linkname);
1122 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1123 wine_get_config_dir(), path, args);
1124 fprintf(file, "Type=Application\n");
1125 fprintf(file, "StartupNotify=true\n");
1126 if (descr && lstrlenA(descr))
1127 fprintf(file, "Comment=%s\n", descr);
1128 if (workdir && lstrlenA(workdir))
1129 fprintf(file, "Path=%s\n", workdir);
1130 if (icon && lstrlenA(icon))
1131 fprintf(file, "Icon=%s\n", icon);
1133 fclose(file);
1135 if (unix_link)
1137 DWORD ret = register_menus_entry(location, unix_link);
1138 if (ret != ERROR_SUCCESS)
1139 return FALSE;
1142 return TRUE;
1145 static BOOL write_directory_entry(const char *directory, const char *location)
1147 FILE *file;
1149 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1151 file = fopen(location, "w");
1152 if (file == NULL)
1153 return FALSE;
1155 fprintf(file, "[Desktop Entry]\n");
1156 fprintf(file, "Type=Directory\n");
1157 if (strcmp(directory, "wine") == 0)
1159 fprintf(file, "Name=Wine\n");
1160 fprintf(file, "Icon=wine\n");
1162 else
1164 fprintf(file, "Name=%s\n", directory);
1165 fprintf(file, "Icon=folder\n");
1168 fclose(file);
1169 return TRUE;
1172 static BOOL write_menu_file(const char *unix_link, const char *filename)
1174 char *tempfilename;
1175 FILE *tempfile = NULL;
1176 char *lastEntry;
1177 char *name = NULL;
1178 char *menuPath = NULL;
1179 int i;
1180 int count = 0;
1181 BOOL ret = FALSE;
1183 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1185 while (1)
1187 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1188 if (tempfilename)
1190 int tempfd = mkstemps(tempfilename, 0);
1191 if (tempfd >= 0)
1193 tempfile = fdopen(tempfd, "w");
1194 if (tempfile)
1195 break;
1196 close(tempfd);
1197 goto end;
1199 else if (errno == EEXIST)
1201 HeapFree(GetProcessHeap(), 0, tempfilename);
1202 continue;
1204 HeapFree(GetProcessHeap(), 0, tempfilename);
1206 return FALSE;
1209 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1210 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1211 fprintf(tempfile, "<Menu>\n");
1212 fprintf(tempfile, " <Name>Applications</Name>\n");
1214 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1215 if (name == NULL) goto end;
1216 lastEntry = name;
1217 for (i = 0; filename[i]; i++)
1219 name[i] = filename[i];
1220 if (filename[i] == '/')
1222 char *dir_file_name;
1223 struct stat st;
1224 name[i] = 0;
1225 fprintf(tempfile, " <Menu>\n");
1226 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1227 write_xml_text(tempfile, name);
1228 fprintf(tempfile, "</Name>\n");
1229 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1230 write_xml_text(tempfile, name);
1231 fprintf(tempfile, ".directory</Directory>\n");
1232 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1233 xdg_data_dir, count ? "" : "wine-", name);
1234 if (dir_file_name)
1236 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1237 write_directory_entry(lastEntry, dir_file_name);
1238 HeapFree(GetProcessHeap(), 0, dir_file_name);
1240 name[i] = '-';
1241 lastEntry = &name[i+1];
1242 ++count;
1245 name[i] = 0;
1247 fprintf(tempfile, " <Include>\n");
1248 fprintf(tempfile, " <Filename>");
1249 write_xml_text(tempfile, name);
1250 fprintf(tempfile, "</Filename>\n");
1251 fprintf(tempfile, " </Include>\n");
1252 for (i = 0; i < count; i++)
1253 fprintf(tempfile, " </Menu>\n");
1254 fprintf(tempfile, "</Menu>\n");
1256 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1257 if (menuPath == NULL) goto end;
1258 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1259 ret = TRUE;
1261 end:
1262 if (tempfile)
1263 fclose(tempfile);
1264 if (ret)
1265 ret = (rename(tempfilename, menuPath) == 0);
1266 if (!ret && tempfilename)
1267 remove(tempfilename);
1268 HeapFree(GetProcessHeap(), 0, tempfilename);
1269 if (ret)
1270 register_menus_entry(menuPath, unix_link);
1271 HeapFree(GetProcessHeap(), 0, name);
1272 HeapFree(GetProcessHeap(), 0, menuPath);
1273 return ret;
1276 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1277 const char *descr, const char *workdir, const char *icon)
1279 const char *linkname;
1280 char *desktopPath = NULL;
1281 char *desktopDir;
1282 char *filename = NULL;
1283 BOOL ret = TRUE;
1285 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1286 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1287 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1289 linkname = strrchr(link, '/');
1290 if (linkname == NULL)
1291 linkname = link;
1292 else
1293 ++linkname;
1295 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1296 if (!desktopPath)
1298 WINE_WARN("out of memory creating menu entry\n");
1299 ret = FALSE;
1300 goto end;
1302 desktopDir = strrchr(desktopPath, '/');
1303 *desktopDir = 0;
1304 if (!create_directories(desktopPath))
1306 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1307 ret = FALSE;
1308 goto end;
1310 *desktopDir = '/';
1311 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1313 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1314 ret = FALSE;
1315 goto end;
1318 filename = heap_printf("wine/%s.desktop", link);
1319 if (!filename || !write_menu_file(unix_link, filename))
1321 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1322 ret = FALSE;
1325 end:
1326 HeapFree(GetProcessHeap(), 0, desktopPath);
1327 HeapFree(GetProcessHeap(), 0, filename);
1328 return ret;
1331 /* This escapes reserved characters in .desktop files' Exec keys. */
1332 static LPSTR escape(LPCWSTR arg)
1334 int i, j;
1335 WCHAR *escaped_string;
1336 char *utf8_string;
1338 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1339 if (escaped_string == NULL) return NULL;
1340 for (i = j = 0; arg[i]; i++)
1342 switch (arg[i])
1344 case '\\':
1345 escaped_string[j++] = '\\';
1346 escaped_string[j++] = '\\';
1347 escaped_string[j++] = '\\';
1348 escaped_string[j++] = '\\';
1349 break;
1350 case ' ':
1351 case '\t':
1352 case '\n':
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 case ')':
1367 case '`':
1368 escaped_string[j++] = '\\';
1369 escaped_string[j++] = '\\';
1370 /* fall through */
1371 default:
1372 escaped_string[j++] = arg[i];
1373 break;
1376 escaped_string[j] = 0;
1378 utf8_string = wchars_to_utf8_chars(escaped_string);
1379 if (utf8_string == NULL)
1381 WINE_ERR("out of memory\n");
1382 goto end;
1385 end:
1386 HeapFree(GetProcessHeap(), 0, escaped_string);
1387 return utf8_string;
1390 /* Return a heap-allocated copy of the unix format difference between the two
1391 * Windows-format paths.
1392 * locn is the owning location
1393 * link is within locn
1395 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1397 char *unix_locn, *unix_link;
1398 char *relative = NULL;
1400 unix_locn = wine_get_unix_file_name(locn);
1401 unix_link = wine_get_unix_file_name(link);
1402 if (unix_locn && unix_link)
1404 size_t len_unix_locn, len_unix_link;
1405 len_unix_locn = strlen (unix_locn);
1406 len_unix_link = strlen (unix_link);
1407 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1409 size_t len_rel;
1410 char *p = strrchr (unix_link + len_unix_locn, '/');
1411 p = strrchr (p, '.');
1412 if (p)
1414 *p = '\0';
1415 len_unix_link = p - unix_link;
1417 len_rel = len_unix_link - len_unix_locn;
1418 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1419 if (relative)
1421 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1425 if (!relative)
1426 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1427 HeapFree(GetProcessHeap(), 0, unix_locn);
1428 HeapFree(GetProcessHeap(), 0, unix_link);
1429 return relative;
1432 /***********************************************************************
1434 * GetLinkLocation
1436 * returns TRUE if successful
1437 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1438 * *relative will contain the address of a heap-allocated copy of the portion
1439 * of the filename that is within the specified location, in unix form
1441 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1443 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1444 DWORD len, i, r, filelen;
1445 const DWORD locations[] = {
1446 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1447 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1448 CSIDL_COMMON_STARTMENU };
1450 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1451 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1452 if (filelen==0 || filelen>MAX_PATH)
1453 return FALSE;
1455 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1457 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1458 * expand or our hardcoded list won't match.
1460 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1461 if (filelen==0 || filelen>MAX_PATH)
1462 return FALSE;
1464 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1466 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1468 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1469 continue;
1471 len = lstrlenW(buffer);
1472 if (len >= MAX_PATH)
1473 continue; /* We've just trashed memory! Hopefully we are OK */
1475 if (len > filelen || filename[len]!='\\')
1476 continue;
1477 /* do a lstrcmpinW */
1478 filename[len] = 0;
1479 r = lstrcmpiW( filename, buffer );
1480 filename[len] = '\\';
1481 if ( r )
1482 continue;
1484 /* return the remainder of the string and link type */
1485 *loc = locations[i];
1486 *relative = relative_path (filename, buffer);
1487 return (*relative != NULL);
1490 return FALSE;
1493 /* gets the target path directly or through MSI */
1494 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1495 LPWSTR szArgs, DWORD argsSize)
1497 IShellLinkDataList *dl = NULL;
1498 EXP_DARWIN_LINK *dar = NULL;
1499 HRESULT hr;
1501 szPath[0] = 0;
1502 szArgs[0] = 0;
1504 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1505 if (hr == S_OK && szPath[0])
1507 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1508 return hr;
1511 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1512 if (FAILED(hr))
1513 return hr;
1515 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1516 if (SUCCEEDED(hr))
1518 WCHAR* szCmdline;
1519 DWORD cmdSize;
1521 cmdSize=0;
1522 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1523 if (hr == ERROR_SUCCESS)
1525 cmdSize++;
1526 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1527 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1528 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1529 if (hr == ERROR_SUCCESS)
1531 WCHAR *s, *d;
1532 int bcount, in_quotes;
1534 /* Extract the application path */
1535 bcount=0;
1536 in_quotes=0;
1537 s=szCmdline;
1538 d=szPath;
1539 while (*s)
1541 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1543 /* skip the remaining spaces */
1544 do {
1545 s++;
1546 } while (*s==0x0009 || *s==0x0020);
1547 break;
1549 else if (*s==0x005c)
1551 /* '\\' */
1552 *d++=*s++;
1553 bcount++;
1555 else if (*s==0x0022)
1557 /* '"' */
1558 if ((bcount & 1)==0)
1560 /* Preceded by an even number of '\', this is
1561 * half that number of '\', plus a quote which
1562 * we erase.
1564 d-=bcount/2;
1565 in_quotes=!in_quotes;
1566 s++;
1568 else
1570 /* Preceded by an odd number of '\', this is
1571 * half that number of '\' followed by a '"'
1573 d=d-bcount/2-1;
1574 *d++='"';
1575 s++;
1577 bcount=0;
1579 else
1581 /* a regular character */
1582 *d++=*s++;
1583 bcount=0;
1585 if ((d-szPath) == pathSize)
1587 /* Keep processing the path till we get to the
1588 * arguments, but 'stand still'
1590 d--;
1593 /* Close the application path */
1594 *d=0;
1596 lstrcpynW(szArgs, s, argsSize);
1598 HeapFree( GetProcessHeap(), 0, szCmdline );
1600 LocalFree( dar );
1603 IShellLinkDataList_Release( dl );
1604 return hr;
1607 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1609 HRESULT hr;
1610 WCHAR *value = NULL;
1611 DWORD size = 0;
1612 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1613 if (SUCCEEDED(hr))
1615 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1616 if (value)
1618 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1619 if (FAILED(hr))
1621 HeapFree(GetProcessHeap(), 0, value);
1622 value = NULL;
1626 return value;
1629 static char *slashes_to_minuses(const char *string)
1631 int i;
1632 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1633 if (ret)
1635 for (i = 0; string[i]; i++)
1637 if (string[i] == '/')
1638 ret[i] = '-';
1639 else
1640 ret[i] = string[i];
1642 ret[i] = 0;
1643 return ret;
1645 return NULL;
1648 static BOOL next_line(FILE *file, char **line, int *size)
1650 int pos = 0;
1651 char *cr;
1652 if (*line == NULL)
1654 *size = 4096;
1655 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1657 while (*line != NULL)
1659 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1661 HeapFree(GetProcessHeap(), 0, *line);
1662 *line = NULL;
1663 if (feof(file))
1664 return TRUE;
1665 return FALSE;
1667 pos = strlen(*line);
1668 cr = strchr(*line, '\n');
1669 if (cr == NULL)
1671 char *line2;
1672 (*size) *= 2;
1673 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1674 if (line2)
1675 *line = line2;
1676 else
1678 HeapFree(GetProcessHeap(), 0, *line);
1679 *line = NULL;
1682 else
1684 *cr = 0;
1685 return TRUE;
1688 return FALSE;
1691 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1693 char *globs_filename = NULL;
1694 BOOL ret = TRUE;
1695 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1696 if (globs_filename)
1698 FILE *globs_file = fopen(globs_filename, "r");
1699 if (globs_file) /* doesn't have to exist */
1701 char *line = NULL;
1702 int size = 0;
1703 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1705 char *pos;
1706 struct xdg_mime_type *mime_type_entry = NULL;
1707 if (line[0] != '#' && (pos = strchr(line, ':')))
1709 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1710 if (mime_type_entry)
1712 *pos = 0;
1713 mime_type_entry->mimeType = strdupA(line);
1714 mime_type_entry->glob = strdupA(pos + 1);
1715 if (mime_type_entry->mimeType && mime_type_entry->glob)
1716 list_add_tail(mime_types, &mime_type_entry->entry);
1717 else
1719 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1720 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1721 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1722 ret = FALSE;
1725 else
1726 ret = FALSE;
1729 HeapFree(GetProcessHeap(), 0, line);
1730 fclose(globs_file);
1732 HeapFree(GetProcessHeap(), 0, globs_filename);
1734 else
1735 ret = FALSE;
1736 return ret;
1739 static void free_native_mime_types(struct list *native_mime_types)
1741 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1743 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1745 list_remove(&mime_type_entry->entry);
1746 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1747 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1748 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1750 HeapFree(GetProcessHeap(), 0, native_mime_types);
1753 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1755 char *xdg_data_dirs;
1756 BOOL ret;
1758 *mime_types = NULL;
1760 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1761 if (xdg_data_dirs == NULL)
1762 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1763 else
1764 xdg_data_dirs = strdupA(xdg_data_dirs);
1766 if (xdg_data_dirs)
1768 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1769 if (*mime_types)
1771 const char *begin;
1772 char *end;
1774 list_init(*mime_types);
1775 ret = add_mimes(xdg_data_home, *mime_types);
1776 if (ret)
1778 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1780 *end = '\0';
1781 ret = add_mimes(begin, *mime_types);
1782 *end = ':';
1783 if (!ret)
1784 break;
1786 if (ret)
1787 ret = add_mimes(begin, *mime_types);
1790 else
1791 ret = FALSE;
1792 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1794 else
1795 ret = FALSE;
1796 if (!ret && *mime_types)
1798 free_native_mime_types(*mime_types);
1799 *mime_types = NULL;
1801 return ret;
1804 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1805 char **match)
1807 #ifdef HAVE_FNMATCH
1808 struct xdg_mime_type *mime_type_entry;
1809 int matchLength = 0;
1811 *match = NULL;
1813 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1815 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1817 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1819 *match = mime_type_entry->mimeType;
1820 matchLength = strlen(mime_type_entry->glob);
1825 if (*match != NULL)
1827 *match = strdupA(*match);
1828 if (*match == NULL)
1829 return FALSE;
1831 #else
1832 *match = NULL;
1833 #endif
1834 return TRUE;
1837 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1838 const char *extensionA,
1839 LPCWSTR extensionW,
1840 char **mime_type)
1842 WCHAR *lower_extensionW;
1843 INT len;
1844 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1845 if (ret == FALSE || *mime_type != NULL)
1846 return ret;
1847 len = strlenW(extensionW);
1848 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1849 if (lower_extensionW)
1851 char *lower_extensionA;
1852 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1853 strlwrW(lower_extensionW);
1854 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1855 if (lower_extensionA)
1857 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1858 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1860 else
1862 ret = FALSE;
1863 WINE_FIXME("out of memory\n");
1865 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1867 else
1869 ret = FALSE;
1870 WINE_FIXME("out of memory\n");
1872 return ret;
1875 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1877 DWORD size;
1878 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1880 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1881 if (ret)
1883 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1884 return ret;
1886 HeapFree(GetProcessHeap(), 0, ret);
1888 return NULL;
1891 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
1893 WCHAR *valW = reg_get_valW(key, subkey, name);
1894 if (valW)
1896 char *val = wchars_to_utf8_chars(valW);
1897 HeapFree(GetProcessHeap(), 0, valW);
1898 return val;
1900 return NULL;
1903 static HKEY open_associations_reg_key(void)
1905 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1906 '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};
1907 HKEY assocKey;
1908 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1909 return assocKey;
1910 return NULL;
1913 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1915 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1916 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1917 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1918 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1919 HKEY assocKey;
1920 BOOL ret;
1922 if ((assocKey = open_associations_reg_key()))
1924 CHAR *valueA;
1925 WCHAR *value;
1927 ret = FALSE;
1929 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
1930 if (!valueA || lstrcmpA(valueA, mimeType))
1931 ret = TRUE;
1932 HeapFree(GetProcessHeap(), 0, valueA);
1934 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1935 if (!value || strcmpW(value, progId))
1936 ret = TRUE;
1937 HeapFree(GetProcessHeap(), 0, value);
1939 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
1940 if (!valueA || lstrcmpA(valueA, appName))
1941 ret = TRUE;
1942 HeapFree(GetProcessHeap(), 0, valueA);
1944 value = reg_get_valW(assocKey, extensionW, DocNameW);
1945 if (docName && (!value || strcmpW(value, docName)))
1946 ret = TRUE;
1947 HeapFree(GetProcessHeap(), 0, value);
1949 RegCloseKey(assocKey);
1951 else
1953 WINE_ERR("error opening associations registry key\n");
1954 ret = FALSE;
1956 return ret;
1959 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
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 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
1966 HKEY assocKey = NULL;
1967 HKEY subkey = NULL;
1968 WCHAR *mimeTypeW = NULL;
1969 WCHAR *appNameW = NULL;
1970 WCHAR *desktopFileW = NULL;
1972 assocKey = open_associations_reg_key();
1973 if (assocKey == NULL)
1975 WINE_ERR("could not open file associations key\n");
1976 goto done;
1979 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
1981 WINE_ERR("could not create extension subkey\n");
1982 goto done;
1985 mimeTypeW = utf8_chars_to_wchars(mimeType);
1986 if (mimeTypeW == NULL)
1988 WINE_ERR("out of memory\n");
1989 goto done;
1992 appNameW = utf8_chars_to_wchars(appName);
1993 if (appNameW == NULL)
1995 WINE_ERR("out of memory\n");
1996 goto done;
1999 desktopFileW = utf8_chars_to_wchars(desktopFile);
2000 if (desktopFileW == NULL)
2002 WINE_ERR("out of memory\n");
2003 goto done;
2006 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2007 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2008 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2009 if (docName)
2010 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
2011 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2013 done:
2014 RegCloseKey(assocKey);
2015 RegCloseKey(subkey);
2016 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2017 HeapFree(GetProcessHeap(), 0, appNameW);
2018 HeapFree(GetProcessHeap(), 0, desktopFileW);
2021 static BOOL cleanup_associations(void)
2023 static const WCHAR openW[] = {'o','p','e','n',0};
2024 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2025 HKEY assocKey;
2026 BOOL hasChanged = FALSE;
2027 if ((assocKey = open_associations_reg_key()))
2029 int i;
2030 BOOL done = FALSE;
2031 for (i = 0; !done; i++)
2033 WCHAR *extensionW = NULL;
2034 DWORD size = 1024;
2035 LSTATUS ret;
2039 HeapFree(GetProcessHeap(), 0, extensionW);
2040 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2041 if (extensionW == NULL)
2043 WINE_ERR("out of memory\n");
2044 ret = ERROR_OUTOFMEMORY;
2045 break;
2047 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2048 size *= 2;
2049 } while (ret == ERROR_MORE_DATA);
2051 if (ret == ERROR_SUCCESS)
2053 WCHAR *command;
2054 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2055 if (command == NULL)
2057 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2058 if (desktopFile)
2060 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2061 remove(desktopFile);
2063 RegDeleteKeyW(assocKey, extensionW);
2064 hasChanged = TRUE;
2065 HeapFree(GetProcessHeap(), 0, desktopFile);
2067 HeapFree(GetProcessHeap(), 0, command);
2069 else
2071 if (ret != ERROR_NO_MORE_ITEMS)
2072 WINE_ERR("error %d while reading registry\n", ret);
2073 done = TRUE;
2075 HeapFree(GetProcessHeap(), 0, extensionW);
2077 RegCloseKey(assocKey);
2079 else
2080 WINE_ERR("could not open file associations key\n");
2081 return hasChanged;
2084 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2085 const char *mime_type, const char *comment)
2087 BOOL ret = FALSE;
2088 char *filename;
2090 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2091 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2093 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2094 if (filename)
2096 FILE *packageFile = fopen(filename, "w");
2097 if (packageFile)
2099 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2100 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2101 fprintf(packageFile, " <mime-type type=\"");
2102 write_xml_text(packageFile, mime_type);
2103 fprintf(packageFile, "\">\n");
2104 fprintf(packageFile, " <glob pattern=\"*");
2105 write_xml_text(packageFile, dot_extension);
2106 fprintf(packageFile, "\"/>\n");
2107 if (comment)
2109 fprintf(packageFile, " <comment>");
2110 write_xml_text(packageFile, comment);
2111 fprintf(packageFile, "</comment>\n");
2113 fprintf(packageFile, " </mime-type>\n");
2114 fprintf(packageFile, "</mime-info>\n");
2115 ret = TRUE;
2116 fclose(packageFile);
2118 else
2119 WINE_ERR("error writing file %s\n", filename);
2120 HeapFree(GetProcessHeap(), 0, filename);
2122 else
2123 WINE_ERR("out of memory\n");
2124 return ret;
2127 static BOOL is_extension_blacklisted(LPCWSTR extension)
2129 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2130 static const WCHAR comW[] = {'.','c','o','m',0};
2131 static const WCHAR exeW[] = {'.','e','x','e',0};
2132 static const WCHAR msiW[] = {'.','m','s','i',0};
2134 if (!strcmpiW(extension, comW) ||
2135 !strcmpiW(extension, exeW) ||
2136 !strcmpiW(extension, msiW))
2137 return TRUE;
2138 return FALSE;
2141 static const char* get_special_mime_type(LPCWSTR extension)
2143 static const WCHAR lnkW[] = {'.','l','n','k',0};
2144 if (!strcmpiW(extension, lnkW))
2145 return "application/x-ms-shortcut";
2146 return NULL;
2149 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2150 const char *friendlyAppName, const char *mimeType,
2151 const char *progId)
2153 BOOL ret = FALSE;
2154 FILE *desktop;
2156 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
2157 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2158 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
2160 desktop = fopen(desktopPath, "w");
2161 if (desktop)
2163 fprintf(desktop, "[Desktop Entry]\n");
2164 fprintf(desktop, "Type=Application\n");
2165 fprintf(desktop, "Name=%s\n", friendlyAppName);
2166 fprintf(desktop, "MimeType=%s\n", mimeType);
2167 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
2168 fprintf(desktop, "NoDisplay=true\n");
2169 fprintf(desktop, "StartupNotify=true\n");
2170 ret = TRUE;
2171 fclose(desktop);
2173 else
2174 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2175 return ret;
2178 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2180 static const WCHAR openW[] = {'o','p','e','n',0};
2181 struct list *nativeMimeTypes = NULL;
2182 LSTATUS ret = 0;
2183 int i;
2184 BOOL hasChanged = FALSE;
2186 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2188 WINE_ERR("could not build native MIME types\n");
2189 return FALSE;
2192 for (i = 0; ; i++)
2194 WCHAR *extensionW = NULL;
2195 DWORD size = 1024;
2199 HeapFree(GetProcessHeap(), 0, extensionW);
2200 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2201 if (extensionW == NULL)
2203 WINE_ERR("out of memory\n");
2204 ret = ERROR_OUTOFMEMORY;
2205 break;
2207 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2208 size *= 2;
2209 } while (ret == ERROR_MORE_DATA);
2211 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2213 char *extensionA = NULL;
2214 WCHAR *commandW = NULL;
2215 WCHAR *friendlyDocNameW = NULL;
2216 char *friendlyDocNameA = NULL;
2217 WCHAR *iconW = NULL;
2218 char *iconA = NULL;
2219 WCHAR *contentTypeW = NULL;
2220 char *mimeTypeA = NULL;
2221 WCHAR *friendlyAppNameW = NULL;
2222 char *friendlyAppNameA = NULL;
2223 WCHAR *progIdW = NULL;
2224 char *progIdA = NULL;
2226 extensionA = wchars_to_utf8_chars(extensionW);
2227 if (extensionA == NULL)
2229 WINE_ERR("out of memory\n");
2230 goto end;
2233 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2234 if (friendlyDocNameW)
2236 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2237 if (friendlyDocNameA == NULL)
2239 WINE_ERR("out of memory\n");
2240 goto end;
2244 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2246 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2247 if (contentTypeW)
2248 strlwrW(contentTypeW);
2250 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2251 goto end;
2253 if (mimeTypeA == NULL)
2255 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2256 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2257 else if ((get_special_mime_type(extensionW)))
2258 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2259 else
2260 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2262 if (mimeTypeA != NULL)
2264 /* Gnome seems to ignore the <icon> tag in MIME packages,
2265 * and the default name is more intuitive anyway.
2267 if (iconW)
2269 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2270 if (flattened_mime)
2272 int index = 0;
2273 WCHAR *comma = strrchrW(iconW, ',');
2274 if (comma)
2276 *comma = 0;
2277 index = atoiW(comma + 1);
2279 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2280 HeapFree(GetProcessHeap(), 0, flattened_mime);
2284 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2285 hasChanged = TRUE;
2287 else
2289 WINE_FIXME("out of memory\n");
2290 goto end;
2294 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2295 if (commandW == NULL)
2296 /* no command => no application is associated */
2297 goto end;
2299 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2300 if (friendlyAppNameW)
2302 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2303 if (friendlyAppNameA == NULL)
2305 WINE_ERR("out of memory\n");
2306 goto end;
2309 else
2311 friendlyAppNameA = heap_printf("A Wine application");
2312 if (friendlyAppNameA == NULL)
2314 WINE_ERR("out of memory\n");
2315 goto end;
2319 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2320 if (progIdW)
2322 progIdA = escape(progIdW);
2323 if (progIdA == NULL)
2325 WINE_ERR("out of memory\n");
2326 goto end;
2329 else
2330 goto end; /* no progID => not a file type association */
2332 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2334 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2335 if (desktopPath)
2337 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2339 hasChanged = TRUE;
2340 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2342 HeapFree(GetProcessHeap(), 0, desktopPath);
2346 end:
2347 HeapFree(GetProcessHeap(), 0, extensionA);
2348 HeapFree(GetProcessHeap(), 0, commandW);
2349 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2350 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2351 HeapFree(GetProcessHeap(), 0, iconW);
2352 HeapFree(GetProcessHeap(), 0, iconA);
2353 HeapFree(GetProcessHeap(), 0, contentTypeW);
2354 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2355 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2356 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2357 HeapFree(GetProcessHeap(), 0, progIdW);
2358 HeapFree(GetProcessHeap(), 0, progIdA);
2360 HeapFree(GetProcessHeap(), 0, extensionW);
2361 if (ret != ERROR_SUCCESS)
2362 break;
2365 free_native_mime_types(nativeMimeTypes);
2366 return hasChanged;
2369 static char *get_start_exe_path(void)
2371 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2372 '\\','s','t','a','r','t','.','e','x','e',0};
2373 WCHAR start_path[MAX_PATH];
2374 GetWindowsDirectoryW(start_path, MAX_PATH);
2375 lstrcatW(start_path, startW);
2376 return escape(start_path);
2379 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2381 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2382 '\\','s','t','a','r','t','.','e','x','e',0};
2383 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2384 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2385 WCHAR szTmp[INFOTIPSIZE];
2386 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2387 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2388 int iIconId = 0, r = -1;
2389 DWORD csidl = -1;
2390 HANDLE hsem = NULL;
2391 char *unix_link = NULL;
2392 char *start_path = NULL;
2394 if ( !link )
2396 WINE_ERR("Link name is null\n");
2397 return FALSE;
2400 if( !GetLinkLocation( link, &csidl, &link_name ) )
2402 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2403 return TRUE;
2405 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2407 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2408 return TRUE;
2410 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2412 szTmp[0] = 0;
2413 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2414 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2415 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2417 szTmp[0] = 0;
2418 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2419 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2420 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2422 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2423 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2424 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2425 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2427 szTmp[0] = 0;
2428 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2429 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2430 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2432 if( !szPath[0] )
2434 LPITEMIDLIST pidl = NULL;
2435 IShellLinkW_GetIDList( sl, &pidl );
2436 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2437 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2440 /* extract the icon */
2441 if( szIconPath[0] )
2442 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2443 else
2444 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2446 /* fail - try once again after parent process exit */
2447 if( !icon_name )
2449 if (bWait)
2451 WINE_WARN("Unable to extract icon, deferring.\n");
2452 goto cleanup;
2454 WINE_ERR("failed to extract icon from %s\n",
2455 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2458 unix_link = wine_get_unix_file_name(link);
2459 if (unix_link == NULL)
2461 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2462 goto cleanup;
2465 /* check the path */
2466 if( szPath[0] )
2468 static const WCHAR exeW[] = {'.','e','x','e',0};
2469 WCHAR *p;
2471 /* check for .exe extension */
2472 if (!(p = strrchrW( szPath, '.' )) ||
2473 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2474 lstrcmpiW( p, exeW ))
2476 /* Not .exe - use 'start.exe' to launch this file */
2477 p = szArgs + lstrlenW(szPath) + 2;
2478 if (szArgs[0])
2480 p[0] = ' ';
2481 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2482 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2484 else
2485 p[0] = 0;
2487 szArgs[0] = '"';
2488 lstrcpyW(szArgs + 1, szPath);
2489 p[-1] = '"';
2491 GetWindowsDirectoryW(szPath, MAX_PATH);
2492 lstrcatW(szPath, startW);
2495 /* convert app working dir */
2496 if (szWorkDir[0])
2497 work_dir = wine_get_unix_file_name( szWorkDir );
2499 else
2501 /* if there's no path... try run the link itself */
2502 lstrcpynW(szArgs, link, MAX_PATH);
2503 GetWindowsDirectoryW(szPath, MAX_PATH);
2504 lstrcatW(szPath, startW);
2507 /* escape the path and parameters */
2508 escaped_path = escape(szPath);
2509 escaped_args = escape(szArgs);
2510 description = wchars_to_utf8_chars(szDescription);
2511 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2513 WINE_ERR("out of memory allocating/escaping parameters\n");
2514 goto cleanup;
2517 start_path = get_start_exe_path();
2518 if (start_path == NULL)
2520 WINE_ERR("out of memory\n");
2521 goto cleanup;
2524 /* building multiple menus concurrently has race conditions */
2525 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2526 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2528 WINE_ERR("failed wait for semaphore\n");
2529 goto cleanup;
2532 if (in_desktop_dir(csidl))
2534 char *location;
2535 const char *lastEntry;
2536 lastEntry = strrchr(link_name, '/');
2537 if (lastEntry == NULL)
2538 lastEntry = link_name;
2539 else
2540 ++lastEntry;
2541 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2542 if (location)
2544 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2545 if (r == 0)
2546 chmod(location, 0755);
2547 HeapFree(GetProcessHeap(), 0, location);
2550 else
2552 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2553 if (unix_linkW)
2555 char *escaped_lnk = escape(unix_linkW);
2556 if (escaped_lnk)
2558 char *menuarg = heap_printf("/Unix %s", escaped_lnk);
2559 if (menuarg)
2561 r = !write_menu_entry(unix_link, link_name, start_path, menuarg, description, work_dir, icon_name);
2562 HeapFree(GetProcessHeap(), 0, menuarg);
2564 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2566 HeapFree(GetProcessHeap(), 0, unix_linkW);
2570 ReleaseSemaphore( hsem, 1, NULL );
2572 cleanup:
2573 if (hsem) CloseHandle( hsem );
2574 HeapFree( GetProcessHeap(), 0, icon_name );
2575 HeapFree( GetProcessHeap(), 0, work_dir );
2576 HeapFree( GetProcessHeap(), 0, link_name );
2577 HeapFree( GetProcessHeap(), 0, escaped_args );
2578 HeapFree( GetProcessHeap(), 0, escaped_path );
2579 HeapFree( GetProcessHeap(), 0, description );
2580 HeapFree( GetProcessHeap(), 0, unix_link );
2581 HeapFree( GetProcessHeap(), 0, start_path );
2583 if (r && !bWait)
2584 WINE_ERR("failed to build the menu\n" );
2586 return ( r == 0 );
2589 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2591 char *link_name = NULL;
2592 DWORD csidl = -1;
2593 LPWSTR urlPath;
2594 char *escaped_urlPath = NULL;
2595 HRESULT hr;
2596 HANDLE hSem = NULL;
2597 BOOL ret = TRUE;
2598 int r = -1;
2599 char *unix_link = NULL;
2601 if ( !link )
2603 WINE_ERR("Link name is null\n");
2604 return TRUE;
2607 if( !GetLinkLocation( link, &csidl, &link_name ) )
2609 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2610 return TRUE;
2612 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2614 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2615 ret = TRUE;
2616 goto cleanup;
2618 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2620 hr = url->lpVtbl->GetURL(url, &urlPath);
2621 if (FAILED(hr))
2623 ret = TRUE;
2624 goto cleanup;
2626 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2628 unix_link = wine_get_unix_file_name(link);
2629 if (unix_link == NULL)
2631 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2632 goto cleanup;
2635 escaped_urlPath = escape(urlPath);
2636 if (escaped_urlPath == NULL)
2638 WINE_ERR("couldn't escape url, out of memory\n");
2639 goto cleanup;
2642 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2643 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2645 WINE_ERR("failed wait for semaphore\n");
2646 goto cleanup;
2648 if (in_desktop_dir(csidl))
2650 char *location;
2651 const char *lastEntry;
2652 lastEntry = strrchr(link_name, '/');
2653 if (lastEntry == NULL)
2654 lastEntry = link_name;
2655 else
2656 ++lastEntry;
2657 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2658 if (location)
2660 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2661 if (r == 0)
2662 chmod(location, 0755);
2663 HeapFree(GetProcessHeap(), 0, location);
2666 else
2667 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2668 ret = (r != 0);
2669 ReleaseSemaphore(hSem, 1, NULL);
2671 cleanup:
2672 if (hSem)
2673 CloseHandle(hSem);
2674 HeapFree(GetProcessHeap(), 0, link_name);
2675 CoTaskMemFree( urlPath );
2676 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2677 HeapFree(GetProcessHeap(), 0, unix_link);
2678 return ret;
2681 static BOOL WaitForParentProcess( void )
2683 PROCESSENTRY32 procentry;
2684 HANDLE hsnapshot = NULL, hprocess = NULL;
2685 DWORD ourpid = GetCurrentProcessId();
2686 BOOL ret = FALSE, rc;
2688 WINE_TRACE("Waiting for parent process\n");
2689 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2690 INVALID_HANDLE_VALUE)
2692 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2693 goto done;
2696 procentry.dwSize = sizeof(PROCESSENTRY32);
2697 rc = Process32First( hsnapshot, &procentry );
2698 while (rc)
2700 if (procentry.th32ProcessID == ourpid) break;
2701 rc = Process32Next( hsnapshot, &procentry );
2703 if (!rc)
2705 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2706 goto done;
2709 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2710 NULL)
2712 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2713 GetLastError());
2714 goto done;
2717 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2718 ret = TRUE;
2719 else
2720 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2722 done:
2723 if (hprocess) CloseHandle( hprocess );
2724 if (hsnapshot) CloseHandle( hsnapshot );
2725 return ret;
2728 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2730 IShellLinkW *sl;
2731 IPersistFile *pf;
2732 HRESULT r;
2733 WCHAR fullname[MAX_PATH];
2734 DWORD len;
2736 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2738 if( !linkname[0] )
2740 WINE_ERR("link name missing\n");
2741 return 1;
2744 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2745 if (len==0 || len>MAX_PATH)
2747 WINE_ERR("couldn't get full path of link file\n");
2748 return 1;
2751 r = CoInitialize( NULL );
2752 if( FAILED( r ) )
2754 WINE_ERR("CoInitialize failed\n");
2755 return 1;
2758 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2759 &IID_IShellLinkW, (LPVOID *) &sl );
2760 if( FAILED( r ) )
2762 WINE_ERR("No IID_IShellLink\n");
2763 return 1;
2766 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2767 if( FAILED( r ) )
2769 WINE_ERR("No IID_IPersistFile\n");
2770 return 1;
2773 r = IPersistFile_Load( pf, fullname, STGM_READ );
2774 if( SUCCEEDED( r ) )
2776 /* If something fails (eg. Couldn't extract icon)
2777 * wait for parent process and try again
2779 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2781 WaitForParentProcess();
2782 InvokeShellLinker( sl, fullname, FALSE );
2785 else
2787 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2790 IPersistFile_Release( pf );
2791 IShellLinkW_Release( sl );
2793 CoUninitialize();
2795 return !r;
2798 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2800 IUniformResourceLocatorW *url;
2801 IPersistFile *pf;
2802 HRESULT r;
2803 WCHAR fullname[MAX_PATH];
2804 DWORD len;
2806 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2808 if( !urlname[0] )
2810 WINE_ERR("URL name missing\n");
2811 return 1;
2814 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2815 if (len==0 || len>MAX_PATH)
2817 WINE_ERR("couldn't get full path of URL file\n");
2818 return 1;
2821 r = CoInitialize( NULL );
2822 if( FAILED( r ) )
2824 WINE_ERR("CoInitialize failed\n");
2825 return 1;
2828 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2829 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2830 if( FAILED( r ) )
2832 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2833 return 1;
2836 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2837 if( FAILED( r ) )
2839 WINE_ERR("No IID_IPersistFile\n");
2840 return 1;
2842 r = IPersistFile_Load( pf, fullname, STGM_READ );
2843 if( SUCCEEDED( r ) )
2845 /* If something fails (eg. Couldn't extract icon)
2846 * wait for parent process and try again
2848 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2850 WaitForParentProcess();
2851 InvokeShellLinkerForURL( url, fullname, FALSE );
2855 IPersistFile_Release( pf );
2856 url->lpVtbl->Release( url );
2858 CoUninitialize();
2860 return !r;
2863 static void RefreshFileTypeAssociations(void)
2865 HANDLE hSem = NULL;
2866 char *mime_dir = NULL;
2867 char *packages_dir = NULL;
2868 char *applications_dir = NULL;
2869 BOOL hasChanged;
2871 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2872 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2874 WINE_ERR("failed wait for semaphore\n");
2875 CloseHandle(hSem);
2876 hSem = NULL;
2877 goto end;
2880 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2881 if (mime_dir == NULL)
2883 WINE_ERR("out of memory\n");
2884 goto end;
2886 create_directories(mime_dir);
2888 packages_dir = heap_printf("%s/packages", mime_dir);
2889 if (packages_dir == NULL)
2891 WINE_ERR("out of memory\n");
2892 goto end;
2894 create_directories(packages_dir);
2896 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2897 if (applications_dir == NULL)
2899 WINE_ERR("out of memory\n");
2900 goto end;
2902 create_directories(applications_dir);
2904 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2905 hasChanged |= cleanup_associations();
2906 if (hasChanged)
2908 const char *argv[3];
2910 argv[0] = "update-mime-database";
2911 argv[1] = mime_dir;
2912 argv[2] = NULL;
2913 spawnvp( _P_NOWAIT, argv[0], argv );
2915 argv[0] = "update-desktop-database";
2916 argv[1] = applications_dir;
2917 spawnvp( _P_NOWAIT, argv[0], argv );
2920 end:
2921 if (hSem)
2923 ReleaseSemaphore(hSem, 1, NULL);
2924 CloseHandle(hSem);
2926 HeapFree(GetProcessHeap(), 0, mime_dir);
2927 HeapFree(GetProcessHeap(), 0, packages_dir);
2928 HeapFree(GetProcessHeap(), 0, applications_dir);
2931 static void cleanup_menus(void)
2933 HKEY hkey;
2935 hkey = open_menus_reg_key();
2936 if (hkey)
2938 int i;
2939 LSTATUS lret = ERROR_SUCCESS;
2940 for (i = 0; lret == ERROR_SUCCESS; )
2942 WCHAR *value = NULL;
2943 WCHAR *data = NULL;
2944 DWORD valueSize = 4096;
2945 DWORD dataSize = 4096;
2946 while (1)
2948 lret = ERROR_OUTOFMEMORY;
2949 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
2950 if (value == NULL)
2951 break;
2952 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
2953 if (data == NULL)
2954 break;
2955 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2956 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2957 break;
2958 valueSize *= 2;
2959 dataSize *= 2;
2960 HeapFree(GetProcessHeap(), 0, value);
2961 HeapFree(GetProcessHeap(), 0, data);
2962 value = data = NULL;
2964 if (lret == ERROR_SUCCESS)
2966 char *unix_file;
2967 char *windows_file;
2968 unix_file = wchars_to_unix_chars(value);
2969 windows_file = wchars_to_unix_chars(data);
2970 if (unix_file != NULL && windows_file != NULL)
2972 struct stat filestats;
2973 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
2975 WINE_TRACE("removing menu related file %s\n", unix_file);
2976 remove(unix_file);
2977 RegDeleteValueW(hkey, value);
2979 else
2980 i++;
2982 else
2984 WINE_ERR("out of memory enumerating menus\n");
2985 lret = ERROR_OUTOFMEMORY;
2987 HeapFree(GetProcessHeap(), 0, unix_file);
2988 HeapFree(GetProcessHeap(), 0, windows_file);
2990 else if (lret != ERROR_NO_MORE_ITEMS)
2991 WINE_ERR("error %d reading registry\n", lret);
2992 HeapFree(GetProcessHeap(), 0, value);
2993 HeapFree(GetProcessHeap(), 0, data);
2995 RegCloseKey(hkey);
2997 else
2998 WINE_ERR("error opening registry key, menu cleanup failed\n");
3001 static WCHAR *next_token( LPWSTR *p )
3003 LPWSTR token = NULL, t = *p;
3005 if( !t )
3006 return NULL;
3008 while( t && !token )
3010 switch( *t )
3012 case ' ':
3013 t++;
3014 continue;
3015 case '"':
3016 /* unquote the token */
3017 token = ++t;
3018 t = strchrW( token, '"' );
3019 if( t )
3020 *t++ = 0;
3021 break;
3022 case 0:
3023 t = NULL;
3024 break;
3025 default:
3026 token = t;
3027 t = strchrW( token, ' ' );
3028 if( t )
3029 *t++ = 0;
3030 break;
3033 *p = t;
3034 return token;
3037 static BOOL init_xdg(void)
3039 WCHAR shellDesktopPath[MAX_PATH];
3040 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3041 if (SUCCEEDED(hr))
3042 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3043 if (xdg_desktop_dir == NULL)
3045 WINE_ERR("error looking up the desktop directory\n");
3046 return FALSE;
3049 if (getenv("XDG_CONFIG_HOME"))
3050 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3051 else
3052 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3053 if (xdg_config_dir)
3055 create_directories(xdg_config_dir);
3056 if (getenv("XDG_DATA_HOME"))
3057 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3058 else
3059 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3060 if (xdg_data_dir)
3062 char *buffer;
3063 create_directories(xdg_data_dir);
3064 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3065 if (buffer)
3067 mkdir(buffer, 0777);
3068 HeapFree(GetProcessHeap(), 0, buffer);
3070 return TRUE;
3072 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3074 WINE_ERR("out of memory\n");
3075 return FALSE;
3078 /***********************************************************************
3080 * wWinMain
3082 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3084 static const WCHAR dash_aW[] = {'-','a',0};
3085 static const WCHAR dash_rW[] = {'-','r',0};
3086 static const WCHAR dash_uW[] = {'-','u',0};
3087 static const WCHAR dash_wW[] = {'-','w',0};
3089 LPWSTR token = NULL, p;
3090 BOOL bWait = FALSE;
3091 BOOL bURL = FALSE;
3092 int ret = 0;
3094 if (!init_xdg())
3095 return 1;
3097 for( p = cmdline; p && *p; )
3099 token = next_token( &p );
3100 if( !token )
3101 break;
3102 if( !strcmpW( token, dash_aW ) )
3104 RefreshFileTypeAssociations();
3105 continue;
3107 if( !strcmpW( token, dash_rW ) )
3109 cleanup_menus();
3110 continue;
3112 if( !strcmpW( token, dash_wW ) )
3113 bWait = TRUE;
3114 else if ( !strcmpW( token, dash_uW ) )
3115 bURL = TRUE;
3116 else if( token[0] == '-' )
3118 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3120 else
3122 BOOL bRet;
3124 if (bURL)
3125 bRet = Process_URL( token, bWait );
3126 else
3127 bRet = Process_Link( token, bWait );
3128 if (!bRet)
3130 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3131 ret = 1;
3136 return ret;