winemenubuilder: Load only low bit count icons if we are going to save to XPM format.
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blob620d70528c2eb8af055c220b5e8e3a6442c7b9d6
1 /*
2 * Helper program to build unix menu entries
4 * Copyright 1997 Marcus Meissner
5 * Copyright 1998 Juergen Schmied
6 * Copyright 2003 Mike McCormack for CodeWeavers
7 * Copyright 2004 Dmitry Timoshkov
8 * Copyright 2005 Bill Medland
9 * Copyright 2008 Damjan Jovanovic
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 * This program is used to replicate the Windows desktop and start menu
27 * into the native desktop's copies. Desktop entries are merged directly
28 * into the native desktop. The Windows Start Menu corresponds to a Wine
29 * entry within the native "start" menu and replicates the whole tree
30 * structure of the Windows Start Menu. Currently it does not differentiate
31 * between the user's desktop/start menu and the "All Users" copies.
33 * This program will read a Windows shortcut file using the IShellLink
34 * interface, then create a KDE/Gnome menu entry for the shortcut.
36 * winemenubuilder [ -w ] <shortcut.lnk>
38 * If the -w parameter is passed, and the shortcut cannot be created,
39 * this program will wait for the parent process to finish and then try
40 * again. This covers the case when a ShortCut is created before the
41 * executable containing its icon.
43 * TODO
44 * Handle data lnk files. There is no icon in the file; the icon is in
45 * the handler for the file type (or pointed to by the lnk file). Also it
46 * might be better to use a native handler (e.g. a native acroread for pdf
47 * files).
48 * Differentiate between the user's entries and the "All Users" entries.
49 * If it is possible to add the desktop files to the native system's
50 * shared location for an "All Users" entry then do so. As a suggestion the
51 * shared menu Wine base could be writable to the wine group, or a wineadm
52 * group.
53 * Clean up fd.o menu icons and .directory files when the menu is deleted
54 * in Windows.
55 * Generate icons for file open handlers to go into the "Open with..."
56 * list. What does Windows use, the default icon for the .EXE file? It's
57 * not in the registry.
58 * Associate applications under HKCR\Applications to open any MIME type
59 * (by associating with application/octet-stream, or how?).
60 * Clean up fd.o MIME types when they are deleted in Windows, their icons
61 * too. Very hard - once we associate them with fd.o, we can't tell whether
62 * they are ours or not, and the extension <-> MIME type mapping isn't
63 * one-to-one either.
64 * Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
65 * that write associations there won't associate (#17019).
68 #include "config.h"
69 #include "wine/port.h"
71 #include <ctype.h>
72 #include <stdio.h>
73 #include <string.h>
74 #ifdef HAVE_UNISTD_H
75 #include <unistd.h>
76 #endif
77 #include <errno.h>
78 #include <stdarg.h>
79 #ifdef HAVE_FNMATCH_H
80 #include <fnmatch.h>
81 #endif
83 #define COBJMACROS
85 #include <windows.h>
86 #include <shlobj.h>
87 #include <objidl.h>
88 #include <shlguid.h>
89 #include <appmgmt.h>
90 #include <tlhelp32.h>
91 #include <intshcut.h>
92 #include <shlwapi.h>
94 #include "wine/unicode.h"
95 #include "wine/debug.h"
96 #include "wine/library.h"
97 #include "wine/list.h"
98 #include "wine.xpm"
100 #ifdef HAVE_PNG_H
101 #undef FAR
102 #include <png.h>
103 #endif
105 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
107 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
108 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
109 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
110 (csidl)==CSIDL_COMMON_STARTMENU)
112 /* link file formats */
114 #include "pshpack1.h"
116 typedef struct
118 BYTE bWidth;
119 BYTE bHeight;
120 BYTE bColorCount;
121 BYTE bReserved;
122 WORD wPlanes;
123 WORD wBitCount;
124 DWORD dwBytesInRes;
125 WORD nID;
126 } GRPICONDIRENTRY;
128 typedef struct
130 WORD idReserved;
131 WORD idType;
132 WORD idCount;
133 GRPICONDIRENTRY idEntries[1];
134 } GRPICONDIR;
136 typedef struct
138 BYTE bWidth;
139 BYTE bHeight;
140 BYTE bColorCount;
141 BYTE bReserved;
142 WORD wPlanes;
143 WORD wBitCount;
144 DWORD dwBytesInRes;
145 DWORD dwImageOffset;
146 } ICONDIRENTRY;
148 typedef struct
150 WORD idReserved;
151 WORD idType;
152 WORD idCount;
153 } ICONDIR;
156 #include "poppack.h"
158 typedef struct
160 HRSRC *pResInfo;
161 int nIndex;
162 } ENUMRESSTRUCT;
164 struct xdg_mime_type
166 char *mimeType;
167 char *glob;
168 struct list entry;
171 static char *xdg_config_dir;
172 static char *xdg_data_dir;
173 static char *xdg_desktop_dir;
175 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra);
176 static char *extract_icon(LPCWSTR path, int index, const char *destFilename, BOOL bWait);
178 /* Icon extraction routines
180 * FIXME: should use PrivateExtractIcons and friends
181 * FIXME: should not use stdio
184 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
186 /* PNG-specific code */
187 #ifdef SONAME_LIBPNG
189 static void *libpng_handle;
190 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
191 MAKE_FUNCPTR(png_create_info_struct);
192 MAKE_FUNCPTR(png_create_write_struct);
193 MAKE_FUNCPTR(png_destroy_write_struct);
194 MAKE_FUNCPTR(png_get_error_ptr);
195 MAKE_FUNCPTR(png_init_io);
196 MAKE_FUNCPTR(png_set_bgr);
197 MAKE_FUNCPTR(png_set_error_fn);
198 MAKE_FUNCPTR(png_set_text);
199 MAKE_FUNCPTR(png_set_IHDR);
200 MAKE_FUNCPTR(png_write_end);
201 MAKE_FUNCPTR(png_write_info);
202 MAKE_FUNCPTR(png_write_row);
203 #undef MAKE_FUNCPTR
205 static void *load_libpng(void)
207 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
209 #define LOAD_FUNCPTR(f) \
210 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
211 libpng_handle = NULL; \
212 return NULL; \
214 LOAD_FUNCPTR(png_create_info_struct);
215 LOAD_FUNCPTR(png_create_write_struct);
216 LOAD_FUNCPTR(png_destroy_write_struct);
217 LOAD_FUNCPTR(png_get_error_ptr);
218 LOAD_FUNCPTR(png_init_io);
219 LOAD_FUNCPTR(png_set_bgr);
220 LOAD_FUNCPTR(png_set_error_fn);
221 LOAD_FUNCPTR(png_set_IHDR);
222 LOAD_FUNCPTR(png_set_text);
223 LOAD_FUNCPTR(png_write_end);
224 LOAD_FUNCPTR(png_write_info);
225 LOAD_FUNCPTR(png_write_row);
226 #undef LOAD_FUNCPTR
228 return libpng_handle;
231 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
233 jmp_buf *pjmpbuf;
235 /* This uses setjmp/longjmp just like the default. We can't use the
236 * default because there's no way to access the jmp buffer in the png_struct
237 * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
238 WINE_ERR("PNG error: %s\n", wine_dbgstr_an(error_message, -1));
239 pjmpbuf = ppng_get_error_ptr(png_ptr);
240 longjmp(*pjmpbuf, 1);
243 static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
245 WINE_WARN("PNG warning: %s\n", wine_dbgstr_an(warning_message, -1));
248 static BOOL SaveTrueColorIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
250 static const char comment_key[] = "Created from";
251 FILE *fp;
252 png_structp png_ptr;
253 png_infop info_ptr;
254 png_text comment;
255 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
256 BYTE *row, *copy = NULL;
257 const BYTE *pXOR, *pAND = NULL;
258 int nWidth = pIcon->bmiHeader.biWidth;
259 int nHeight = pIcon->bmiHeader.biHeight;
260 int nBpp = pIcon->bmiHeader.biBitCount;
261 jmp_buf jmpbuf;
263 switch (nBpp)
265 case 32:
266 color_type |= PNG_COLOR_MASK_ALPHA;
267 /* fall through */
268 case 24:
269 color_type |= PNG_COLOR_MASK_COLOR;
270 break;
271 default:
272 return FALSE;
275 if (!libpng_handle && !load_libpng())
277 WINE_WARN("Unable to load libpng\n");
278 return FALSE;
281 if (!(fp = fopen(png_filename, "w")))
283 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
284 return FALSE;
287 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
288 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
289 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
290 if (nHeight > nWidth)
292 nHeight /= 2;
293 pAND = pXOR + nHeight * nXORWidthBytes;
296 /* Apply mask if present */
297 if (pAND)
299 RGBQUAD bgColor;
301 /* copy bytes before modifying them */
302 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
303 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
304 pXOR = copy;
306 /* image and mask are upside down reversed */
307 row = copy + (nHeight - 1) * nXORWidthBytes;
309 /* top left corner */
310 bgColor.rgbRed = row[0];
311 bgColor.rgbGreen = row[1];
312 bgColor.rgbBlue = row[2];
313 bgColor.rgbReserved = 0;
315 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
316 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
317 if (MASK(j, i))
319 RGBQUAD *pixel = (RGBQUAD *)row;
320 pixel->rgbBlue = bgColor.rgbBlue;
321 pixel->rgbGreen = bgColor.rgbGreen;
322 pixel->rgbRed = bgColor.rgbRed;
323 if (nBpp == 32)
324 pixel->rgbReserved = bgColor.rgbReserved;
328 comment.text = NULL;
330 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
331 !(info_ptr = ppng_create_info_struct(png_ptr)))
332 goto error;
334 if (setjmp(jmpbuf))
336 /* All future errors jump here */
337 goto error;
339 ppng_set_error_fn(png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
341 ppng_init_io(png_ptr, fp);
342 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
343 color_type,
344 PNG_INTERLACE_NONE,
345 PNG_COMPRESSION_TYPE_DEFAULT,
346 PNG_FILTER_TYPE_DEFAULT);
348 /* Set comment */
349 comment.compression = PNG_TEXT_COMPRESSION_NONE;
350 comment.key = (png_charp)comment_key;
351 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
352 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
353 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
354 comment.text_length = i - 1;
355 ppng_set_text(png_ptr, info_ptr, &comment, 1);
358 ppng_write_info(png_ptr, info_ptr);
359 ppng_set_bgr(png_ptr);
360 for (i = nHeight - 1; i >= 0 ; i--)
361 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
362 ppng_write_end(png_ptr, info_ptr);
364 ppng_destroy_write_struct(&png_ptr, &info_ptr);
365 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
366 fclose(fp);
367 HeapFree(GetProcessHeap(), 0, copy);
368 HeapFree(GetProcessHeap(), 0, comment.text);
369 return TRUE;
371 error:
372 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
373 fclose(fp);
374 unlink(png_filename);
375 HeapFree(GetProcessHeap(), 0, copy);
376 HeapFree(GetProcessHeap(), 0, comment.text);
377 return FALSE;
380 static BOOL SavePalettedIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
382 static const char comment_key[] = "Created from";
383 FILE *pngFile = NULL;
384 int i, j;
385 int nHeight;
386 int nXORWidthBytes;
387 int nANDWidthBytes;
388 BOOL b8BitColors;
389 int nColors;
390 const BYTE *pXOR;
391 const BYTE *pAND;
392 png_structp png_ptr;
393 png_infop info_ptr;
394 png_text comment;
395 jmp_buf jmpbuf;
396 unsigned char *row = NULL;
397 BOOL ret = FALSE;
399 comment.text = NULL;
401 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
403 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
404 goto done;
407 if (!(pngFile = fopen(png_filename, "w")))
409 WINE_TRACE("Unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
410 goto done;
413 nHeight = pIcon->bmiHeader.biHeight / 2;
414 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
415 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
416 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
417 + ((pIcon->bmiHeader.biWidth % 32) > 0));
418 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
419 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
420 : 1 << pIcon->bmiHeader.biBitCount;
421 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
422 pAND = pXOR + nHeight * nXORWidthBytes;
424 row = HeapAlloc(GetProcessHeap(), 0, 4 * pIcon->bmiHeader.biWidth);
425 if (row == NULL)
427 WINE_ERR("out of memory\n");
428 goto done;
431 if (!libpng_handle && !load_libpng())
433 WINE_WARN("Unable to load libpng\n");
434 goto done;
437 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
438 !(info_ptr = ppng_create_info_struct(png_ptr)))
439 goto done;
441 if (setjmp(jmpbuf))
443 /* All future errors jump here */
444 goto done;
446 ppng_set_error_fn(png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
448 ppng_init_io(png_ptr, pngFile);
449 ppng_set_IHDR(png_ptr, info_ptr, pIcon->bmiHeader.biWidth, nHeight, 8,
450 PNG_COLOR_TYPE_RGB_ALPHA,
451 PNG_INTERLACE_NONE,
452 PNG_COMPRESSION_TYPE_DEFAULT,
453 PNG_FILTER_TYPE_DEFAULT);
455 /* Set comment */
456 comment.compression = PNG_TEXT_COMPRESSION_NONE;
457 comment.key = (png_charp)comment_key;
458 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
459 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
460 if (comment.text == NULL)
462 WINE_ERR("out of memory\n");
463 goto done;
465 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
466 comment.text_length = i - 1;
467 ppng_set_text(png_ptr, info_ptr, &comment, 1);
469 ppng_write_info(png_ptr, info_ptr);
470 for (i = 0; i < nHeight; i++)
472 unsigned char *p = row;
473 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
475 if MASK(j,i)
477 *p++ = 0;
478 *p++ = 0;
479 *p++ = 0;
480 *p++ = 0;
482 else
484 #define COLOR(x,y) (b8BitColors ? pXOR[(x) + (nHeight - (y) - 1) * nXORWidthBytes] : (x) % 2 ? pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF : (pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF0) >> 4)
485 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbRed;
486 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbGreen;
487 *p++ = pIcon->bmiColors[COLOR(j,i)].rgbBlue;
488 *p++ = 0xFF;
489 #undef COLOR
492 ppng_write_row(png_ptr, (png_bytep)row);
494 ppng_write_end(png_ptr, info_ptr);
495 ret = TRUE;
497 done:
498 ppng_destroy_write_struct(&png_ptr, &info_ptr);
499 if (pngFile != NULL)
500 fclose(pngFile);
501 HeapFree(GetProcessHeap(), 0, comment.text);
502 HeapFree(GetProcessHeap(), 0, row);
503 return ret;
506 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
508 switch (pIcon->bmiHeader.biBitCount)
510 case 4:
511 case 8:
512 return SavePalettedIconResAsPNG(pIcon, png_filename, commentW);
513 case 24:
514 case 32:
515 return SaveTrueColorIconResAsPNG(pIcon, png_filename, commentW);
516 default:
517 WINE_FIXME("unsupported bpp %d, please report\n", pIcon->bmiHeader.biBitCount);
518 return FALSE;
521 #endif /* SONAME_LIBPNG */
523 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
525 FILE *fXPMFile;
526 int nHeight;
527 int nXORWidthBytes;
528 int nANDWidthBytes;
529 BOOL b8BitColors;
530 int nColors;
531 const BYTE *pXOR;
532 const BYTE *pAND;
533 BOOL aColorUsed[256] = {0};
534 int nColorsUsed = 0;
535 int i,j;
536 char *comment;
538 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
540 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
541 return FALSE;
544 if (!(fXPMFile = fopen(szXPMFileName, "w")))
546 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
547 return FALSE;
550 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
551 comment = HeapAlloc(GetProcessHeap(), 0, i);
552 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
554 nHeight = pIcon->bmiHeader.biHeight / 2;
555 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
556 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
557 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
558 + ((pIcon->bmiHeader.biWidth % 32) > 0));
559 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
560 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
561 : 1 << pIcon->bmiHeader.biBitCount;
562 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
563 pAND = pXOR + nHeight * nXORWidthBytes;
565 #define COLOR(x,y) (b8BitColors ? pXOR[(x) + (nHeight - (y) - 1) * nXORWidthBytes] : (x) % 2 ? pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF : (pXOR[(x) / 2 + (nHeight - (y) - 1) * nXORWidthBytes] & 0xF0) >> 4)
567 for (i = 0; i < nHeight; i++) {
568 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
569 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
571 aColorUsed[COLOR(j,i)] = TRUE;
572 nColorsUsed++;
577 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
578 goto error;
579 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
580 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
581 goto error;
583 for (i = 0; i < nColors; i++) {
584 if (aColorUsed[i])
585 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
586 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
587 goto error;
589 if (fprintf(fXPMFile, "\" c None\"") <= 0)
590 goto error;
592 for (i = 0; i < nHeight; i++)
594 if (fprintf(fXPMFile, ",\n\"") <= 0)
595 goto error;
596 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
598 if MASK(j,i)
600 if (fprintf(fXPMFile, " ") <= 0)
601 goto error;
603 else
604 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
605 goto error;
607 if (fprintf(fXPMFile, "\"") <= 0)
608 goto error;
610 if (fprintf(fXPMFile, "};\n") <= 0)
611 goto error;
613 #undef MASK
614 #undef COLOR
616 HeapFree(GetProcessHeap(), 0, comment);
617 fclose(fXPMFile);
618 return TRUE;
620 error:
621 HeapFree(GetProcessHeap(), 0, comment);
622 fclose(fXPMFile);
623 unlink( szXPMFileName );
624 return FALSE;
627 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
629 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
631 if (!sEnumRes->nIndex--)
633 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
634 return FALSE;
636 else
637 return TRUE;
640 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
642 HMODULE hModule;
643 HRSRC hResInfo;
644 LPCWSTR lpName = NULL;
645 HGLOBAL hResData;
646 GRPICONDIR *pIconDir;
647 BITMAPINFO *pIcon;
648 ENUMRESSTRUCT sEnumRes;
649 int nMax = 0;
650 int nMaxBits = 0;
651 int i;
652 BOOL ret = FALSE;
654 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
655 if (!hModule)
657 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
658 wine_dbgstr_w(szFileName), GetLastError());
659 return FALSE;
662 if (nIndex < 0)
664 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
665 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
666 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
668 else
670 hResInfo=NULL;
671 sEnumRes.pResInfo = &hResInfo;
672 sEnumRes.nIndex = nIndex;
673 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
674 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
675 sEnumRes.nIndex != -1)
677 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
681 if (hResInfo)
683 if ((hResData = LoadResource(hModule, hResInfo)))
685 if ((pIconDir = LockResource(hResData)))
687 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[0].nID); /* default to first entry */
688 for (i = 0; i < pIconDir->idCount; i++)
690 #ifndef SONAME_LIBPNG
691 if (pIconDir->idEntries[i].wBitCount != 4 && pIconDir->idEntries[i].wBitCount != 8)
692 continue;
693 #endif
694 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
696 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
698 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
699 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
700 nMaxBits = pIconDir->idEntries[i].wBitCount;
706 FreeResource(hResData);
709 else
711 WINE_WARN("found no icon\n");
712 FreeLibrary(hModule);
713 return FALSE;
716 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
718 if ((hResData = LoadResource(hModule, hResInfo)))
720 if ((pIcon = LockResource(hResData)))
722 #ifdef SONAME_LIBPNG
723 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
724 ret = TRUE;
725 else
726 #endif
728 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
729 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
730 ret = TRUE;
734 FreeResource(hResData);
738 FreeLibrary(hModule);
739 return ret;
742 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
744 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
745 !extract_icon16(szFileName, szXPMFileName)*/)
746 return FALSE;
747 return TRUE;
750 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
752 FILE *fICOFile = NULL;
753 ICONDIR iconDir;
754 ICONDIRENTRY *pIconDirEntry = NULL;
755 int nMax = 0, nMaxBits = 0;
756 int nIndex = 0;
757 void *pIcon = NULL;
758 int i;
759 char *filename = NULL;
761 filename = wine_get_unix_file_name(szFileName);
762 if (!(fICOFile = fopen(filename, "r")))
764 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
765 goto error;
768 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
769 (iconDir.idReserved != 0) || (iconDir.idType != 1))
771 WINE_WARN("Invalid ico file format\n");
772 goto error;
775 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
776 goto error;
777 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
778 goto error;
780 for (i = 0; i < iconDir.idCount; i++)
782 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
783 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
784 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
786 nIndex = i;
787 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
788 nMaxBits = pIconDirEntry[i].wBitCount;
791 WINE_TRACE("Selected: %d\n", nIndex);
793 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
794 goto error;
795 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
796 goto error;
797 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
798 goto error;
801 /* Prefer PNG over XPM */
802 #ifdef SONAME_LIBPNG
803 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
804 #endif
806 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
807 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
808 goto error;
811 HeapFree(GetProcessHeap(), 0, pIcon);
812 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
813 fclose(fICOFile);
814 HeapFree(GetProcessHeap(), 0, filename);
815 return 1;
817 error:
818 HeapFree(GetProcessHeap(), 0, pIcon);
819 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
820 if (fICOFile) fclose(fICOFile);
821 HeapFree(GetProcessHeap(), 0, filename);
822 return 0;
825 static int ExtractFromFileType(LPCWSTR szFileName, char *szXPMFileName)
827 int ret = 0;
828 WCHAR *extension;
829 WCHAR *icon = NULL;
830 WCHAR *comma;
831 WCHAR *executable = NULL;
832 int index = 0;
833 char *output_path = NULL;
835 extension = strrchrW(szFileName, '.');
836 if (extension == NULL)
837 goto end;
839 icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
840 if (icon)
842 comma = strrchrW(icon, ',');
843 if (comma)
845 *comma = 0;
846 index = atoiW(comma + 1);
848 output_path = extract_icon(icon, index, NULL, FALSE);
849 WINE_TRACE("defaulticon %s -> icon %s\n", wine_dbgstr_w(icon), wine_dbgstr_a(output_path));
851 else
853 executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, NULL);
854 if (executable)
855 output_path = extract_icon(executable, 0, NULL, FALSE);
856 WINE_TRACE("executable %s -> icon %s\n", wine_dbgstr_w(executable), wine_dbgstr_a(output_path));
858 if (output_path)
859 ret = (rename(output_path, szXPMFileName) == 0);
861 end:
862 HeapFree(GetProcessHeap(), 0, icon);
863 HeapFree(GetProcessHeap(), 0, executable);
864 HeapFree(GetProcessHeap(), 0, output_path);
865 return ret;
868 static BOOL create_default_icon( const char *filename, const char* comment )
870 FILE *fXPM;
871 unsigned int i;
873 if (!(fXPM = fopen(filename, "w"))) return FALSE;
874 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
875 goto error;
876 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
877 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
878 goto error;
880 if (fprintf( fXPM, "};\n" ) <=0)
881 goto error;
882 fclose( fXPM );
883 return TRUE;
884 error:
885 fclose( fXPM );
886 unlink( filename );
887 return FALSE;
891 static unsigned short crc16(const char* string)
893 unsigned short crc = 0;
894 int i, j, xor_poly;
896 for (i = 0; string[i] != 0; i++)
898 char c = string[i];
899 for (j = 0; j < 8; c >>= 1, j++)
901 xor_poly = (c ^ crc) & 1;
902 crc >>= 1;
903 if (xor_poly)
904 crc ^= 0xa001;
907 return crc;
910 static char *strdupA( const char *str )
912 char *ret;
914 if (!str) return NULL;
915 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
916 return ret;
919 static char* heap_printf(const char *format, ...)
921 va_list args;
922 int size = 4096;
923 char *buffer, *ret;
924 int n;
926 va_start(args, format);
927 while (1)
929 buffer = HeapAlloc(GetProcessHeap(), 0, size);
930 if (buffer == NULL)
931 break;
932 n = vsnprintf(buffer, size, format, args);
933 if (n == -1)
934 size *= 2;
935 else if (n >= size)
936 size = n + 1;
937 else
938 break;
939 HeapFree(GetProcessHeap(), 0, buffer);
941 va_end(args);
942 if (!buffer) return NULL;
943 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
944 if (!ret) ret = buffer;
945 return ret;
948 static void write_xml_text(FILE *file, const char *text)
950 int i;
951 for (i = 0; text[i]; i++)
953 if (text[i] == '&')
954 fputs("&amp;", file);
955 else if (text[i] == '<')
956 fputs("&lt;", file);
957 else if (text[i] == '>')
958 fputs("&gt;", file);
959 else if (text[i] == '\'')
960 fputs("&apos;", file);
961 else if (text[i] == '"')
962 fputs("&quot;", file);
963 else
964 fputc(text[i], file);
968 static BOOL create_directories(char *directory)
970 BOOL ret = TRUE;
971 int i;
973 for (i = 0; directory[i]; i++)
975 if (i > 0 && directory[i] == '/')
977 directory[i] = 0;
978 mkdir(directory, 0777);
979 directory[i] = '/';
982 if (mkdir(directory, 0777) && errno != EEXIST)
983 ret = FALSE;
985 return ret;
988 static char* wchars_to_utf8_chars(LPCWSTR string)
990 char *ret;
991 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
992 ret = HeapAlloc(GetProcessHeap(), 0, size);
993 if (ret)
994 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
995 return ret;
998 static char* wchars_to_unix_chars(LPCWSTR string)
1000 char *ret;
1001 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
1002 ret = HeapAlloc(GetProcessHeap(), 0, size);
1003 if (ret)
1004 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
1005 return ret;
1008 static WCHAR* utf8_chars_to_wchars(LPCSTR string)
1010 WCHAR *ret;
1011 INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
1012 ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1013 if (ret)
1014 MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
1015 return ret;
1018 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
1019 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
1021 unsigned short crc;
1022 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
1023 char* s;
1024 int n;
1026 /* Where should we save the icon? */
1027 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
1028 iconsdir = heap_printf("%s/icons", xdg_data_dir);
1029 if (iconsdir)
1031 if (mkdir(iconsdir, 0777) && errno != EEXIST)
1033 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
1034 goto end;
1037 else
1039 WINE_TRACE("no icon created\n");
1040 return NULL;
1043 /* Determine the icon base name */
1044 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
1045 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
1046 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
1047 s=ico_name=ico_path;
1048 while (*s!='\0') {
1049 if (*s=='/' || *s=='\\') {
1050 *s='\\';
1051 ico_name=s;
1052 } else {
1053 *s=tolower(*s);
1055 s++;
1057 if (*ico_name=='\\') *ico_name++='\0';
1058 s=strrchr(ico_name,'.');
1059 if (s) *s='\0';
1061 /* Compute the source-path hash */
1062 crc=crc16(ico_path);
1064 /* Try to treat the source file as an exe */
1065 if (destFilename)
1066 xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
1067 else
1068 xpm_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
1069 if (xpm_path == NULL)
1071 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
1072 return NULL;
1075 if (ExtractFromEXEDLL( path, index, xpm_path ))
1076 goto end;
1078 /* Must be something else, ignore the index in that case */
1079 if (destFilename)
1080 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
1081 else
1082 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
1083 if (ExtractFromICO( path, xpm_path))
1084 goto end;
1085 if (ExtractFromFileType( path, xpm_path ))
1086 goto end;
1087 if (!bWait)
1089 if (destFilename)
1090 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
1091 else
1092 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
1093 if (create_default_icon( xpm_path, ico_path ))
1094 goto end;
1097 HeapFree( GetProcessHeap(), 0, xpm_path );
1098 xpm_path=NULL;
1100 end:
1101 HeapFree(GetProcessHeap(), 0, iconsdir);
1102 HeapFree(GetProcessHeap(), 0, ico_path);
1103 return xpm_path;
1106 static HKEY open_menus_reg_key(void)
1108 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1109 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
1110 HKEY assocKey;
1111 DWORD ret;
1112 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
1113 if (ret == ERROR_SUCCESS)
1114 return assocKey;
1115 SetLastError(ret);
1116 return NULL;
1119 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
1121 WCHAR *unix_fileW;
1122 WCHAR *windows_fileW;
1123 INT size;
1124 DWORD ret;
1126 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
1127 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1128 if (unix_fileW)
1130 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
1131 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
1132 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1133 if (windows_fileW)
1135 HKEY hkey;
1136 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
1137 hkey = open_menus_reg_key();
1138 if (hkey)
1140 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
1141 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
1142 RegCloseKey(hkey);
1144 else
1145 ret = GetLastError();
1146 HeapFree(GetProcessHeap(), 0, windows_fileW);
1148 else
1149 ret = ERROR_NOT_ENOUGH_MEMORY;
1150 HeapFree(GetProcessHeap(), 0, unix_fileW);
1152 else
1153 ret = ERROR_NOT_ENOUGH_MEMORY;
1154 return ret;
1157 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
1158 const char *path, const char *args, const char *descr,
1159 const char *workdir, const char *icon)
1161 FILE *file;
1163 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1164 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1165 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1167 file = fopen(location, "w");
1168 if (file == NULL)
1169 return FALSE;
1171 fprintf(file, "[Desktop Entry]\n");
1172 fprintf(file, "Name=%s\n", linkname);
1173 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1174 wine_get_config_dir(), path, args);
1175 fprintf(file, "Type=Application\n");
1176 fprintf(file, "StartupNotify=true\n");
1177 if (descr && lstrlenA(descr))
1178 fprintf(file, "Comment=%s\n", descr);
1179 if (workdir && lstrlenA(workdir))
1180 fprintf(file, "Path=%s\n", workdir);
1181 if (icon && lstrlenA(icon))
1182 fprintf(file, "Icon=%s\n", icon);
1184 fclose(file);
1186 if (unix_link)
1188 DWORD ret = register_menus_entry(location, unix_link);
1189 if (ret != ERROR_SUCCESS)
1190 return FALSE;
1193 return TRUE;
1196 static BOOL write_directory_entry(const char *directory, const char *location)
1198 FILE *file;
1200 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
1202 file = fopen(location, "w");
1203 if (file == NULL)
1204 return FALSE;
1206 fprintf(file, "[Desktop Entry]\n");
1207 fprintf(file, "Type=Directory\n");
1208 if (strcmp(directory, "wine") == 0)
1210 fprintf(file, "Name=Wine\n");
1211 fprintf(file, "Icon=wine\n");
1213 else
1215 fprintf(file, "Name=%s\n", directory);
1216 fprintf(file, "Icon=folder\n");
1219 fclose(file);
1220 return TRUE;
1223 static BOOL write_menu_file(const char *unix_link, const char *filename)
1225 char *tempfilename;
1226 FILE *tempfile = NULL;
1227 char *lastEntry;
1228 char *name = NULL;
1229 char *menuPath = NULL;
1230 int i;
1231 int count = 0;
1232 BOOL ret = FALSE;
1234 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1236 while (1)
1238 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1239 if (tempfilename)
1241 int tempfd = mkstemps(tempfilename, 0);
1242 if (tempfd >= 0)
1244 tempfile = fdopen(tempfd, "w");
1245 if (tempfile)
1246 break;
1247 close(tempfd);
1248 goto end;
1250 else if (errno == EEXIST)
1252 HeapFree(GetProcessHeap(), 0, tempfilename);
1253 continue;
1255 HeapFree(GetProcessHeap(), 0, tempfilename);
1257 return FALSE;
1260 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1261 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1262 fprintf(tempfile, "<Menu>\n");
1263 fprintf(tempfile, " <Name>Applications</Name>\n");
1265 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1266 if (name == NULL) goto end;
1267 lastEntry = name;
1268 for (i = 0; filename[i]; i++)
1270 name[i] = filename[i];
1271 if (filename[i] == '/')
1273 char *dir_file_name;
1274 struct stat st;
1275 name[i] = 0;
1276 fprintf(tempfile, " <Menu>\n");
1277 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1278 write_xml_text(tempfile, name);
1279 fprintf(tempfile, "</Name>\n");
1280 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1281 write_xml_text(tempfile, name);
1282 fprintf(tempfile, ".directory</Directory>\n");
1283 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1284 xdg_data_dir, count ? "" : "wine-", name);
1285 if (dir_file_name)
1287 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1288 write_directory_entry(lastEntry, dir_file_name);
1289 HeapFree(GetProcessHeap(), 0, dir_file_name);
1291 name[i] = '-';
1292 lastEntry = &name[i+1];
1293 ++count;
1296 name[i] = 0;
1298 fprintf(tempfile, " <Include>\n");
1299 fprintf(tempfile, " <Filename>");
1300 write_xml_text(tempfile, name);
1301 fprintf(tempfile, "</Filename>\n");
1302 fprintf(tempfile, " </Include>\n");
1303 for (i = 0; i < count; i++)
1304 fprintf(tempfile, " </Menu>\n");
1305 fprintf(tempfile, "</Menu>\n");
1307 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1308 if (menuPath == NULL) goto end;
1309 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1310 ret = TRUE;
1312 end:
1313 if (tempfile)
1314 fclose(tempfile);
1315 if (ret)
1316 ret = (rename(tempfilename, menuPath) == 0);
1317 if (!ret && tempfilename)
1318 remove(tempfilename);
1319 HeapFree(GetProcessHeap(), 0, tempfilename);
1320 if (ret)
1321 register_menus_entry(menuPath, unix_link);
1322 HeapFree(GetProcessHeap(), 0, name);
1323 HeapFree(GetProcessHeap(), 0, menuPath);
1324 return ret;
1327 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1328 const char *descr, const char *workdir, const char *icon)
1330 const char *linkname;
1331 char *desktopPath = NULL;
1332 char *desktopDir;
1333 char *filename = NULL;
1334 BOOL ret = TRUE;
1336 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1337 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1338 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1340 linkname = strrchr(link, '/');
1341 if (linkname == NULL)
1342 linkname = link;
1343 else
1344 ++linkname;
1346 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1347 if (!desktopPath)
1349 WINE_WARN("out of memory creating menu entry\n");
1350 ret = FALSE;
1351 goto end;
1353 desktopDir = strrchr(desktopPath, '/');
1354 *desktopDir = 0;
1355 if (!create_directories(desktopPath))
1357 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1358 ret = FALSE;
1359 goto end;
1361 *desktopDir = '/';
1362 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1364 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1365 ret = FALSE;
1366 goto end;
1369 filename = heap_printf("wine/%s.desktop", link);
1370 if (!filename || !write_menu_file(unix_link, filename))
1372 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1373 ret = FALSE;
1376 end:
1377 HeapFree(GetProcessHeap(), 0, desktopPath);
1378 HeapFree(GetProcessHeap(), 0, filename);
1379 return ret;
1382 /* This escapes reserved characters in .desktop files' Exec keys. */
1383 static LPSTR escape(LPCWSTR arg)
1385 int i, j;
1386 WCHAR *escaped_string;
1387 char *utf8_string;
1389 escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
1390 if (escaped_string == NULL) return NULL;
1391 for (i = j = 0; arg[i]; i++)
1393 switch (arg[i])
1395 case '\\':
1396 escaped_string[j++] = '\\';
1397 escaped_string[j++] = '\\';
1398 escaped_string[j++] = '\\';
1399 escaped_string[j++] = '\\';
1400 break;
1401 case ' ':
1402 case '\t':
1403 case '\n':
1404 case '"':
1405 case '\'':
1406 case '>':
1407 case '<':
1408 case '~':
1409 case '|':
1410 case '&':
1411 case ';':
1412 case '$':
1413 case '*':
1414 case '?':
1415 case '#':
1416 case '(':
1417 case ')':
1418 case '`':
1419 escaped_string[j++] = '\\';
1420 escaped_string[j++] = '\\';
1421 /* fall through */
1422 default:
1423 escaped_string[j++] = arg[i];
1424 break;
1427 escaped_string[j] = 0;
1429 utf8_string = wchars_to_utf8_chars(escaped_string);
1430 if (utf8_string == NULL)
1432 WINE_ERR("out of memory\n");
1433 goto end;
1436 end:
1437 HeapFree(GetProcessHeap(), 0, escaped_string);
1438 return utf8_string;
1441 /* Return a heap-allocated copy of the unix format difference between the two
1442 * Windows-format paths.
1443 * locn is the owning location
1444 * link is within locn
1446 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1448 char *unix_locn, *unix_link;
1449 char *relative = NULL;
1451 unix_locn = wine_get_unix_file_name(locn);
1452 unix_link = wine_get_unix_file_name(link);
1453 if (unix_locn && unix_link)
1455 size_t len_unix_locn, len_unix_link;
1456 len_unix_locn = strlen (unix_locn);
1457 len_unix_link = strlen (unix_link);
1458 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1460 size_t len_rel;
1461 char *p = strrchr (unix_link + len_unix_locn, '/');
1462 p = strrchr (p, '.');
1463 if (p)
1465 *p = '\0';
1466 len_unix_link = p - unix_link;
1468 len_rel = len_unix_link - len_unix_locn;
1469 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1470 if (relative)
1472 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1476 if (!relative)
1477 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1478 HeapFree(GetProcessHeap(), 0, unix_locn);
1479 HeapFree(GetProcessHeap(), 0, unix_link);
1480 return relative;
1483 /***********************************************************************
1485 * GetLinkLocation
1487 * returns TRUE if successful
1488 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1489 * *relative will contain the address of a heap-allocated copy of the portion
1490 * of the filename that is within the specified location, in unix form
1492 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1494 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1495 DWORD len, i, r, filelen;
1496 const DWORD locations[] = {
1497 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1498 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1499 CSIDL_COMMON_STARTMENU };
1501 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1502 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1503 if (filelen==0 || filelen>MAX_PATH)
1504 return FALSE;
1506 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1508 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1509 * expand or our hardcoded list won't match.
1511 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1512 if (filelen==0 || filelen>MAX_PATH)
1513 return FALSE;
1515 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1517 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1519 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1520 continue;
1522 len = lstrlenW(buffer);
1523 if (len >= MAX_PATH)
1524 continue; /* We've just trashed memory! Hopefully we are OK */
1526 if (len > filelen || filename[len]!='\\')
1527 continue;
1528 /* do a lstrcmpinW */
1529 filename[len] = 0;
1530 r = lstrcmpiW( filename, buffer );
1531 filename[len] = '\\';
1532 if ( r )
1533 continue;
1535 /* return the remainder of the string and link type */
1536 *loc = locations[i];
1537 *relative = relative_path (filename, buffer);
1538 return (*relative != NULL);
1541 return FALSE;
1544 /* gets the target path directly or through MSI */
1545 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1546 LPWSTR szArgs, DWORD argsSize)
1548 IShellLinkDataList *dl = NULL;
1549 EXP_DARWIN_LINK *dar = NULL;
1550 HRESULT hr;
1552 szPath[0] = 0;
1553 szArgs[0] = 0;
1555 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1556 if (hr == S_OK && szPath[0])
1558 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1559 return hr;
1562 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1563 if (FAILED(hr))
1564 return hr;
1566 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1567 if (SUCCEEDED(hr))
1569 WCHAR* szCmdline;
1570 DWORD cmdSize;
1572 cmdSize=0;
1573 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1574 if (hr == ERROR_SUCCESS)
1576 cmdSize++;
1577 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1578 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1579 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1580 if (hr == ERROR_SUCCESS)
1582 WCHAR *s, *d;
1583 int bcount, in_quotes;
1585 /* Extract the application path */
1586 bcount=0;
1587 in_quotes=0;
1588 s=szCmdline;
1589 d=szPath;
1590 while (*s)
1592 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1594 /* skip the remaining spaces */
1595 do {
1596 s++;
1597 } while (*s==0x0009 || *s==0x0020);
1598 break;
1600 else if (*s==0x005c)
1602 /* '\\' */
1603 *d++=*s++;
1604 bcount++;
1606 else if (*s==0x0022)
1608 /* '"' */
1609 if ((bcount & 1)==0)
1611 /* Preceded by an even number of '\', this is
1612 * half that number of '\', plus a quote which
1613 * we erase.
1615 d-=bcount/2;
1616 in_quotes=!in_quotes;
1617 s++;
1619 else
1621 /* Preceded by an odd number of '\', this is
1622 * half that number of '\' followed by a '"'
1624 d=d-bcount/2-1;
1625 *d++='"';
1626 s++;
1628 bcount=0;
1630 else
1632 /* a regular character */
1633 *d++=*s++;
1634 bcount=0;
1636 if ((d-szPath) == pathSize)
1638 /* Keep processing the path till we get to the
1639 * arguments, but 'stand still'
1641 d--;
1644 /* Close the application path */
1645 *d=0;
1647 lstrcpynW(szArgs, s, argsSize);
1649 HeapFree( GetProcessHeap(), 0, szCmdline );
1651 LocalFree( dar );
1654 IShellLinkDataList_Release( dl );
1655 return hr;
1658 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1660 HRESULT hr;
1661 WCHAR *value = NULL;
1662 DWORD size = 0;
1663 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1664 if (SUCCEEDED(hr))
1666 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1667 if (value)
1669 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1670 if (FAILED(hr))
1672 HeapFree(GetProcessHeap(), 0, value);
1673 value = NULL;
1677 return value;
1680 static char *slashes_to_minuses(const char *string)
1682 int i;
1683 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1684 if (ret)
1686 for (i = 0; string[i]; i++)
1688 if (string[i] == '/')
1689 ret[i] = '-';
1690 else
1691 ret[i] = string[i];
1693 ret[i] = 0;
1694 return ret;
1696 return NULL;
1699 static BOOL next_line(FILE *file, char **line, int *size)
1701 int pos = 0;
1702 char *cr;
1703 if (*line == NULL)
1705 *size = 4096;
1706 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1708 while (*line != NULL)
1710 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1712 HeapFree(GetProcessHeap(), 0, *line);
1713 *line = NULL;
1714 if (feof(file))
1715 return TRUE;
1716 return FALSE;
1718 pos = strlen(*line);
1719 cr = strchr(*line, '\n');
1720 if (cr == NULL)
1722 char *line2;
1723 (*size) *= 2;
1724 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1725 if (line2)
1726 *line = line2;
1727 else
1729 HeapFree(GetProcessHeap(), 0, *line);
1730 *line = NULL;
1733 else
1735 *cr = 0;
1736 return TRUE;
1739 return FALSE;
1742 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1744 char *globs_filename = NULL;
1745 BOOL ret = TRUE;
1746 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1747 if (globs_filename)
1749 FILE *globs_file = fopen(globs_filename, "r");
1750 if (globs_file) /* doesn't have to exist */
1752 char *line = NULL;
1753 int size = 0;
1754 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1756 char *pos;
1757 struct xdg_mime_type *mime_type_entry = NULL;
1758 if (line[0] != '#' && (pos = strchr(line, ':')))
1760 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1761 if (mime_type_entry)
1763 *pos = 0;
1764 mime_type_entry->mimeType = strdupA(line);
1765 mime_type_entry->glob = strdupA(pos + 1);
1766 if (mime_type_entry->mimeType && mime_type_entry->glob)
1767 list_add_tail(mime_types, &mime_type_entry->entry);
1768 else
1770 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1771 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1772 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1773 ret = FALSE;
1776 else
1777 ret = FALSE;
1780 HeapFree(GetProcessHeap(), 0, line);
1781 fclose(globs_file);
1783 HeapFree(GetProcessHeap(), 0, globs_filename);
1785 else
1786 ret = FALSE;
1787 return ret;
1790 static void free_native_mime_types(struct list *native_mime_types)
1792 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1794 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1796 list_remove(&mime_type_entry->entry);
1797 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1798 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1799 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1801 HeapFree(GetProcessHeap(), 0, native_mime_types);
1804 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1806 char *xdg_data_dirs;
1807 BOOL ret;
1809 *mime_types = NULL;
1811 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1812 if (xdg_data_dirs == NULL)
1813 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1814 else
1815 xdg_data_dirs = strdupA(xdg_data_dirs);
1817 if (xdg_data_dirs)
1819 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1820 if (*mime_types)
1822 const char *begin;
1823 char *end;
1825 list_init(*mime_types);
1826 ret = add_mimes(xdg_data_home, *mime_types);
1827 if (ret)
1829 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1831 *end = '\0';
1832 ret = add_mimes(begin, *mime_types);
1833 *end = ':';
1834 if (!ret)
1835 break;
1837 if (ret)
1838 ret = add_mimes(begin, *mime_types);
1841 else
1842 ret = FALSE;
1843 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1845 else
1846 ret = FALSE;
1847 if (!ret && *mime_types)
1849 free_native_mime_types(*mime_types);
1850 *mime_types = NULL;
1852 return ret;
1855 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1856 char **match)
1858 #ifdef HAVE_FNMATCH
1859 struct xdg_mime_type *mime_type_entry;
1860 int matchLength = 0;
1862 *match = NULL;
1864 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1866 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1868 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1870 *match = mime_type_entry->mimeType;
1871 matchLength = strlen(mime_type_entry->glob);
1876 if (*match != NULL)
1878 *match = strdupA(*match);
1879 if (*match == NULL)
1880 return FALSE;
1882 #else
1883 *match = NULL;
1884 #endif
1885 return TRUE;
1888 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1889 const char *extensionA,
1890 LPCWSTR extensionW,
1891 char **mime_type)
1893 WCHAR *lower_extensionW;
1894 INT len;
1895 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1896 if (ret == FALSE || *mime_type != NULL)
1897 return ret;
1898 len = strlenW(extensionW);
1899 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1900 if (lower_extensionW)
1902 char *lower_extensionA;
1903 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1904 strlwrW(lower_extensionW);
1905 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1906 if (lower_extensionA)
1908 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1909 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1911 else
1913 ret = FALSE;
1914 WINE_FIXME("out of memory\n");
1916 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1918 else
1920 ret = FALSE;
1921 WINE_FIXME("out of memory\n");
1923 return ret;
1926 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1928 DWORD size;
1929 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1931 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1932 if (ret)
1934 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1935 return ret;
1937 HeapFree(GetProcessHeap(), 0, ret);
1939 return NULL;
1942 static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
1944 WCHAR *valW = reg_get_valW(key, subkey, name);
1945 if (valW)
1947 char *val = wchars_to_utf8_chars(valW);
1948 HeapFree(GetProcessHeap(), 0, valW);
1949 return val;
1951 return NULL;
1954 static HKEY open_associations_reg_key(void)
1956 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1957 '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};
1958 HKEY assocKey;
1959 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1960 return assocKey;
1961 return NULL;
1964 static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1966 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1967 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1968 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
1969 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
1970 HKEY assocKey;
1971 BOOL ret;
1973 if ((assocKey = open_associations_reg_key()))
1975 CHAR *valueA;
1976 WCHAR *value;
1978 ret = FALSE;
1980 valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
1981 if (!valueA || lstrcmpA(valueA, mimeType))
1982 ret = TRUE;
1983 HeapFree(GetProcessHeap(), 0, valueA);
1985 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1986 if (!value || strcmpW(value, progId))
1987 ret = TRUE;
1988 HeapFree(GetProcessHeap(), 0, value);
1990 valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
1991 if (!valueA || lstrcmpA(valueA, appName))
1992 ret = TRUE;
1993 HeapFree(GetProcessHeap(), 0, valueA);
1995 value = reg_get_valW(assocKey, extensionW, DocNameW);
1996 if (docName && (!value || strcmpW(value, docName)))
1997 ret = TRUE;
1998 HeapFree(GetProcessHeap(), 0, value);
2000 RegCloseKey(assocKey);
2002 else
2004 WINE_ERR("error opening associations registry key\n");
2005 ret = FALSE;
2007 return ret;
2010 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
2012 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2013 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
2014 static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
2015 static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2016 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2017 HKEY assocKey = NULL;
2018 HKEY subkey = NULL;
2019 WCHAR *mimeTypeW = NULL;
2020 WCHAR *appNameW = NULL;
2021 WCHAR *desktopFileW = NULL;
2023 assocKey = open_associations_reg_key();
2024 if (assocKey == NULL)
2026 WINE_ERR("could not open file associations key\n");
2027 goto done;
2030 if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2032 WINE_ERR("could not create extension subkey\n");
2033 goto done;
2036 mimeTypeW = utf8_chars_to_wchars(mimeType);
2037 if (mimeTypeW == NULL)
2039 WINE_ERR("out of memory\n");
2040 goto done;
2043 appNameW = utf8_chars_to_wchars(appName);
2044 if (appNameW == NULL)
2046 WINE_ERR("out of memory\n");
2047 goto done;
2050 desktopFileW = utf8_chars_to_wchars(desktopFile);
2051 if (desktopFileW == NULL)
2053 WINE_ERR("out of memory\n");
2054 goto done;
2057 RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
2058 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
2059 RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2060 if (docName)
2061 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
2062 RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2064 done:
2065 RegCloseKey(assocKey);
2066 RegCloseKey(subkey);
2067 HeapFree(GetProcessHeap(), 0, mimeTypeW);
2068 HeapFree(GetProcessHeap(), 0, appNameW);
2069 HeapFree(GetProcessHeap(), 0, desktopFileW);
2072 static BOOL cleanup_associations(void)
2074 static const WCHAR openW[] = {'o','p','e','n',0};
2075 static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2076 HKEY assocKey;
2077 BOOL hasChanged = FALSE;
2078 if ((assocKey = open_associations_reg_key()))
2080 int i;
2081 BOOL done = FALSE;
2082 for (i = 0; !done; i++)
2084 WCHAR *extensionW = NULL;
2085 DWORD size = 1024;
2086 LSTATUS ret;
2090 HeapFree(GetProcessHeap(), 0, extensionW);
2091 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2092 if (extensionW == NULL)
2094 WINE_ERR("out of memory\n");
2095 ret = ERROR_OUTOFMEMORY;
2096 break;
2098 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
2099 size *= 2;
2100 } while (ret == ERROR_MORE_DATA);
2102 if (ret == ERROR_SUCCESS)
2104 WCHAR *command;
2105 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2106 if (command == NULL)
2108 char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2109 if (desktopFile)
2111 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2112 remove(desktopFile);
2114 RegDeleteKeyW(assocKey, extensionW);
2115 hasChanged = TRUE;
2116 HeapFree(GetProcessHeap(), 0, desktopFile);
2118 HeapFree(GetProcessHeap(), 0, command);
2120 else
2122 if (ret != ERROR_NO_MORE_ITEMS)
2123 WINE_ERR("error %d while reading registry\n", ret);
2124 done = TRUE;
2126 HeapFree(GetProcessHeap(), 0, extensionW);
2128 RegCloseKey(assocKey);
2130 else
2131 WINE_ERR("could not open file associations key\n");
2132 return hasChanged;
2135 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
2136 const char *mime_type, const char *comment)
2138 BOOL ret = FALSE;
2139 char *filename;
2141 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
2142 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
2144 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
2145 if (filename)
2147 FILE *packageFile = fopen(filename, "w");
2148 if (packageFile)
2150 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2151 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2152 fprintf(packageFile, " <mime-type type=\"");
2153 write_xml_text(packageFile, mime_type);
2154 fprintf(packageFile, "\">\n");
2155 fprintf(packageFile, " <glob pattern=\"*");
2156 write_xml_text(packageFile, dot_extension);
2157 fprintf(packageFile, "\"/>\n");
2158 if (comment)
2160 fprintf(packageFile, " <comment>");
2161 write_xml_text(packageFile, comment);
2162 fprintf(packageFile, "</comment>\n");
2164 fprintf(packageFile, " </mime-type>\n");
2165 fprintf(packageFile, "</mime-info>\n");
2166 ret = TRUE;
2167 fclose(packageFile);
2169 else
2170 WINE_ERR("error writing file %s\n", filename);
2171 HeapFree(GetProcessHeap(), 0, filename);
2173 else
2174 WINE_ERR("out of memory\n");
2175 return ret;
2178 static BOOL is_extension_blacklisted(LPCWSTR extension)
2180 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
2181 static const WCHAR comW[] = {'.','c','o','m',0};
2182 static const WCHAR exeW[] = {'.','e','x','e',0};
2183 static const WCHAR msiW[] = {'.','m','s','i',0};
2185 if (!strcmpiW(extension, comW) ||
2186 !strcmpiW(extension, exeW) ||
2187 !strcmpiW(extension, msiW))
2188 return TRUE;
2189 return FALSE;
2192 static const char* get_special_mime_type(LPCWSTR extension)
2194 static const WCHAR lnkW[] = {'.','l','n','k',0};
2195 if (!strcmpiW(extension, lnkW))
2196 return "application/x-ms-shortcut";
2197 return NULL;
2200 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
2201 const char *friendlyAppName, const char *mimeType,
2202 const char *progId)
2204 BOOL ret = FALSE;
2205 FILE *desktop;
2207 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
2208 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2209 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
2211 desktop = fopen(desktopPath, "w");
2212 if (desktop)
2214 fprintf(desktop, "[Desktop Entry]\n");
2215 fprintf(desktop, "Type=Application\n");
2216 fprintf(desktop, "Name=%s\n", friendlyAppName);
2217 fprintf(desktop, "MimeType=%s\n", mimeType);
2218 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
2219 fprintf(desktop, "NoDisplay=true\n");
2220 fprintf(desktop, "StartupNotify=true\n");
2221 ret = TRUE;
2222 fclose(desktop);
2224 else
2225 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
2226 return ret;
2229 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
2231 static const WCHAR openW[] = {'o','p','e','n',0};
2232 struct list *nativeMimeTypes = NULL;
2233 LSTATUS ret = 0;
2234 int i;
2235 BOOL hasChanged = FALSE;
2237 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
2239 WINE_ERR("could not build native MIME types\n");
2240 return FALSE;
2243 for (i = 0; ; i++)
2245 WCHAR *extensionW = NULL;
2246 DWORD size = 1024;
2250 HeapFree(GetProcessHeap(), 0, extensionW);
2251 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2252 if (extensionW == NULL)
2254 WINE_ERR("out of memory\n");
2255 ret = ERROR_OUTOFMEMORY;
2256 break;
2258 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
2259 size *= 2;
2260 } while (ret == ERROR_MORE_DATA);
2262 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2264 char *extensionA = NULL;
2265 WCHAR *commandW = NULL;
2266 WCHAR *friendlyDocNameW = NULL;
2267 char *friendlyDocNameA = NULL;
2268 WCHAR *iconW = NULL;
2269 char *iconA = NULL;
2270 WCHAR *contentTypeW = NULL;
2271 char *mimeTypeA = NULL;
2272 WCHAR *friendlyAppNameW = NULL;
2273 char *friendlyAppNameA = NULL;
2274 WCHAR *progIdW = NULL;
2275 char *progIdA = NULL;
2277 extensionA = wchars_to_utf8_chars(extensionW);
2278 if (extensionA == NULL)
2280 WINE_ERR("out of memory\n");
2281 goto end;
2284 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2285 if (friendlyDocNameW)
2287 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2288 if (friendlyDocNameA == NULL)
2290 WINE_ERR("out of memory\n");
2291 goto end;
2295 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2297 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2298 if (contentTypeW)
2299 strlwrW(contentTypeW);
2301 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2302 goto end;
2304 if (mimeTypeA == NULL)
2306 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2307 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2308 else if ((get_special_mime_type(extensionW)))
2309 mimeTypeA = strdupA(get_special_mime_type(extensionW));
2310 else
2311 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2313 if (mimeTypeA != NULL)
2315 /* Gnome seems to ignore the <icon> tag in MIME packages,
2316 * and the default name is more intuitive anyway.
2318 if (iconW)
2320 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2321 if (flattened_mime)
2323 int index = 0;
2324 WCHAR *comma = strrchrW(iconW, ',');
2325 if (comma)
2327 *comma = 0;
2328 index = atoiW(comma + 1);
2330 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2331 HeapFree(GetProcessHeap(), 0, flattened_mime);
2335 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2336 hasChanged = TRUE;
2338 else
2340 WINE_FIXME("out of memory\n");
2341 goto end;
2345 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2346 if (commandW == NULL)
2347 /* no command => no application is associated */
2348 goto end;
2350 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2351 if (friendlyAppNameW)
2353 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2354 if (friendlyAppNameA == NULL)
2356 WINE_ERR("out of memory\n");
2357 goto end;
2360 else
2362 friendlyAppNameA = heap_printf("A Wine application");
2363 if (friendlyAppNameA == NULL)
2365 WINE_ERR("out of memory\n");
2366 goto end;
2370 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2371 if (progIdW)
2373 progIdA = escape(progIdW);
2374 if (progIdA == NULL)
2376 WINE_ERR("out of memory\n");
2377 goto end;
2380 else
2381 goto end; /* no progID => not a file type association */
2383 if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2385 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2386 if (desktopPath)
2388 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2390 hasChanged = TRUE;
2391 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2393 HeapFree(GetProcessHeap(), 0, desktopPath);
2397 end:
2398 HeapFree(GetProcessHeap(), 0, extensionA);
2399 HeapFree(GetProcessHeap(), 0, commandW);
2400 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2401 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2402 HeapFree(GetProcessHeap(), 0, iconW);
2403 HeapFree(GetProcessHeap(), 0, iconA);
2404 HeapFree(GetProcessHeap(), 0, contentTypeW);
2405 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2406 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2407 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2408 HeapFree(GetProcessHeap(), 0, progIdW);
2409 HeapFree(GetProcessHeap(), 0, progIdA);
2411 HeapFree(GetProcessHeap(), 0, extensionW);
2412 if (ret != ERROR_SUCCESS)
2413 break;
2416 free_native_mime_types(nativeMimeTypes);
2417 return hasChanged;
2420 static char *get_start_exe_path(void)
2422 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2423 '\\','s','t','a','r','t','.','e','x','e',0};
2424 WCHAR start_path[MAX_PATH];
2425 GetWindowsDirectoryW(start_path, MAX_PATH);
2426 lstrcatW(start_path, startW);
2427 return escape(start_path);
2430 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2432 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2433 '\\','s','t','a','r','t','.','e','x','e',0};
2434 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2435 char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2436 WCHAR szTmp[INFOTIPSIZE];
2437 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2438 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2439 int iIconId = 0, r = -1;
2440 DWORD csidl = -1;
2441 HANDLE hsem = NULL;
2442 char *unix_link = NULL;
2443 char *start_path = NULL;
2445 if ( !link )
2447 WINE_ERR("Link name is null\n");
2448 return FALSE;
2451 if( !GetLinkLocation( link, &csidl, &link_name ) )
2453 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2454 return TRUE;
2456 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2458 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2459 return TRUE;
2461 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2463 szTmp[0] = 0;
2464 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2465 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2466 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2468 szTmp[0] = 0;
2469 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2470 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2471 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2473 get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
2474 ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2475 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2476 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2478 szTmp[0] = 0;
2479 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2480 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2481 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2483 if( !szPath[0] )
2485 LPITEMIDLIST pidl = NULL;
2486 IShellLinkW_GetIDList( sl, &pidl );
2487 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2488 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2491 /* extract the icon */
2492 if( szIconPath[0] )
2493 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2494 else
2495 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2497 /* fail - try once again after parent process exit */
2498 if( !icon_name )
2500 if (bWait)
2502 WINE_WARN("Unable to extract icon, deferring.\n");
2503 goto cleanup;
2505 WINE_ERR("failed to extract icon from %s\n",
2506 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2509 unix_link = wine_get_unix_file_name(link);
2510 if (unix_link == NULL)
2512 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2513 goto cleanup;
2516 /* check the path */
2517 if( szPath[0] )
2519 static const WCHAR exeW[] = {'.','e','x','e',0};
2520 WCHAR *p;
2522 /* check for .exe extension */
2523 if (!(p = strrchrW( szPath, '.' )) ||
2524 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2525 lstrcmpiW( p, exeW ))
2527 /* Not .exe - use 'start.exe' to launch this file */
2528 p = szArgs + lstrlenW(szPath) + 2;
2529 if (szArgs[0])
2531 p[0] = ' ';
2532 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2533 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2535 else
2536 p[0] = 0;
2538 szArgs[0] = '"';
2539 lstrcpyW(szArgs + 1, szPath);
2540 p[-1] = '"';
2542 GetWindowsDirectoryW(szPath, MAX_PATH);
2543 lstrcatW(szPath, startW);
2546 /* convert app working dir */
2547 if (szWorkDir[0])
2548 work_dir = wine_get_unix_file_name( szWorkDir );
2550 else
2552 /* if there's no path... try run the link itself */
2553 lstrcpynW(szArgs, link, MAX_PATH);
2554 GetWindowsDirectoryW(szPath, MAX_PATH);
2555 lstrcatW(szPath, startW);
2558 /* escape the path and parameters */
2559 escaped_path = escape(szPath);
2560 escaped_args = escape(szArgs);
2561 description = wchars_to_utf8_chars(szDescription);
2562 if (escaped_path == NULL || escaped_args == NULL || description == NULL)
2564 WINE_ERR("out of memory allocating/escaping parameters\n");
2565 goto cleanup;
2568 start_path = get_start_exe_path();
2569 if (start_path == NULL)
2571 WINE_ERR("out of memory\n");
2572 goto cleanup;
2575 /* building multiple menus concurrently has race conditions */
2576 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2577 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2579 WINE_ERR("failed wait for semaphore\n");
2580 goto cleanup;
2583 if (in_desktop_dir(csidl))
2585 char *location;
2586 const char *lastEntry;
2587 lastEntry = strrchr(link_name, '/');
2588 if (lastEntry == NULL)
2589 lastEntry = link_name;
2590 else
2591 ++lastEntry;
2592 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2593 if (location)
2595 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name);
2596 if (r == 0)
2597 chmod(location, 0755);
2598 HeapFree(GetProcessHeap(), 0, location);
2601 else
2603 WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
2604 if (unix_linkW)
2606 char *escaped_lnk = escape(unix_linkW);
2607 if (escaped_lnk)
2609 char *menuarg = heap_printf("/Unix %s", escaped_lnk);
2610 if (menuarg)
2612 r = !write_menu_entry(unix_link, link_name, start_path, menuarg, description, work_dir, icon_name);
2613 HeapFree(GetProcessHeap(), 0, menuarg);
2615 HeapFree(GetProcessHeap(), 0, escaped_lnk);
2617 HeapFree(GetProcessHeap(), 0, unix_linkW);
2621 ReleaseSemaphore( hsem, 1, NULL );
2623 cleanup:
2624 if (hsem) CloseHandle( hsem );
2625 HeapFree( GetProcessHeap(), 0, icon_name );
2626 HeapFree( GetProcessHeap(), 0, work_dir );
2627 HeapFree( GetProcessHeap(), 0, link_name );
2628 HeapFree( GetProcessHeap(), 0, escaped_args );
2629 HeapFree( GetProcessHeap(), 0, escaped_path );
2630 HeapFree( GetProcessHeap(), 0, description );
2631 HeapFree( GetProcessHeap(), 0, unix_link );
2632 HeapFree( GetProcessHeap(), 0, start_path );
2634 if (r && !bWait)
2635 WINE_ERR("failed to build the menu\n" );
2637 return ( r == 0 );
2640 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2642 char *link_name = NULL;
2643 DWORD csidl = -1;
2644 LPWSTR urlPath;
2645 char *escaped_urlPath = NULL;
2646 HRESULT hr;
2647 HANDLE hSem = NULL;
2648 BOOL ret = TRUE;
2649 int r = -1;
2650 char *unix_link = NULL;
2652 if ( !link )
2654 WINE_ERR("Link name is null\n");
2655 return TRUE;
2658 if( !GetLinkLocation( link, &csidl, &link_name ) )
2660 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2661 return TRUE;
2663 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2665 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2666 ret = TRUE;
2667 goto cleanup;
2669 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2671 hr = url->lpVtbl->GetURL(url, &urlPath);
2672 if (FAILED(hr))
2674 ret = TRUE;
2675 goto cleanup;
2677 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2679 unix_link = wine_get_unix_file_name(link);
2680 if (unix_link == NULL)
2682 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2683 goto cleanup;
2686 escaped_urlPath = escape(urlPath);
2687 if (escaped_urlPath == NULL)
2689 WINE_ERR("couldn't escape url, out of memory\n");
2690 goto cleanup;
2693 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2694 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2696 WINE_ERR("failed wait for semaphore\n");
2697 goto cleanup;
2699 if (in_desktop_dir(csidl))
2701 char *location;
2702 const char *lastEntry;
2703 lastEntry = strrchr(link_name, '/');
2704 if (lastEntry == NULL)
2705 lastEntry = link_name;
2706 else
2707 ++lastEntry;
2708 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2709 if (location)
2711 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2712 if (r == 0)
2713 chmod(location, 0755);
2714 HeapFree(GetProcessHeap(), 0, location);
2717 else
2718 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2719 ret = (r != 0);
2720 ReleaseSemaphore(hSem, 1, NULL);
2722 cleanup:
2723 if (hSem)
2724 CloseHandle(hSem);
2725 HeapFree(GetProcessHeap(), 0, link_name);
2726 CoTaskMemFree( urlPath );
2727 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2728 HeapFree(GetProcessHeap(), 0, unix_link);
2729 return ret;
2732 static BOOL WaitForParentProcess( void )
2734 PROCESSENTRY32 procentry;
2735 HANDLE hsnapshot = NULL, hprocess = NULL;
2736 DWORD ourpid = GetCurrentProcessId();
2737 BOOL ret = FALSE, rc;
2739 WINE_TRACE("Waiting for parent process\n");
2740 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2741 INVALID_HANDLE_VALUE)
2743 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2744 goto done;
2747 procentry.dwSize = sizeof(PROCESSENTRY32);
2748 rc = Process32First( hsnapshot, &procentry );
2749 while (rc)
2751 if (procentry.th32ProcessID == ourpid) break;
2752 rc = Process32Next( hsnapshot, &procentry );
2754 if (!rc)
2756 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2757 goto done;
2760 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2761 NULL)
2763 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2764 GetLastError());
2765 goto done;
2768 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2769 ret = TRUE;
2770 else
2771 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2773 done:
2774 if (hprocess) CloseHandle( hprocess );
2775 if (hsnapshot) CloseHandle( hsnapshot );
2776 return ret;
2779 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2781 IShellLinkW *sl;
2782 IPersistFile *pf;
2783 HRESULT r;
2784 WCHAR fullname[MAX_PATH];
2785 DWORD len;
2787 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2789 if( !linkname[0] )
2791 WINE_ERR("link name missing\n");
2792 return 1;
2795 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2796 if (len==0 || len>MAX_PATH)
2798 WINE_ERR("couldn't get full path of link file\n");
2799 return 1;
2802 r = CoInitialize( NULL );
2803 if( FAILED( r ) )
2805 WINE_ERR("CoInitialize failed\n");
2806 return 1;
2809 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2810 &IID_IShellLinkW, (LPVOID *) &sl );
2811 if( FAILED( r ) )
2813 WINE_ERR("No IID_IShellLink\n");
2814 return 1;
2817 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2818 if( FAILED( r ) )
2820 WINE_ERR("No IID_IPersistFile\n");
2821 return 1;
2824 r = IPersistFile_Load( pf, fullname, STGM_READ );
2825 if( SUCCEEDED( r ) )
2827 /* If something fails (eg. Couldn't extract icon)
2828 * wait for parent process and try again
2830 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2832 WaitForParentProcess();
2833 InvokeShellLinker( sl, fullname, FALSE );
2836 else
2838 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2841 IPersistFile_Release( pf );
2842 IShellLinkW_Release( sl );
2844 CoUninitialize();
2846 return !r;
2849 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2851 IUniformResourceLocatorW *url;
2852 IPersistFile *pf;
2853 HRESULT r;
2854 WCHAR fullname[MAX_PATH];
2855 DWORD len;
2857 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2859 if( !urlname[0] )
2861 WINE_ERR("URL name missing\n");
2862 return 1;
2865 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2866 if (len==0 || len>MAX_PATH)
2868 WINE_ERR("couldn't get full path of URL file\n");
2869 return 1;
2872 r = CoInitialize( NULL );
2873 if( FAILED( r ) )
2875 WINE_ERR("CoInitialize failed\n");
2876 return 1;
2879 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2880 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2881 if( FAILED( r ) )
2883 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2884 return 1;
2887 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2888 if( FAILED( r ) )
2890 WINE_ERR("No IID_IPersistFile\n");
2891 return 1;
2893 r = IPersistFile_Load( pf, fullname, STGM_READ );
2894 if( SUCCEEDED( r ) )
2896 /* If something fails (eg. Couldn't extract icon)
2897 * wait for parent process and try again
2899 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2901 WaitForParentProcess();
2902 InvokeShellLinkerForURL( url, fullname, FALSE );
2906 IPersistFile_Release( pf );
2907 url->lpVtbl->Release( url );
2909 CoUninitialize();
2911 return !r;
2914 static void RefreshFileTypeAssociations(void)
2916 HANDLE hSem = NULL;
2917 char *mime_dir = NULL;
2918 char *packages_dir = NULL;
2919 char *applications_dir = NULL;
2920 BOOL hasChanged;
2922 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2923 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2925 WINE_ERR("failed wait for semaphore\n");
2926 CloseHandle(hSem);
2927 hSem = NULL;
2928 goto end;
2931 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2932 if (mime_dir == NULL)
2934 WINE_ERR("out of memory\n");
2935 goto end;
2937 create_directories(mime_dir);
2939 packages_dir = heap_printf("%s/packages", mime_dir);
2940 if (packages_dir == NULL)
2942 WINE_ERR("out of memory\n");
2943 goto end;
2945 create_directories(packages_dir);
2947 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2948 if (applications_dir == NULL)
2950 WINE_ERR("out of memory\n");
2951 goto end;
2953 create_directories(applications_dir);
2955 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2956 hasChanged |= cleanup_associations();
2957 if (hasChanged)
2959 const char *argv[3];
2961 argv[0] = "update-mime-database";
2962 argv[1] = mime_dir;
2963 argv[2] = NULL;
2964 spawnvp( _P_NOWAIT, argv[0], argv );
2966 argv[0] = "update-desktop-database";
2967 argv[1] = applications_dir;
2968 spawnvp( _P_NOWAIT, argv[0], argv );
2971 end:
2972 if (hSem)
2974 ReleaseSemaphore(hSem, 1, NULL);
2975 CloseHandle(hSem);
2977 HeapFree(GetProcessHeap(), 0, mime_dir);
2978 HeapFree(GetProcessHeap(), 0, packages_dir);
2979 HeapFree(GetProcessHeap(), 0, applications_dir);
2982 static void cleanup_menus(void)
2984 HKEY hkey;
2986 hkey = open_menus_reg_key();
2987 if (hkey)
2989 int i;
2990 LSTATUS lret = ERROR_SUCCESS;
2991 for (i = 0; lret == ERROR_SUCCESS; )
2993 WCHAR *value = NULL;
2994 WCHAR *data = NULL;
2995 DWORD valueSize = 4096;
2996 DWORD dataSize = 4096;
2997 while (1)
2999 lret = ERROR_OUTOFMEMORY;
3000 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3001 if (value == NULL)
3002 break;
3003 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3004 if (data == NULL)
3005 break;
3006 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3007 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
3008 break;
3009 valueSize *= 2;
3010 dataSize *= 2;
3011 HeapFree(GetProcessHeap(), 0, value);
3012 HeapFree(GetProcessHeap(), 0, data);
3013 value = data = NULL;
3015 if (lret == ERROR_SUCCESS)
3017 char *unix_file;
3018 char *windows_file;
3019 unix_file = wchars_to_unix_chars(value);
3020 windows_file = wchars_to_unix_chars(data);
3021 if (unix_file != NULL && windows_file != NULL)
3023 struct stat filestats;
3024 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
3026 WINE_TRACE("removing menu related file %s\n", unix_file);
3027 remove(unix_file);
3028 RegDeleteValueW(hkey, value);
3030 else
3031 i++;
3033 else
3035 WINE_ERR("out of memory enumerating menus\n");
3036 lret = ERROR_OUTOFMEMORY;
3038 HeapFree(GetProcessHeap(), 0, unix_file);
3039 HeapFree(GetProcessHeap(), 0, windows_file);
3041 else if (lret != ERROR_NO_MORE_ITEMS)
3042 WINE_ERR("error %d reading registry\n", lret);
3043 HeapFree(GetProcessHeap(), 0, value);
3044 HeapFree(GetProcessHeap(), 0, data);
3046 RegCloseKey(hkey);
3048 else
3049 WINE_ERR("error opening registry key, menu cleanup failed\n");
3052 static WCHAR *next_token( LPWSTR *p )
3054 LPWSTR token = NULL, t = *p;
3056 if( !t )
3057 return NULL;
3059 while( t && !token )
3061 switch( *t )
3063 case ' ':
3064 t++;
3065 continue;
3066 case '"':
3067 /* unquote the token */
3068 token = ++t;
3069 t = strchrW( token, '"' );
3070 if( t )
3071 *t++ = 0;
3072 break;
3073 case 0:
3074 t = NULL;
3075 break;
3076 default:
3077 token = t;
3078 t = strchrW( token, ' ' );
3079 if( t )
3080 *t++ = 0;
3081 break;
3084 *p = t;
3085 return token;
3088 static BOOL init_xdg(void)
3090 WCHAR shellDesktopPath[MAX_PATH];
3091 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
3092 if (SUCCEEDED(hr))
3093 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
3094 if (xdg_desktop_dir == NULL)
3096 WINE_ERR("error looking up the desktop directory\n");
3097 return FALSE;
3100 if (getenv("XDG_CONFIG_HOME"))
3101 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
3102 else
3103 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
3104 if (xdg_config_dir)
3106 create_directories(xdg_config_dir);
3107 if (getenv("XDG_DATA_HOME"))
3108 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3109 else
3110 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
3111 if (xdg_data_dir)
3113 char *buffer;
3114 create_directories(xdg_data_dir);
3115 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
3116 if (buffer)
3118 mkdir(buffer, 0777);
3119 HeapFree(GetProcessHeap(), 0, buffer);
3121 return TRUE;
3123 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
3125 WINE_ERR("out of memory\n");
3126 return FALSE;
3129 /***********************************************************************
3131 * wWinMain
3133 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3135 static const WCHAR dash_aW[] = {'-','a',0};
3136 static const WCHAR dash_rW[] = {'-','r',0};
3137 static const WCHAR dash_uW[] = {'-','u',0};
3138 static const WCHAR dash_wW[] = {'-','w',0};
3140 LPWSTR token = NULL, p;
3141 BOOL bWait = FALSE;
3142 BOOL bURL = FALSE;
3143 int ret = 0;
3145 if (!init_xdg())
3146 return 1;
3148 for( p = cmdline; p && *p; )
3150 token = next_token( &p );
3151 if( !token )
3152 break;
3153 if( !strcmpW( token, dash_aW ) )
3155 RefreshFileTypeAssociations();
3156 continue;
3158 if( !strcmpW( token, dash_rW ) )
3160 cleanup_menus();
3161 continue;
3163 if( !strcmpW( token, dash_wW ) )
3164 bWait = TRUE;
3165 else if ( !strcmpW( token, dash_uW ) )
3166 bURL = TRUE;
3167 else if( token[0] == '-' )
3169 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3171 else
3173 BOOL bRet;
3175 if (bURL)
3176 bRet = Process_URL( token, bWait );
3177 else
3178 bRet = Process_Link( token, bWait );
3179 if (!bRet)
3181 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3182 ret = 1;
3187 return ret;