winemenubuilder: Distinguish menu icons from association icons.
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blobd9d78523232f8577d68840324e1042d0f808808f
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_init_io);
192 MAKE_FUNCPTR(png_set_bgr);
193 MAKE_FUNCPTR(png_set_text);
194 MAKE_FUNCPTR(png_set_IHDR);
195 MAKE_FUNCPTR(png_write_end);
196 MAKE_FUNCPTR(png_write_info);
197 MAKE_FUNCPTR(png_write_row);
198 #undef MAKE_FUNCPTR
200 static void *load_libpng(void)
202 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
204 #define LOAD_FUNCPTR(f) \
205 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
206 libpng_handle = NULL; \
207 return NULL; \
209 LOAD_FUNCPTR(png_create_info_struct);
210 LOAD_FUNCPTR(png_create_write_struct);
211 LOAD_FUNCPTR(png_destroy_write_struct);
212 LOAD_FUNCPTR(png_init_io);
213 LOAD_FUNCPTR(png_set_bgr);
214 LOAD_FUNCPTR(png_set_IHDR);
215 LOAD_FUNCPTR(png_set_text);
216 LOAD_FUNCPTR(png_write_end);
217 LOAD_FUNCPTR(png_write_info);
218 LOAD_FUNCPTR(png_write_row);
219 #undef LOAD_FUNCPTR
221 return libpng_handle;
224 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
226 static const char comment_key[] = "Created from";
227 FILE *fp;
228 png_structp png_ptr;
229 png_infop info_ptr;
230 png_text comment;
231 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
232 BYTE *row, *copy = NULL;
233 const BYTE *pXOR, *pAND = NULL;
234 int nWidth = pIcon->bmiHeader.biWidth;
235 int nHeight = pIcon->bmiHeader.biHeight;
236 int nBpp = pIcon->bmiHeader.biBitCount;
238 switch (nBpp)
240 case 32:
241 color_type |= PNG_COLOR_MASK_ALPHA;
242 /* fall through */
243 case 24:
244 color_type |= PNG_COLOR_MASK_COLOR;
245 break;
246 default:
247 return FALSE;
250 if (!libpng_handle && !load_libpng())
252 WINE_WARN("Unable to load libpng\n");
253 return FALSE;
256 if (!(fp = fopen(png_filename, "w")))
258 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
259 return FALSE;
262 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
263 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
264 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
265 if (nHeight > nWidth)
267 nHeight /= 2;
268 pAND = pXOR + nHeight * nXORWidthBytes;
271 /* Apply mask if present */
272 if (pAND)
274 RGBQUAD bgColor;
276 /* copy bytes before modifying them */
277 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
278 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
279 pXOR = copy;
281 /* image and mask are upside down reversed */
282 row = copy + (nHeight - 1) * nXORWidthBytes;
284 /* top left corner */
285 bgColor.rgbRed = row[0];
286 bgColor.rgbGreen = row[1];
287 bgColor.rgbBlue = row[2];
288 bgColor.rgbReserved = 0;
290 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
291 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
292 if (MASK(j, i))
294 RGBQUAD *pixel = (RGBQUAD *)row;
295 pixel->rgbBlue = bgColor.rgbBlue;
296 pixel->rgbGreen = bgColor.rgbGreen;
297 pixel->rgbRed = bgColor.rgbRed;
298 if (nBpp == 32)
299 pixel->rgbReserved = bgColor.rgbReserved;
303 comment.text = NULL;
305 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
306 !(info_ptr = ppng_create_info_struct(png_ptr)))
307 goto error;
309 if (setjmp(png_jmpbuf(png_ptr)))
311 /* All future errors jump here */
312 WINE_ERR("png error\n");
313 goto error;
316 ppng_init_io(png_ptr, fp);
317 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
318 color_type,
319 PNG_INTERLACE_NONE,
320 PNG_COMPRESSION_TYPE_DEFAULT,
321 PNG_FILTER_TYPE_DEFAULT);
323 /* Set comment */
324 comment.compression = PNG_TEXT_COMPRESSION_NONE;
325 comment.key = (png_charp)comment_key;
326 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
327 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
328 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
329 comment.text_length = i - 1;
330 ppng_set_text(png_ptr, info_ptr, &comment, 1);
333 ppng_write_info(png_ptr, info_ptr);
334 ppng_set_bgr(png_ptr);
335 for (i = nHeight - 1; i >= 0 ; i--)
336 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
337 ppng_write_end(png_ptr, info_ptr);
339 ppng_destroy_write_struct(&png_ptr, &info_ptr);
340 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
341 fclose(fp);
342 HeapFree(GetProcessHeap(), 0, copy);
343 HeapFree(GetProcessHeap(), 0, comment.text);
344 return TRUE;
346 error:
347 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
348 fclose(fp);
349 unlink(png_filename);
350 HeapFree(GetProcessHeap(), 0, copy);
351 HeapFree(GetProcessHeap(), 0, comment.text);
352 return FALSE;
354 #endif /* SONAME_LIBPNG */
356 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
358 FILE *fXPMFile;
359 int nHeight;
360 int nXORWidthBytes;
361 int nANDWidthBytes;
362 BOOL b8BitColors;
363 int nColors;
364 const BYTE *pXOR;
365 const BYTE *pAND;
366 BOOL aColorUsed[256] = {0};
367 int nColorsUsed = 0;
368 int i,j;
369 char *comment;
371 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
373 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
374 return FALSE;
377 if (!(fXPMFile = fopen(szXPMFileName, "w")))
379 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
380 return FALSE;
383 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
384 comment = HeapAlloc(GetProcessHeap(), 0, i);
385 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
387 nHeight = pIcon->bmiHeader.biHeight / 2;
388 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
389 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
390 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
391 + ((pIcon->bmiHeader.biWidth % 32) > 0));
392 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
393 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
394 : 1 << pIcon->bmiHeader.biBitCount;
395 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
396 pAND = pXOR + nHeight * nXORWidthBytes;
398 #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)
400 for (i = 0; i < nHeight; i++) {
401 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
402 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
404 aColorUsed[COLOR(j,i)] = TRUE;
405 nColorsUsed++;
410 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
411 goto error;
412 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
413 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
414 goto error;
416 for (i = 0; i < nColors; i++) {
417 if (aColorUsed[i])
418 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
419 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
420 goto error;
422 if (fprintf(fXPMFile, "\" c None\"") <= 0)
423 goto error;
425 for (i = 0; i < nHeight; i++)
427 if (fprintf(fXPMFile, ",\n\"") <= 0)
428 goto error;
429 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
431 if MASK(j,i)
433 if (fprintf(fXPMFile, " ") <= 0)
434 goto error;
436 else
437 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
438 goto error;
440 if (fprintf(fXPMFile, "\"") <= 0)
441 goto error;
443 if (fprintf(fXPMFile, "};\n") <= 0)
444 goto error;
446 #undef MASK
447 #undef COLOR
449 HeapFree(GetProcessHeap(), 0, comment);
450 fclose(fXPMFile);
451 return TRUE;
453 error:
454 HeapFree(GetProcessHeap(), 0, comment);
455 fclose(fXPMFile);
456 unlink( szXPMFileName );
457 return FALSE;
460 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
462 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
464 if (!sEnumRes->nIndex--)
466 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
467 return FALSE;
469 else
470 return TRUE;
473 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
475 HMODULE hModule;
476 HRSRC hResInfo;
477 LPCWSTR lpName = NULL;
478 HGLOBAL hResData;
479 GRPICONDIR *pIconDir;
480 BITMAPINFO *pIcon;
481 ENUMRESSTRUCT sEnumRes;
482 int nMax = 0;
483 int nMaxBits = 0;
484 int i;
485 BOOL ret = FALSE;
487 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
488 if (!hModule)
490 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
491 wine_dbgstr_w(szFileName), GetLastError());
492 return FALSE;
495 if (nIndex < 0)
497 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
498 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
499 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
501 else
503 hResInfo=NULL;
504 sEnumRes.pResInfo = &hResInfo;
505 sEnumRes.nIndex = nIndex;
506 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
507 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
508 sEnumRes.nIndex != -1)
510 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
514 if (hResInfo)
516 if ((hResData = LoadResource(hModule, hResInfo)))
518 if ((pIconDir = LockResource(hResData)))
520 for (i = 0; i < pIconDir->idCount; i++)
522 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
524 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
526 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
527 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
528 nMaxBits = pIconDir->idEntries[i].wBitCount;
534 FreeResource(hResData);
537 else
539 WINE_WARN("found no icon\n");
540 FreeLibrary(hModule);
541 return FALSE;
544 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
546 if ((hResData = LoadResource(hModule, hResInfo)))
548 if ((pIcon = LockResource(hResData)))
550 #ifdef SONAME_LIBPNG
551 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
552 ret = TRUE;
553 else
554 #endif
556 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
557 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
558 ret = TRUE;
562 FreeResource(hResData);
566 FreeLibrary(hModule);
567 return ret;
570 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
572 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
573 !extract_icon16(szFileName, szXPMFileName)*/)
574 return FALSE;
575 return TRUE;
578 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
580 FILE *fICOFile = NULL;
581 ICONDIR iconDir;
582 ICONDIRENTRY *pIconDirEntry = NULL;
583 int nMax = 0, nMaxBits = 0;
584 int nIndex = 0;
585 void *pIcon = NULL;
586 int i;
587 char *filename = NULL;
589 filename = wine_get_unix_file_name(szFileName);
590 if (!(fICOFile = fopen(filename, "r")))
592 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
593 goto error;
596 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
597 (iconDir.idReserved != 0) || (iconDir.idType != 1))
599 WINE_WARN("Invalid ico file format\n");
600 goto error;
603 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
604 goto error;
605 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
606 goto error;
608 for (i = 0; i < iconDir.idCount; i++)
610 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
611 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
612 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
614 nIndex = i;
615 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
616 nMaxBits = pIconDirEntry[i].wBitCount;
619 WINE_TRACE("Selected: %d\n", nIndex);
621 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
622 goto error;
623 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
624 goto error;
625 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
626 goto error;
629 /* Prefer PNG over XPM */
630 #ifdef SONAME_LIBPNG
631 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
632 #endif
634 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
635 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
636 goto error;
639 HeapFree(GetProcessHeap(), 0, pIcon);
640 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
641 fclose(fICOFile);
642 HeapFree(GetProcessHeap(), 0, filename);
643 return 1;
645 error:
646 HeapFree(GetProcessHeap(), 0, pIcon);
647 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
648 if (fICOFile) fclose(fICOFile);
649 HeapFree(GetProcessHeap(), 0, filename);
650 return 0;
653 static BOOL create_default_icon( const char *filename, const char* comment )
655 FILE *fXPM;
656 unsigned int i;
658 if (!(fXPM = fopen(filename, "w"))) return FALSE;
659 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
660 goto error;
661 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
662 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
663 goto error;
665 if (fprintf( fXPM, "};\n" ) <=0)
666 goto error;
667 fclose( fXPM );
668 return TRUE;
669 error:
670 fclose( fXPM );
671 unlink( filename );
672 return FALSE;
676 static unsigned short crc16(const char* string)
678 unsigned short crc = 0;
679 int i, j, xor_poly;
681 for (i = 0; string[i] != 0; i++)
683 char c = string[i];
684 for (j = 0; j < 8; c >>= 1, j++)
686 xor_poly = (c ^ crc) & 1;
687 crc >>= 1;
688 if (xor_poly)
689 crc ^= 0xa001;
692 return crc;
695 static char* heap_printf(const char *format, ...)
697 va_list args;
698 int size = 4096;
699 char *buffer;
700 int n;
702 va_start(args, format);
703 while (1)
705 buffer = HeapAlloc(GetProcessHeap(), 0, size);
706 if (buffer == NULL)
707 break;
708 n = vsnprintf(buffer, size, format, args);
709 if (n == -1)
710 size *= 2;
711 else if (n >= size)
712 size = n + 1;
713 else
714 break;
715 HeapFree(GetProcessHeap(), 0, buffer);
717 va_end(args);
718 return buffer;
721 static BOOL create_directories(char *directory)
723 BOOL ret = TRUE;
724 int i;
726 for (i = 0; directory[i]; i++)
728 if (i > 0 && directory[i] == '/')
730 directory[i] = 0;
731 mkdir(directory, 0777);
732 directory[i] = '/';
735 if (mkdir(directory, 0777) && errno != EEXIST)
736 ret = FALSE;
738 return ret;
741 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
742 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
744 unsigned short crc;
745 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
746 char* s;
747 int n;
749 /* Where should we save the icon? */
750 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
751 iconsdir = heap_printf("%s/icons", xdg_data_dir);
752 if (iconsdir)
754 if (mkdir(iconsdir, 0777) && errno != EEXIST)
756 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
757 goto end;
760 else
762 WINE_TRACE("no icon created\n");
763 return NULL;
766 /* Determine the icon base name */
767 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
768 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
769 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
770 s=ico_name=ico_path;
771 while (*s!='\0') {
772 if (*s=='/' || *s=='\\') {
773 *s='\\';
774 ico_name=s;
775 } else {
776 *s=tolower(*s);
778 s++;
780 if (*ico_name=='\\') *ico_name++='\0';
781 s=strrchr(ico_name,'.');
782 if (s) *s='\0';
784 /* Compute the source-path hash */
785 crc=crc16(ico_path);
787 /* Try to treat the source file as an exe */
788 if (destFilename)
789 xpm_path=HeapAlloc(GetProcessHeap(),0,strlen(iconsdir)+1+strlen(destFilename)+1+3);
790 else
791 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
792 if (xpm_path == NULL)
794 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
795 return NULL;
797 if (destFilename)
798 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
799 else
800 sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
801 if (ExtractFromEXEDLL( path, index, xpm_path ))
802 goto end;
804 /* Must be something else, ignore the index in that case */
805 if (destFilename)
806 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
807 else
808 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
809 if (ExtractFromICO( path, xpm_path))
810 goto end;
811 if (!bWait)
813 if (destFilename)
814 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
815 else
816 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
817 if (create_default_icon( xpm_path, ico_path ))
818 goto end;
821 HeapFree( GetProcessHeap(), 0, xpm_path );
822 xpm_path=NULL;
824 end:
825 HeapFree(GetProcessHeap(), 0, iconsdir);
826 HeapFree(GetProcessHeap(), 0, ico_path);
827 return xpm_path;
830 static HKEY open_menus_reg_key(void)
832 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
833 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
834 HKEY assocKey;
835 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
836 return assocKey;
837 return NULL;
840 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
841 const char *path, const char *args, const char *descr,
842 const char *workdir, const char *icon)
844 FILE *file;
846 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
847 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
848 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
850 file = fopen(location, "w");
851 if (file == NULL)
852 return FALSE;
854 fprintf(file, "[Desktop Entry]\n");
855 fprintf(file, "Name=%s\n", linkname);
856 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
857 wine_get_config_dir(), path, args);
858 fprintf(file, "Type=Application\n");
859 fprintf(file, "StartupNotify=true\n");
860 if (descr && lstrlenA(descr))
861 fprintf(file, "Comment=%s\n", descr);
862 if (workdir && lstrlenA(workdir))
863 fprintf(file, "Path=%s\n", workdir);
864 if (icon && lstrlenA(icon))
865 fprintf(file, "Icon=%s\n", icon);
867 fclose(file);
869 if (unix_link)
871 HKEY hkey = open_menus_reg_key();
872 if (hkey)
874 RegSetValueExA(hkey, location, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
875 RegCloseKey(hkey);
877 else
878 return FALSE;
881 return TRUE;
884 static BOOL write_directory_entry(const char *directory, const char *location)
886 FILE *file;
888 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
890 file = fopen(location, "w");
891 if (file == NULL)
892 return FALSE;
894 fprintf(file, "[Desktop Entry]\n");
895 fprintf(file, "Type=Directory\n");
896 if (strcmp(directory, "wine") == 0)
898 fprintf(file, "Name=Wine\n");
899 fprintf(file, "Icon=wine\n");
901 else
903 fprintf(file, "Name=%s\n", directory);
904 fprintf(file, "Icon=folder\n");
907 fclose(file);
908 return TRUE;
911 static BOOL write_menu_file(const char *unix_link, const char *filename)
913 char *tempfilename;
914 FILE *tempfile = NULL;
915 char *lastEntry;
916 char *name = NULL;
917 char *menuPath = NULL;
918 int i;
919 int count = 0;
920 BOOL ret = FALSE;
922 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
924 while (1)
926 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
927 if (tempfilename)
929 int tempfd = mkstemps(tempfilename, 0);
930 if (tempfd >= 0)
932 tempfile = fdopen(tempfd, "w");
933 if (tempfile)
934 break;
935 close(tempfd);
936 goto end;
938 else if (errno == EEXIST)
940 HeapFree(GetProcessHeap(), 0, tempfilename);
941 continue;
943 HeapFree(GetProcessHeap(), 0, tempfilename);
945 return FALSE;
948 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
949 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
950 fprintf(tempfile, "<Menu>\n");
951 fprintf(tempfile, " <Name>Applications</Name>\n");
953 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
954 if (name == NULL) goto end;
955 lastEntry = name;
956 for (i = 0; filename[i]; i++)
958 name[i] = filename[i];
959 if (filename[i] == '/')
961 char *dir_file_name;
962 struct stat st;
963 name[i] = 0;
964 fprintf(tempfile, " <Menu>\n");
965 fprintf(tempfile, " <Name>%s%s</Name>\n", count ? "" : "wine-", name);
966 fprintf(tempfile, " <Directory>%s%s.directory</Directory>\n", count ? "" : "wine-", name);
967 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
968 xdg_data_dir, count ? "" : "wine-", name);
969 if (dir_file_name)
971 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
972 write_directory_entry(lastEntry, dir_file_name);
973 HeapFree(GetProcessHeap(), 0, dir_file_name);
975 name[i] = '-';
976 lastEntry = &name[i+1];
977 ++count;
980 name[i] = 0;
982 fprintf(tempfile, " <Include>\n");
983 fprintf(tempfile, " <Filename>%s</Filename>\n", name);
984 fprintf(tempfile, " </Include>\n");
985 for (i = 0; i < count; i++)
986 fprintf(tempfile, " </Menu>\n");
987 fprintf(tempfile, "</Menu>\n");
989 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
990 if (menuPath == NULL) goto end;
991 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
992 ret = TRUE;
994 end:
995 if (tempfile)
996 fclose(tempfile);
997 if (ret)
998 ret = (rename(tempfilename, menuPath) == 0);
999 if (!ret && tempfilename)
1000 remove(tempfilename);
1001 HeapFree(GetProcessHeap(), 0, tempfilename);
1002 if (ret)
1004 HKEY hkey = open_menus_reg_key();
1005 if (hkey)
1007 RegSetValueExA(hkey, menuPath, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
1008 RegCloseKey(hkey);
1011 HeapFree(GetProcessHeap(), 0, name);
1012 HeapFree(GetProcessHeap(), 0, menuPath);
1013 return ret;
1016 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1017 const char *descr, const char *workdir, const char *icon)
1019 const char *linkname;
1020 char *desktopPath = NULL;
1021 char *desktopDir;
1022 char *filename = NULL;
1023 BOOL ret = TRUE;
1025 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1026 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1027 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1029 linkname = strrchr(link, '/');
1030 if (linkname == NULL)
1031 linkname = link;
1032 else
1033 ++linkname;
1035 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1036 if (!desktopPath)
1038 WINE_WARN("out of memory creating menu entry\n");
1039 ret = FALSE;
1040 goto end;
1042 desktopDir = strrchr(desktopPath, '/');
1043 *desktopDir = 0;
1044 if (!create_directories(desktopPath))
1046 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1047 ret = FALSE;
1048 goto end;
1050 *desktopDir = '/';
1051 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1053 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1054 ret = FALSE;
1055 goto end;
1058 filename = heap_printf("wine/%s.desktop", link);
1059 if (!filename || !write_menu_file(unix_link, filename))
1061 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1062 ret = FALSE;
1065 end:
1066 HeapFree(GetProcessHeap(), 0, desktopPath);
1067 HeapFree(GetProcessHeap(), 0, filename);
1068 return ret;
1071 /* This escapes \ in filenames */
1072 static LPSTR escape(LPCWSTR arg)
1074 LPSTR narg, x;
1075 LPCWSTR esc;
1076 int len = 0, n;
1078 esc = arg;
1079 while((esc = strchrW(esc, '\\')))
1081 esc++;
1082 len++;
1085 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1086 narg = HeapAlloc(GetProcessHeap(), 0, len);
1088 x = narg;
1089 while (*arg)
1091 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1092 x += n;
1093 len -= n;
1094 if (*arg == '\\')
1095 *x++='\\'; /* escape \ */
1096 arg++;
1098 *x = 0;
1099 return narg;
1102 /* Return a heap-allocated copy of the unix format difference between the two
1103 * Windows-format paths.
1104 * locn is the owning location
1105 * link is within locn
1107 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1109 char *unix_locn, *unix_link;
1110 char *relative = NULL;
1112 unix_locn = wine_get_unix_file_name(locn);
1113 unix_link = wine_get_unix_file_name(link);
1114 if (unix_locn && unix_link)
1116 size_t len_unix_locn, len_unix_link;
1117 len_unix_locn = strlen (unix_locn);
1118 len_unix_link = strlen (unix_link);
1119 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1121 size_t len_rel;
1122 char *p = strrchr (unix_link + len_unix_locn, '/');
1123 p = strrchr (p, '.');
1124 if (p)
1126 *p = '\0';
1127 len_unix_link = p - unix_link;
1129 len_rel = len_unix_link - len_unix_locn;
1130 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1131 if (relative)
1133 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1137 if (!relative)
1138 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1139 HeapFree(GetProcessHeap(), 0, unix_locn);
1140 HeapFree(GetProcessHeap(), 0, unix_link);
1141 return relative;
1144 /***********************************************************************
1146 * GetLinkLocation
1148 * returns TRUE if successful
1149 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1150 * *relative will contain the address of a heap-allocated copy of the portion
1151 * of the filename that is within the specified location, in unix form
1153 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1155 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1156 DWORD len, i, r, filelen;
1157 const DWORD locations[] = {
1158 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1159 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1160 CSIDL_COMMON_STARTMENU };
1162 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1163 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1164 if (filelen==0 || filelen>MAX_PATH)
1165 return FALSE;
1167 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1169 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1170 * expand or our hardcoded list won't match.
1172 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1173 if (filelen==0 || filelen>MAX_PATH)
1174 return FALSE;
1176 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1178 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1180 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1181 continue;
1183 len = lstrlenW(buffer);
1184 if (len >= MAX_PATH)
1185 continue; /* We've just trashed memory! Hopefully we are OK */
1187 if (len > filelen || filename[len]!='\\')
1188 continue;
1189 /* do a lstrcmpinW */
1190 filename[len] = 0;
1191 r = lstrcmpiW( filename, buffer );
1192 filename[len] = '\\';
1193 if ( r )
1194 continue;
1196 /* return the remainder of the string and link type */
1197 *loc = locations[i];
1198 *relative = relative_path (filename, buffer);
1199 return (*relative != NULL);
1202 return FALSE;
1205 /* gets the target path directly or through MSI */
1206 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1207 LPWSTR szArgs, DWORD argsSize)
1209 IShellLinkDataList *dl = NULL;
1210 EXP_DARWIN_LINK *dar = NULL;
1211 HRESULT hr;
1213 szPath[0] = 0;
1214 szArgs[0] = 0;
1216 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1217 if (hr == S_OK && szPath[0])
1219 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1220 return hr;
1223 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1224 if (FAILED(hr))
1225 return hr;
1227 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1228 if (SUCCEEDED(hr))
1230 WCHAR* szCmdline;
1231 DWORD cmdSize;
1233 cmdSize=0;
1234 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1235 if (hr == ERROR_SUCCESS)
1237 cmdSize++;
1238 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1239 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1240 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1241 if (hr == ERROR_SUCCESS)
1243 WCHAR *s, *d;
1244 int bcount, in_quotes;
1246 /* Extract the application path */
1247 bcount=0;
1248 in_quotes=0;
1249 s=szCmdline;
1250 d=szPath;
1251 while (*s)
1253 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1255 /* skip the remaining spaces */
1256 do {
1257 s++;
1258 } while (*s==0x0009 || *s==0x0020);
1259 break;
1261 else if (*s==0x005c)
1263 /* '\\' */
1264 *d++=*s++;
1265 bcount++;
1267 else if (*s==0x0022)
1269 /* '"' */
1270 if ((bcount & 1)==0)
1272 /* Preceded by an even number of '\', this is
1273 * half that number of '\', plus a quote which
1274 * we erase.
1276 d-=bcount/2;
1277 in_quotes=!in_quotes;
1278 s++;
1280 else
1282 /* Preceded by an odd number of '\', this is
1283 * half that number of '\' followed by a '"'
1285 d=d-bcount/2-1;
1286 *d++='"';
1287 s++;
1289 bcount=0;
1291 else
1293 /* a regular character */
1294 *d++=*s++;
1295 bcount=0;
1297 if ((d-szPath) == pathSize)
1299 /* Keep processing the path till we get to the
1300 * arguments, but 'stand still'
1302 d--;
1305 /* Close the application path */
1306 *d=0;
1308 lstrcpynW(szArgs, s, argsSize);
1310 HeapFree( GetProcessHeap(), 0, szCmdline );
1312 LocalFree( dar );
1315 IShellLinkDataList_Release( dl );
1316 return hr;
1319 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1321 HRESULT hr;
1322 WCHAR *value = NULL;
1323 DWORD size = 0;
1324 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1325 if (SUCCEEDED(hr))
1327 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1328 if (value)
1330 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1331 if (FAILED(hr))
1333 HeapFree(GetProcessHeap(), 0, value);
1334 value = NULL;
1338 return value;
1341 static char* wchars_to_utf8_chars(LPCWSTR string)
1343 char *ret;
1344 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
1345 ret = HeapAlloc(GetProcessHeap(), 0, size);
1346 if (ret)
1347 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
1348 return ret;
1351 static char *slashes_to_minuses(const char *string)
1353 int i;
1354 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1355 if (ret)
1357 for (i = 0; string[i]; i++)
1359 if (string[i] == '/')
1360 ret[i] = '-';
1361 else
1362 ret[i] = string[i];
1364 ret[i] = 0;
1365 return ret;
1367 return NULL;
1370 static BOOL next_line(FILE *file, char **line, int *size)
1372 int pos = 0;
1373 char *cr;
1374 if (*line == NULL)
1376 *size = 4096;
1377 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1379 while (*line != NULL)
1381 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1383 HeapFree(GetProcessHeap(), 0, *line);
1384 *line = NULL;
1385 if (feof(file))
1386 return TRUE;
1387 return FALSE;
1389 pos = strlen(*line);
1390 cr = strchr(*line, '\n');
1391 if (cr == NULL)
1393 char *line2;
1394 (*size) *= 2;
1395 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1396 if (line2)
1397 *line = line2;
1398 else
1400 HeapFree(GetProcessHeap(), 0, *line);
1401 *line = NULL;
1404 else
1406 *cr = 0;
1407 return TRUE;
1410 return FALSE;
1413 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1415 char *globs_filename = NULL;
1416 BOOL ret = TRUE;
1417 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1418 if (globs_filename)
1420 FILE *globs_file = fopen(globs_filename, "r");
1421 if (globs_file) /* doesn't have to exist */
1423 char *line = NULL;
1424 int size = 0;
1425 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1427 char *pos;
1428 struct xdg_mime_type *mime_type_entry = NULL;
1429 if (line[0] != '#' && (pos = strchr(line, ':')))
1431 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1432 if (mime_type_entry)
1434 *pos = 0;
1435 mime_type_entry->mimeType = heap_printf("%s", line);
1436 mime_type_entry->glob = heap_printf("%s", pos + 1);
1437 if (mime_type_entry->mimeType && mime_type_entry->glob)
1438 list_add_tail(mime_types, &mime_type_entry->entry);
1439 else
1441 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1442 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1443 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1444 ret = FALSE;
1447 else
1448 ret = FALSE;
1451 HeapFree(GetProcessHeap(), 0, line);
1452 fclose(globs_file);
1454 HeapFree(GetProcessHeap(), 0, globs_filename);
1456 else
1457 ret = FALSE;
1458 return ret;
1461 static void free_native_mime_types(struct list *native_mime_types)
1463 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1465 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1467 list_remove(&mime_type_entry->entry);
1468 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1469 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1470 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1472 HeapFree(GetProcessHeap(), 0, native_mime_types);
1475 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1477 char *xdg_data_dirs;
1478 BOOL ret;
1480 *mime_types = NULL;
1482 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1483 if (xdg_data_dirs == NULL)
1484 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1485 else
1486 xdg_data_dirs = heap_printf("%s", xdg_data_dirs);
1488 if (xdg_data_dirs)
1490 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1491 if (*mime_types)
1493 const char *begin;
1494 char *end;
1496 list_init(*mime_types);
1497 ret = add_mimes(xdg_data_home, *mime_types);
1498 if (ret)
1500 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1502 *end = '\0';
1503 ret = add_mimes(begin, *mime_types);
1504 *end = ':';
1505 if (!ret)
1506 break;
1508 if (ret)
1509 ret = add_mimes(begin, *mime_types);
1512 else
1513 ret = FALSE;
1514 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1516 else
1517 ret = FALSE;
1518 if (!ret && *mime_types)
1520 free_native_mime_types(*mime_types);
1521 *mime_types = NULL;
1523 return ret;
1526 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1527 char **match)
1529 #ifdef HAVE_FNMATCH
1530 struct xdg_mime_type *mime_type_entry;
1531 int matchLength = 0;
1533 *match = NULL;
1535 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1537 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1539 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1541 *match = mime_type_entry->mimeType;
1542 matchLength = strlen(mime_type_entry->glob);
1547 if (*match != NULL)
1549 *match = heap_printf("%s", *match);
1550 if (*match == NULL)
1551 return FALSE;
1553 #else
1554 *match = NULL;
1555 #endif
1556 return TRUE;
1559 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1560 const char *extensionA,
1561 LPCWSTR extensionW,
1562 char **mime_type)
1564 WCHAR *lower_extensionW;
1565 INT len;
1566 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1567 if (ret == FALSE || *mime_type != NULL)
1568 return ret;
1569 len = strlenW(extensionW);
1570 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1571 if (lower_extensionW)
1573 char *lower_extensionA;
1574 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1575 strlwrW(lower_extensionW);
1576 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1577 if (lower_extensionA)
1579 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1580 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1582 else
1584 ret = FALSE;
1585 WINE_FIXME("out of memory\n");
1587 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1589 else
1591 ret = FALSE;
1592 WINE_FIXME("out of memory\n");
1594 return ret;
1597 static CHAR* reg_get_valA(HKEY key, LPCSTR subkey, LPCSTR name)
1599 DWORD size;
1600 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1602 CHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1603 if (ret)
1605 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1606 return ret;
1608 HeapFree(GetProcessHeap(), 0, ret);
1610 return NULL;
1613 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1615 DWORD size;
1616 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1618 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1619 if (ret)
1621 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1622 return ret;
1624 HeapFree(GetProcessHeap(), 0, ret);
1626 return NULL;
1629 static HKEY open_associations_reg_key(void)
1631 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1632 '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};
1633 HKEY assocKey;
1634 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1635 return assocKey;
1636 return NULL;
1639 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1641 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1642 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1643 HKEY assocKey;
1644 BOOL ret;
1646 if ((assocKey = open_associations_reg_key()))
1648 CHAR *valueA;
1649 WCHAR *value;
1651 ret = FALSE;
1653 valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1654 if (!valueA || lstrcmpA(valueA, mimeType))
1655 ret = TRUE;
1656 HeapFree(GetProcessHeap(), 0, valueA);
1658 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1659 if (!value || strcmpW(value, progId))
1660 ret = TRUE;
1661 HeapFree(GetProcessHeap(), 0, value);
1663 valueA = reg_get_valA(assocKey, extensionA, "AppName");
1664 if (!valueA || lstrcmpA(valueA, appName))
1665 ret = TRUE;
1666 HeapFree(GetProcessHeap(), 0, valueA);
1668 value = reg_get_valW(assocKey, extensionW, DocNameW);
1669 if (docName && (!value || strcmpW(value, docName)))
1670 ret = TRUE;
1671 HeapFree(GetProcessHeap(), 0, value);
1673 RegCloseKey(assocKey);
1675 else
1677 WINE_ERR("error opening associations registry key\n");
1678 ret = FALSE;
1680 return ret;
1683 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1685 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1686 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1687 HKEY assocKey;
1689 if ((assocKey = open_associations_reg_key()))
1691 HKEY subkey;
1692 if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1694 RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (BYTE*) mimeType, lstrlenA(mimeType) + 1);
1695 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1696 RegSetValueExA(subkey, "AppName", 0, REG_SZ, (BYTE*) appName, lstrlenA(appName) + 1);
1697 if (docName)
1698 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1699 RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1700 RegCloseKey(subkey);
1702 else
1703 WINE_ERR("could not create extension subkey\n");
1704 RegCloseKey(assocKey);
1706 else
1707 WINE_ERR("could not open file associations key\n");
1710 static BOOL cleanup_associations(void)
1712 static const WCHAR openW[] = {'o','p','e','n',0};
1713 HKEY assocKey;
1714 BOOL hasChanged = FALSE;
1715 if ((assocKey = open_associations_reg_key()))
1717 int i;
1718 BOOL done = FALSE;
1719 for (i = 0; !done; i++)
1721 WCHAR *extensionW = NULL;
1722 char *extensionA = NULL;
1723 DWORD size = 1024;
1724 LSTATUS ret;
1728 HeapFree(GetProcessHeap(), 0, extensionW);
1729 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1730 if (extensionW == NULL)
1732 WINE_ERR("out of memory\n");
1733 ret = ERROR_OUTOFMEMORY;
1734 break;
1736 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1737 size *= 2;
1738 } while (ret == ERROR_MORE_DATA);
1740 if (ret == ERROR_SUCCESS)
1742 WCHAR *command;
1743 extensionA = wchars_to_utf8_chars(extensionW);
1744 if (extensionA == NULL)
1746 WINE_ERR("out of memory\n");
1747 done = TRUE;
1748 goto end;
1750 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1751 if (command == NULL)
1753 char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1754 if (desktopFile)
1756 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1757 remove(desktopFile);
1759 RegDeleteKeyW(assocKey, extensionW);
1760 hasChanged = TRUE;
1761 HeapFree(GetProcessHeap(), 0, desktopFile);
1763 HeapFree(GetProcessHeap(), 0, command);
1765 else
1767 if (ret != ERROR_NO_MORE_ITEMS)
1768 WINE_ERR("error %d while reading registry\n", ret);
1769 done = TRUE;
1771 end:
1772 HeapFree(GetProcessHeap(), 0, extensionA);
1773 HeapFree(GetProcessHeap(), 0, extensionW);
1775 RegCloseKey(assocKey);
1777 else
1778 WINE_ERR("could not open file associations key\n");
1779 return hasChanged;
1782 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1783 const char *mime_type, const char *comment)
1785 BOOL ret = FALSE;
1786 char *filename;
1788 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1789 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1791 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1792 if (filename)
1794 FILE *packageFile = fopen(filename, "w");
1795 if (packageFile)
1797 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1798 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1799 fprintf(packageFile, " <mime-type type=\"%s\">\n", mime_type);
1800 fprintf(packageFile, " <glob pattern=\"*%s\"/>\n", dot_extension);
1801 if (comment)
1802 fprintf(packageFile, " <comment>%s</comment>\n", comment);
1803 fprintf(packageFile, " </mime-type>\n");
1804 fprintf(packageFile, "</mime-info>\n");
1805 ret = TRUE;
1806 fclose(packageFile);
1808 else
1809 WINE_ERR("error writing file %s\n", filename);
1810 HeapFree(GetProcessHeap(), 0, filename);
1812 else
1813 WINE_ERR("out of memory\n");
1814 return ret;
1817 static BOOL is_extension_blacklisted(LPCWSTR extension)
1819 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1820 static const WCHAR comW[] = {'.','c','o','m',0};
1821 static const WCHAR exeW[] = {'.','e','x','e',0};
1822 static const WCHAR msiW[] = {'.','m','s','i',0};
1824 if (!strcmpiW(extension, comW) ||
1825 !strcmpiW(extension, exeW) ||
1826 !strcmpiW(extension, msiW))
1827 return TRUE;
1828 return FALSE;
1831 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1832 const char *friendlyAppName, const char *mimeType,
1833 const char *progId)
1835 BOOL ret = FALSE;
1836 FILE *desktop;
1838 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1839 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1840 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1842 desktop = fopen(desktopPath, "w");
1843 if (desktop)
1845 fprintf(desktop, "[Desktop Entry]\n");
1846 fprintf(desktop, "Type=Application\n");
1847 fprintf(desktop, "Name=%s\n", friendlyAppName);
1848 fprintf(desktop, "MimeType=%s\n", mimeType);
1849 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1850 fprintf(desktop, "NoDisplay=true\n");
1851 fprintf(desktop, "StartupNotify=true\n");
1852 ret = TRUE;
1853 fclose(desktop);
1855 else
1856 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1857 return ret;
1860 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1862 static const WCHAR openW[] = {'o','p','e','n',0};
1863 struct list *nativeMimeTypes = NULL;
1864 LSTATUS ret = 0;
1865 int i;
1866 BOOL hasChanged = FALSE;
1868 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1870 WINE_ERR("could not build native MIME types\n");
1871 return FALSE;
1874 for (i = 0; ; i++)
1876 WCHAR *extensionW = NULL;
1877 DWORD size = 1024;
1881 HeapFree(GetProcessHeap(), 0, extensionW);
1882 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1883 if (extensionW == NULL)
1885 WINE_ERR("out of memory\n");
1886 ret = ERROR_OUTOFMEMORY;
1887 break;
1889 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1890 size *= 2;
1891 } while (ret == ERROR_MORE_DATA);
1893 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1895 char *extensionA = NULL;
1896 WCHAR *commandW = NULL;
1897 WCHAR *friendlyDocNameW = NULL;
1898 char *friendlyDocNameA = NULL;
1899 WCHAR *iconW = NULL;
1900 char *iconA = NULL;
1901 WCHAR *contentTypeW = NULL;
1902 char *mimeTypeA = NULL;
1903 WCHAR *friendlyAppNameW = NULL;
1904 char *friendlyAppNameA = NULL;
1905 WCHAR *progIdW = NULL;
1906 char *progIdA = NULL;
1908 extensionA = wchars_to_utf8_chars(extensionW);
1909 if (extensionA == NULL)
1911 WINE_ERR("out of memory\n");
1912 goto end;
1915 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
1916 if (friendlyDocNameW)
1918 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
1919 if (friendlyDocNameA == NULL)
1921 WINE_ERR("out of memory\n");
1922 goto end;
1926 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
1928 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
1930 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
1931 goto end;
1933 if (mimeTypeA == NULL)
1935 if (contentTypeW != NULL)
1936 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
1937 else
1938 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
1940 if (mimeTypeA != NULL)
1942 /* Gnome seems to ignore the <icon> tag in MIME packages,
1943 * and the default name is more intuitive anyway.
1945 if (iconW)
1947 char *flattened_mime = slashes_to_minuses(mimeTypeA);
1948 if (flattened_mime)
1950 int index = 0;
1951 WCHAR *comma = strrchrW(iconW, ',');
1952 if (comma)
1954 *comma = 0;
1955 index = atoiW(comma + 1);
1957 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
1958 HeapFree(GetProcessHeap(), 0, flattened_mime);
1962 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
1963 hasChanged = TRUE;
1965 else
1967 WINE_FIXME("out of memory\n");
1968 goto end;
1972 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1973 if (commandW == NULL)
1974 /* no command => no application is associated */
1975 goto end;
1977 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
1978 if (friendlyAppNameW)
1980 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
1981 if (friendlyAppNameA == NULL)
1983 WINE_ERR("out of memory\n");
1984 goto end;
1987 else
1989 friendlyAppNameA = heap_printf("A Wine application");
1990 if (friendlyAppNameA == NULL)
1992 WINE_ERR("out of memory\n");
1993 goto end;
1997 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
1998 if (progIdW)
2000 progIdA = wchars_to_utf8_chars(progIdW);
2001 if (progIdA == NULL)
2003 WINE_ERR("out of memory\n");
2004 goto end;
2007 else
2008 goto end; /* no progID => not a file type association */
2010 if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2012 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2013 if (desktopPath)
2015 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2017 hasChanged = TRUE;
2018 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2020 HeapFree(GetProcessHeap(), 0, desktopPath);
2024 end:
2025 HeapFree(GetProcessHeap(), 0, extensionA);
2026 HeapFree(GetProcessHeap(), 0, commandW);
2027 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2028 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2029 HeapFree(GetProcessHeap(), 0, iconW);
2030 HeapFree(GetProcessHeap(), 0, iconA);
2031 HeapFree(GetProcessHeap(), 0, contentTypeW);
2032 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2033 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2034 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2035 HeapFree(GetProcessHeap(), 0, progIdW);
2036 HeapFree(GetProcessHeap(), 0, progIdA);
2038 HeapFree(GetProcessHeap(), 0, extensionW);
2039 if (ret != ERROR_SUCCESS)
2040 break;
2043 free_native_mime_types(nativeMimeTypes);
2044 return hasChanged;
2047 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2049 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2050 '\\','s','t','a','r','t','.','e','x','e',0};
2051 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2052 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
2053 WCHAR szTmp[INFOTIPSIZE];
2054 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2055 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2056 int iIconId = 0, r = -1;
2057 DWORD csidl = -1;
2058 HANDLE hsem = NULL;
2059 char *unix_link = NULL;
2061 if ( !link )
2063 WINE_ERR("Link name is null\n");
2064 return FALSE;
2067 if( !GetLinkLocation( link, &csidl, &link_name ) )
2069 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2070 return TRUE;
2072 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2074 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2075 return TRUE;
2077 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2079 szTmp[0] = 0;
2080 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2081 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2082 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2084 szTmp[0] = 0;
2085 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2086 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2087 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2089 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
2090 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2091 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2093 szTmp[0] = 0;
2094 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2095 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2096 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2098 if( !szPath[0] )
2100 LPITEMIDLIST pidl = NULL;
2101 IShellLinkW_GetIDList( sl, &pidl );
2102 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2103 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2106 /* extract the icon */
2107 if( szIconPath[0] )
2108 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2109 else
2110 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2112 /* fail - try once again after parent process exit */
2113 if( !icon_name )
2115 if (bWait)
2117 WINE_WARN("Unable to extract icon, deferring.\n");
2118 goto cleanup;
2120 WINE_ERR("failed to extract icon from %s\n",
2121 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2124 unix_link = wine_get_unix_file_name(link);
2125 if (unix_link == NULL)
2127 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2128 goto cleanup;
2131 /* check the path */
2132 if( szPath[0] )
2134 static const WCHAR exeW[] = {'.','e','x','e',0};
2135 WCHAR *p;
2137 /* check for .exe extension */
2138 if (!(p = strrchrW( szPath, '.' )) ||
2139 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2140 lstrcmpiW( p, exeW ))
2142 /* Not .exe - use 'start.exe' to launch this file */
2143 p = szArgs + lstrlenW(szPath) + 2;
2144 if (szArgs[0])
2146 p[0] = ' ';
2147 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2148 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2150 else
2151 p[0] = 0;
2153 szArgs[0] = '"';
2154 lstrcpyW(szArgs + 1, szPath);
2155 p[-1] = '"';
2157 GetWindowsDirectoryW(szPath, MAX_PATH);
2158 lstrcatW(szPath, startW);
2161 /* convert app working dir */
2162 if (szWorkDir[0])
2163 work_dir = wine_get_unix_file_name( szWorkDir );
2165 else
2167 /* if there's no path... try run the link itself */
2168 lstrcpynW(szArgs, link, MAX_PATH);
2169 GetWindowsDirectoryW(szPath, MAX_PATH);
2170 lstrcatW(szPath, startW);
2173 /* escape the path and parameters */
2174 escaped_path = escape(szPath);
2175 escaped_args = escape(szArgs);
2176 escaped_description = escape(szDescription);
2178 /* building multiple menus concurrently has race conditions */
2179 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2180 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2182 WINE_ERR("failed wait for semaphore\n");
2183 goto cleanup;
2186 if (in_desktop_dir(csidl))
2188 char *location;
2189 const char *lastEntry;
2190 lastEntry = strrchr(link_name, '/');
2191 if (lastEntry == NULL)
2192 lastEntry = link_name;
2193 else
2194 ++lastEntry;
2195 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2196 if (location)
2198 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2199 HeapFree(GetProcessHeap(), 0, location);
2202 else
2203 r = !write_menu_entry(unix_link, link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2205 ReleaseSemaphore( hsem, 1, NULL );
2207 cleanup:
2208 if (hsem) CloseHandle( hsem );
2209 HeapFree( GetProcessHeap(), 0, icon_name );
2210 HeapFree( GetProcessHeap(), 0, work_dir );
2211 HeapFree( GetProcessHeap(), 0, link_name );
2212 HeapFree( GetProcessHeap(), 0, escaped_args );
2213 HeapFree( GetProcessHeap(), 0, escaped_path );
2214 HeapFree( GetProcessHeap(), 0, escaped_description );
2215 HeapFree( GetProcessHeap(), 0, unix_link);
2217 if (r && !bWait)
2218 WINE_ERR("failed to build the menu\n" );
2220 return ( r == 0 );
2223 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2225 char *link_name = NULL;
2226 DWORD csidl = -1;
2227 LPWSTR urlPath;
2228 char *escaped_urlPath = NULL;
2229 HRESULT hr;
2230 HANDLE hSem = NULL;
2231 BOOL ret = TRUE;
2232 int r = -1;
2233 char *unix_link = NULL;
2235 if ( !link )
2237 WINE_ERR("Link name is null\n");
2238 return TRUE;
2241 if( !GetLinkLocation( link, &csidl, &link_name ) )
2243 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2244 return TRUE;
2246 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2248 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2249 ret = TRUE;
2250 goto cleanup;
2252 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2254 hr = url->lpVtbl->GetURL(url, &urlPath);
2255 if (FAILED(hr))
2257 ret = TRUE;
2258 goto cleanup;
2260 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2262 unix_link = wine_get_unix_file_name(link);
2263 if (unix_link == NULL)
2265 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2266 goto cleanup;
2269 escaped_urlPath = escape(urlPath);
2271 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2272 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2274 WINE_ERR("failed wait for semaphore\n");
2275 goto cleanup;
2277 if (in_desktop_dir(csidl))
2279 char *location;
2280 const char *lastEntry;
2281 lastEntry = strrchr(link_name, '/');
2282 if (lastEntry == NULL)
2283 lastEntry = link_name;
2284 else
2285 ++lastEntry;
2286 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2287 if (location)
2289 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2290 HeapFree(GetProcessHeap(), 0, location);
2293 else
2294 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2295 ret = (r != 0);
2296 ReleaseSemaphore(hSem, 1, NULL);
2298 cleanup:
2299 if (hSem)
2300 CloseHandle(hSem);
2301 HeapFree(GetProcessHeap(), 0, link_name);
2302 CoTaskMemFree( urlPath );
2303 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2304 HeapFree(GetProcessHeap(), 0, unix_link);
2305 return ret;
2308 static BOOL WaitForParentProcess( void )
2310 PROCESSENTRY32 procentry;
2311 HANDLE hsnapshot = NULL, hprocess = NULL;
2312 DWORD ourpid = GetCurrentProcessId();
2313 BOOL ret = FALSE, rc;
2315 WINE_TRACE("Waiting for parent process\n");
2316 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2317 INVALID_HANDLE_VALUE)
2319 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2320 goto done;
2323 procentry.dwSize = sizeof(PROCESSENTRY32);
2324 rc = Process32First( hsnapshot, &procentry );
2325 while (rc)
2327 if (procentry.th32ProcessID == ourpid) break;
2328 rc = Process32Next( hsnapshot, &procentry );
2330 if (!rc)
2332 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2333 goto done;
2336 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2337 NULL)
2339 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2340 GetLastError());
2341 goto done;
2344 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2345 ret = TRUE;
2346 else
2347 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2349 done:
2350 if (hprocess) CloseHandle( hprocess );
2351 if (hsnapshot) CloseHandle( hsnapshot );
2352 return ret;
2355 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2357 IShellLinkW *sl;
2358 IPersistFile *pf;
2359 HRESULT r;
2360 WCHAR fullname[MAX_PATH];
2361 DWORD len;
2363 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2365 if( !linkname[0] )
2367 WINE_ERR("link name missing\n");
2368 return 1;
2371 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2372 if (len==0 || len>MAX_PATH)
2374 WINE_ERR("couldn't get full path of link file\n");
2375 return 1;
2378 r = CoInitialize( NULL );
2379 if( FAILED( r ) )
2381 WINE_ERR("CoInitialize failed\n");
2382 return 1;
2385 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2386 &IID_IShellLinkW, (LPVOID *) &sl );
2387 if( FAILED( r ) )
2389 WINE_ERR("No IID_IShellLink\n");
2390 return 1;
2393 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2394 if( FAILED( r ) )
2396 WINE_ERR("No IID_IPersistFile\n");
2397 return 1;
2400 r = IPersistFile_Load( pf, fullname, STGM_READ );
2401 if( SUCCEEDED( r ) )
2403 /* If something fails (eg. Couldn't extract icon)
2404 * wait for parent process and try again
2406 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2408 WaitForParentProcess();
2409 InvokeShellLinker( sl, fullname, FALSE );
2412 else
2414 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2417 IPersistFile_Release( pf );
2418 IShellLinkW_Release( sl );
2420 CoUninitialize();
2422 return !r;
2425 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2427 IUniformResourceLocatorW *url;
2428 IPersistFile *pf;
2429 HRESULT r;
2430 WCHAR fullname[MAX_PATH];
2431 DWORD len;
2433 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2435 if( !urlname[0] )
2437 WINE_ERR("URL name missing\n");
2438 return 1;
2441 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2442 if (len==0 || len>MAX_PATH)
2444 WINE_ERR("couldn't get full path of URL file\n");
2445 return 1;
2448 r = CoInitialize( NULL );
2449 if( FAILED( r ) )
2451 WINE_ERR("CoInitialize failed\n");
2452 return 1;
2455 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2456 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2457 if( FAILED( r ) )
2459 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2460 return 1;
2463 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2464 if( FAILED( r ) )
2466 WINE_ERR("No IID_IPersistFile\n");
2467 return 1;
2469 r = IPersistFile_Load( pf, fullname, STGM_READ );
2470 if( SUCCEEDED( r ) )
2472 /* If something fails (eg. Couldn't extract icon)
2473 * wait for parent process and try again
2475 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2477 WaitForParentProcess();
2478 InvokeShellLinkerForURL( url, fullname, FALSE );
2482 IPersistFile_Release( pf );
2483 url->lpVtbl->Release( url );
2485 CoUninitialize();
2487 return !r;
2490 static void RefreshFileTypeAssociations(void)
2492 HANDLE hSem = NULL;
2493 char *mime_dir = NULL;
2494 char *packages_dir = NULL;
2495 char *applications_dir = NULL;
2496 BOOL hasChanged;
2498 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2499 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2501 WINE_ERR("failed wait for semaphore\n");
2502 CloseHandle(hSem);
2503 hSem = NULL;
2504 goto end;
2507 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2508 if (mime_dir == NULL)
2510 WINE_ERR("out of memory\n");
2511 goto end;
2513 create_directories(mime_dir);
2515 packages_dir = heap_printf("%s/packages", mime_dir);
2516 if (packages_dir == NULL)
2518 WINE_ERR("out of memory\n");
2519 goto end;
2521 create_directories(packages_dir);
2523 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2524 if (applications_dir == NULL)
2526 WINE_ERR("out of memory\n");
2527 goto end;
2529 create_directories(applications_dir);
2531 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2532 hasChanged |= cleanup_associations();
2533 if (hasChanged)
2535 const char *argv[3];
2537 argv[0] = "update-mime-database";
2538 argv[1] = mime_dir;
2539 argv[2] = NULL;
2540 spawnvp( _P_NOWAIT, argv[0], argv );
2542 argv[0] = "update-desktop-database";
2543 argv[1] = applications_dir;
2544 spawnvp( _P_NOWAIT, argv[0], argv );
2547 end:
2548 if (hSem)
2550 ReleaseSemaphore(hSem, 1, NULL);
2551 CloseHandle(hSem);
2553 HeapFree(GetProcessHeap(), 0, mime_dir);
2554 HeapFree(GetProcessHeap(), 0, packages_dir);
2555 HeapFree(GetProcessHeap(), 0, applications_dir);
2558 static void cleanup_menus(void)
2560 HKEY hkey;
2562 hkey = open_menus_reg_key();
2563 if (hkey)
2565 int i;
2566 LSTATUS lret = ERROR_SUCCESS;
2567 for (i = 0; lret == ERROR_SUCCESS; )
2569 char *value = NULL;
2570 char *data = NULL;
2571 DWORD valueSize = 4096;
2572 DWORD dataSize = 4096;
2573 while (1)
2575 lret = ERROR_OUTOFMEMORY;
2576 value = HeapAlloc(GetProcessHeap(), 0, valueSize);
2577 if (value == NULL)
2578 break;
2579 data = HeapAlloc(GetProcessHeap(), 0, dataSize);
2580 if (data == NULL)
2581 break;
2582 lret = RegEnumValueA(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2583 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2584 break;
2585 valueSize *= 2;
2586 dataSize *= 2;
2587 HeapFree(GetProcessHeap(), 0, value);
2588 HeapFree(GetProcessHeap(), 0, data);
2589 value = data = NULL;
2591 if (lret == ERROR_SUCCESS)
2593 struct stat filestats;
2594 if (stat(data, &filestats) < 0 && errno == ENOENT)
2596 WINE_TRACE("removing menu related file %s\n", value);
2597 remove(value);
2598 RegDeleteValueA(hkey, value);
2600 else
2601 i++;
2603 else if (lret != ERROR_NO_MORE_ITEMS)
2604 WINE_WARN("error %d reading registry\n", lret);
2605 HeapFree(GetProcessHeap(), 0, value);
2606 HeapFree(GetProcessHeap(), 0, data);
2608 RegCloseKey(hkey);
2610 else
2611 WINE_ERR("error opening registry key, menu cleanup failed\n");
2614 static CHAR *next_token( LPSTR *p )
2616 LPSTR token = NULL, t = *p;
2618 if( !t )
2619 return NULL;
2621 while( t && !token )
2623 switch( *t )
2625 case ' ':
2626 t++;
2627 continue;
2628 case '"':
2629 /* unquote the token */
2630 token = ++t;
2631 t = strchr( token, '"' );
2632 if( t )
2633 *t++ = 0;
2634 break;
2635 case 0:
2636 t = NULL;
2637 break;
2638 default:
2639 token = t;
2640 t = strchr( token, ' ' );
2641 if( t )
2642 *t++ = 0;
2643 break;
2646 *p = t;
2647 return token;
2650 static BOOL init_xdg(void)
2652 WCHAR shellDesktopPath[MAX_PATH];
2653 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2654 if (SUCCEEDED(hr))
2655 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2656 if (xdg_desktop_dir == NULL)
2658 WINE_ERR("error looking up the desktop directory\n");
2659 return FALSE;
2662 if (getenv("XDG_CONFIG_HOME"))
2663 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2664 else
2665 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2666 if (xdg_config_dir)
2668 create_directories(xdg_config_dir);
2669 if (getenv("XDG_DATA_HOME"))
2670 xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
2671 else
2672 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2673 if (xdg_data_dir)
2675 char *buffer;
2676 create_directories(xdg_data_dir);
2677 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2678 if (buffer)
2680 mkdir(buffer, 0777);
2681 HeapFree(GetProcessHeap(), 0, buffer);
2683 return TRUE;
2685 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2687 WINE_ERR("out of memory\n");
2688 return FALSE;
2691 /***********************************************************************
2693 * WinMain
2695 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
2697 LPSTR token = NULL, p;
2698 BOOL bWait = FALSE;
2699 BOOL bURL = FALSE;
2700 int ret = 0;
2702 if (!init_xdg())
2703 return 1;
2705 for( p = cmdline; p && *p; )
2707 token = next_token( &p );
2708 if( !token )
2709 break;
2710 if( !lstrcmpA( token, "-a" ) )
2712 RefreshFileTypeAssociations();
2713 continue;
2715 if( !lstrcmpA( token, "-r" ) )
2717 cleanup_menus();
2718 continue;
2720 if( !lstrcmpA( token, "-w" ) )
2721 bWait = TRUE;
2722 else if ( !lstrcmpA( token, "-u" ) )
2723 bURL = TRUE;
2724 else if( token[0] == '-' )
2726 WINE_ERR( "unknown option %s\n",token);
2728 else
2730 WCHAR link[MAX_PATH];
2731 BOOL bRet;
2733 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2734 if (bURL)
2735 bRet = Process_URL( link, bWait );
2736 else
2737 bRet = Process_Link( link, bWait );
2738 if (!bRet)
2740 WINE_ERR( "failed to build menu item for %s\n",token);
2741 ret = 1;
2746 return ret;