push 955563f995be8b0942dbb757ceb5b3a4c8ccafbf
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blobcd3506bec0f516590f9a3c4e4d15aa97be44ea2d
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, 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 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
789 sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
790 if (ExtractFromEXEDLL( path, index, xpm_path ))
791 goto end;
793 /* Must be something else, ignore the index in that case */
794 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
795 if (ExtractFromICO( path, xpm_path))
796 goto end;
797 if (!bWait)
799 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
800 if (create_default_icon( xpm_path, ico_path ))
801 goto end;
804 HeapFree( GetProcessHeap(), 0, xpm_path );
805 xpm_path=NULL;
807 end:
808 HeapFree(GetProcessHeap(), 0, iconsdir);
809 HeapFree(GetProcessHeap(), 0, ico_path);
810 return xpm_path;
813 static HKEY open_menus_reg_key(void)
815 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
816 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
817 HKEY assocKey;
818 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
819 return assocKey;
820 return NULL;
823 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
824 const char *path, const char *args, const char *descr,
825 const char *workdir, const char *icon)
827 FILE *file;
829 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
830 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
831 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
833 file = fopen(location, "w");
834 if (file == NULL)
835 return FALSE;
837 fprintf(file, "[Desktop Entry]\n");
838 fprintf(file, "Name=%s\n", linkname);
839 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
840 wine_get_config_dir(), path, args);
841 fprintf(file, "Type=Application\n");
842 fprintf(file, "StartupNotify=true\n");
843 if (descr && lstrlenA(descr))
844 fprintf(file, "Comment=%s\n", descr);
845 if (workdir && lstrlenA(workdir))
846 fprintf(file, "Path=%s\n", workdir);
847 if (icon && lstrlenA(icon))
848 fprintf(file, "Icon=%s\n", icon);
850 fclose(file);
852 if (unix_link)
854 HKEY hkey = open_menus_reg_key();
855 if (hkey)
857 RegSetValueExA(hkey, location, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
858 RegCloseKey(hkey);
860 else
861 return FALSE;
864 return TRUE;
867 static BOOL write_directory_entry(const char *directory, const char *location)
869 FILE *file;
871 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
873 file = fopen(location, "w");
874 if (file == NULL)
875 return FALSE;
877 fprintf(file, "[Desktop Entry]\n");
878 fprintf(file, "Type=Directory\n");
879 if (strcmp(directory, "wine") == 0)
881 fprintf(file, "Name=Wine\n");
882 fprintf(file, "Icon=wine\n");
884 else
886 fprintf(file, "Name=%s\n", directory);
887 fprintf(file, "Icon=folder\n");
890 fclose(file);
891 return TRUE;
894 static BOOL write_menu_file(const char *unix_link, const char *filename)
896 char *tempfilename;
897 FILE *tempfile = NULL;
898 char *lastEntry;
899 char *name = NULL;
900 char *menuPath = NULL;
901 int i;
902 int count = 0;
903 BOOL ret = FALSE;
905 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
907 while (1)
909 tempfilename = tempnam(xdg_config_dir, "_wine");
910 if (tempfilename)
912 int tempfd = open(tempfilename, O_EXCL | O_CREAT | O_WRONLY, 0666);
913 if (tempfd >= 0)
915 tempfile = fdopen(tempfd, "w");
916 if (tempfile)
917 break;
918 close(tempfd);
919 goto end;
921 else if (errno == EEXIST)
923 free(tempfilename);
924 continue;
926 free(tempfilename);
928 return FALSE;
931 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
932 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
933 fprintf(tempfile, "<Menu>\n");
934 fprintf(tempfile, " <Name>Applications</Name>\n");
936 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
937 if (name == NULL) goto end;
938 lastEntry = name;
939 for (i = 0; filename[i]; i++)
941 name[i] = filename[i];
942 if (filename[i] == '/')
944 char *dir_file_name;
945 struct stat st;
946 name[i] = 0;
947 fprintf(tempfile, " <Menu>\n");
948 fprintf(tempfile, " <Name>%s%s</Name>\n", count ? "" : "wine-", name);
949 fprintf(tempfile, " <Directory>%s%s.directory</Directory>\n", count ? "" : "wine-", name);
950 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
951 xdg_data_dir, count ? "" : "wine-", name);
952 if (dir_file_name)
954 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
955 write_directory_entry(lastEntry, dir_file_name);
956 HeapFree(GetProcessHeap(), 0, dir_file_name);
958 name[i] = '-';
959 lastEntry = &name[i+1];
960 ++count;
963 name[i] = 0;
965 fprintf(tempfile, " <Include>\n");
966 fprintf(tempfile, " <Filename>%s</Filename>\n", name);
967 fprintf(tempfile, " </Include>\n");
968 for (i = 0; i < count; i++)
969 fprintf(tempfile, " </Menu>\n");
970 fprintf(tempfile, "</Menu>\n");
972 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
973 if (menuPath == NULL) goto end;
974 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
975 ret = TRUE;
977 end:
978 if (tempfile)
979 fclose(tempfile);
980 if (ret)
981 ret = (rename(tempfilename, menuPath) == 0);
982 if (!ret && tempfilename)
983 remove(tempfilename);
984 free(tempfilename);
985 if (ret)
987 HKEY hkey = open_menus_reg_key();
988 if (hkey)
990 RegSetValueExA(hkey, menuPath, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
991 RegCloseKey(hkey);
994 HeapFree(GetProcessHeap(), 0, name);
995 HeapFree(GetProcessHeap(), 0, menuPath);
996 return ret;
999 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1000 const char *descr, const char *workdir, const char *icon)
1002 const char *linkname;
1003 char *desktopPath = NULL;
1004 char *desktopDir;
1005 char *filename = NULL;
1006 BOOL ret = TRUE;
1008 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1009 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1010 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1012 linkname = strrchr(link, '/');
1013 if (linkname == NULL)
1014 linkname = link;
1015 else
1016 ++linkname;
1018 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1019 if (!desktopPath)
1021 WINE_WARN("out of memory creating menu entry\n");
1022 ret = FALSE;
1023 goto end;
1025 desktopDir = strrchr(desktopPath, '/');
1026 *desktopDir = 0;
1027 if (!create_directories(desktopPath))
1029 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1030 ret = FALSE;
1031 goto end;
1033 *desktopDir = '/';
1034 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1036 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1037 ret = FALSE;
1038 goto end;
1041 filename = heap_printf("wine/%s.desktop", link);
1042 if (!filename || !write_menu_file(unix_link, filename))
1044 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1045 ret = FALSE;
1048 end:
1049 HeapFree(GetProcessHeap(), 0, desktopPath);
1050 HeapFree(GetProcessHeap(), 0, filename);
1051 return ret;
1054 /* This escapes \ in filenames */
1055 static LPSTR escape(LPCWSTR arg)
1057 LPSTR narg, x;
1058 LPCWSTR esc;
1059 int len = 0, n;
1061 esc = arg;
1062 while((esc = strchrW(esc, '\\')))
1064 esc++;
1065 len++;
1068 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1069 narg = HeapAlloc(GetProcessHeap(), 0, len);
1071 x = narg;
1072 while (*arg)
1074 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1075 x += n;
1076 len -= n;
1077 if (*arg == '\\')
1078 *x++='\\'; /* escape \ */
1079 arg++;
1081 *x = 0;
1082 return narg;
1085 /* Return a heap-allocated copy of the unix format difference between the two
1086 * Windows-format paths.
1087 * locn is the owning location
1088 * link is within locn
1090 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1092 char *unix_locn, *unix_link;
1093 char *relative = NULL;
1095 unix_locn = wine_get_unix_file_name(locn);
1096 unix_link = wine_get_unix_file_name(link);
1097 if (unix_locn && unix_link)
1099 size_t len_unix_locn, len_unix_link;
1100 len_unix_locn = strlen (unix_locn);
1101 len_unix_link = strlen (unix_link);
1102 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1104 size_t len_rel;
1105 char *p = strrchr (unix_link + len_unix_locn, '/');
1106 p = strrchr (p, '.');
1107 if (p)
1109 *p = '\0';
1110 len_unix_link = p - unix_link;
1112 len_rel = len_unix_link - len_unix_locn;
1113 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1114 if (relative)
1116 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1120 if (!relative)
1121 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1122 HeapFree(GetProcessHeap(), 0, unix_locn);
1123 HeapFree(GetProcessHeap(), 0, unix_link);
1124 return relative;
1127 /***********************************************************************
1129 * GetLinkLocation
1131 * returns TRUE if successful
1132 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1133 * *relative will contain the address of a heap-allocated copy of the portion
1134 * of the filename that is within the specified location, in unix form
1136 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1138 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1139 DWORD len, i, r, filelen;
1140 const DWORD locations[] = {
1141 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1142 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1143 CSIDL_COMMON_STARTMENU };
1145 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1146 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1147 if (filelen==0 || filelen>MAX_PATH)
1148 return FALSE;
1150 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1152 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1153 * expand or our hardcoded list won't match.
1155 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1156 if (filelen==0 || filelen>MAX_PATH)
1157 return FALSE;
1159 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1161 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1163 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1164 continue;
1166 len = lstrlenW(buffer);
1167 if (len >= MAX_PATH)
1168 continue; /* We've just trashed memory! Hopefully we are OK */
1170 if (len > filelen || filename[len]!='\\')
1171 continue;
1172 /* do a lstrcmpinW */
1173 filename[len] = 0;
1174 r = lstrcmpiW( filename, buffer );
1175 filename[len] = '\\';
1176 if ( r )
1177 continue;
1179 /* return the remainder of the string and link type */
1180 *loc = locations[i];
1181 *relative = relative_path (filename, buffer);
1182 return (*relative != NULL);
1185 return FALSE;
1188 /* gets the target path directly or through MSI */
1189 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1190 LPWSTR szArgs, DWORD argsSize)
1192 IShellLinkDataList *dl = NULL;
1193 EXP_DARWIN_LINK *dar = NULL;
1194 HRESULT hr;
1196 szPath[0] = 0;
1197 szArgs[0] = 0;
1199 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1200 if (hr == S_OK && szPath[0])
1202 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1203 return hr;
1206 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1207 if (FAILED(hr))
1208 return hr;
1210 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1211 if (SUCCEEDED(hr))
1213 WCHAR* szCmdline;
1214 DWORD cmdSize;
1216 cmdSize=0;
1217 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1218 if (hr == ERROR_SUCCESS)
1220 cmdSize++;
1221 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1222 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1223 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1224 if (hr == ERROR_SUCCESS)
1226 WCHAR *s, *d;
1227 int bcount, in_quotes;
1229 /* Extract the application path */
1230 bcount=0;
1231 in_quotes=0;
1232 s=szCmdline;
1233 d=szPath;
1234 while (*s)
1236 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1238 /* skip the remaining spaces */
1239 do {
1240 s++;
1241 } while (*s==0x0009 || *s==0x0020);
1242 break;
1244 else if (*s==0x005c)
1246 /* '\\' */
1247 *d++=*s++;
1248 bcount++;
1250 else if (*s==0x0022)
1252 /* '"' */
1253 if ((bcount & 1)==0)
1255 /* Preceded by an even number of '\', this is
1256 * half that number of '\', plus a quote which
1257 * we erase.
1259 d-=bcount/2;
1260 in_quotes=!in_quotes;
1261 s++;
1263 else
1265 /* Preceded by an odd number of '\', this is
1266 * half that number of '\' followed by a '"'
1268 d=d-bcount/2-1;
1269 *d++='"';
1270 s++;
1272 bcount=0;
1274 else
1276 /* a regular character */
1277 *d++=*s++;
1278 bcount=0;
1280 if ((d-szPath) == pathSize)
1282 /* Keep processing the path till we get to the
1283 * arguments, but 'stand still'
1285 d--;
1288 /* Close the application path */
1289 *d=0;
1291 lstrcpynW(szArgs, s, argsSize);
1293 HeapFree( GetProcessHeap(), 0, szCmdline );
1295 LocalFree( dar );
1298 IShellLinkDataList_Release( dl );
1299 return hr;
1302 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1304 HRESULT hr;
1305 WCHAR *value = NULL;
1306 DWORD size = 0;
1307 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1308 if (SUCCEEDED(hr))
1310 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1311 if (value)
1313 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1314 if (FAILED(hr))
1316 HeapFree(GetProcessHeap(), 0, value);
1317 value = NULL;
1321 return value;
1324 static char* wchars_to_utf8_chars(LPCWSTR string)
1326 char *ret;
1327 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
1328 ret = HeapAlloc(GetProcessHeap(), 0, size);
1329 if (ret)
1330 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
1331 return ret;
1334 static char *slashes_to_minuses(const char *string)
1336 int i;
1337 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1338 if (ret)
1340 for (i = 0; string[i]; i++)
1342 if (string[i] == '/')
1343 ret[i] = '-';
1344 else
1345 ret[i] = string[i];
1347 ret[i] = 0;
1348 return ret;
1350 return NULL;
1353 static BOOL next_line(FILE *file, char **line, int *size)
1355 int pos = 0;
1356 char *cr;
1357 if (*line == NULL)
1359 *size = 4096;
1360 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1362 while (*line != NULL)
1364 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1366 HeapFree(GetProcessHeap(), 0, *line);
1367 *line = NULL;
1368 if (feof(file))
1369 return TRUE;
1370 return FALSE;
1372 pos = strlen(*line);
1373 cr = strchr(*line, '\n');
1374 if (cr == NULL)
1376 char *line2;
1377 (*size) *= 2;
1378 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1379 if (line2)
1380 *line = line2;
1381 else
1383 HeapFree(GetProcessHeap(), 0, *line);
1384 *line = NULL;
1387 else
1389 *cr = 0;
1390 return TRUE;
1393 return FALSE;
1396 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1398 char *globs_filename = NULL;
1399 BOOL ret = TRUE;
1400 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1401 if (globs_filename)
1403 FILE *globs_file = fopen(globs_filename, "r");
1404 if (globs_file) /* doesn't have to exist */
1406 char *line = NULL;
1407 int size = 0;
1408 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1410 char *pos;
1411 struct xdg_mime_type *mime_type_entry = NULL;
1412 if (line[0] != '#' && (pos = strchr(line, ':')))
1414 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1415 if (mime_type_entry)
1417 *pos = 0;
1418 mime_type_entry->mimeType = heap_printf("%s", line);
1419 mime_type_entry->glob = heap_printf("%s", pos + 1);
1420 if (mime_type_entry->mimeType && mime_type_entry->glob)
1421 list_add_tail(mime_types, &mime_type_entry->entry);
1422 else
1424 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1425 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1426 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1427 ret = FALSE;
1430 else
1431 ret = FALSE;
1434 HeapFree(GetProcessHeap(), 0, line);
1435 fclose(globs_file);
1437 HeapFree(GetProcessHeap(), 0, globs_filename);
1439 else
1440 ret = FALSE;
1441 return ret;
1444 static void free_native_mime_types(struct list *native_mime_types)
1446 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1448 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1450 list_remove(&mime_type_entry->entry);
1451 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1452 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1453 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1455 HeapFree(GetProcessHeap(), 0, native_mime_types);
1458 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1460 char *xdg_data_dirs;
1461 BOOL ret;
1463 *mime_types = NULL;
1465 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1466 if (xdg_data_dirs == NULL)
1467 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1468 else
1469 xdg_data_dirs = heap_printf("%s", xdg_data_dirs);
1471 if (xdg_data_dirs)
1473 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1474 if (*mime_types)
1476 const char *begin;
1477 char *end;
1479 list_init(*mime_types);
1480 ret = add_mimes(xdg_data_home, *mime_types);
1481 if (ret)
1483 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1485 *end = '\0';
1486 ret = add_mimes(begin, *mime_types);
1487 *end = ':';
1488 if (!ret)
1489 break;
1491 if (ret)
1492 ret = add_mimes(begin, *mime_types);
1495 else
1496 ret = FALSE;
1497 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1499 else
1500 ret = FALSE;
1501 if (!ret && *mime_types)
1503 free_native_mime_types(*mime_types);
1504 *mime_types = NULL;
1506 return ret;
1509 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1510 char **match)
1512 #ifdef HAVE_FNMATCH
1513 struct xdg_mime_type *mime_type_entry;
1514 int matchLength = 0;
1516 *match = NULL;
1518 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1520 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1522 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1524 *match = mime_type_entry->mimeType;
1525 matchLength = strlen(mime_type_entry->glob);
1530 if (*match != NULL)
1532 *match = heap_printf("%s", *match);
1533 if (*match == NULL)
1534 return FALSE;
1536 #else
1537 *match = NULL;
1538 #endif
1539 return TRUE;
1542 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1543 const char *extensionA,
1544 LPCWSTR extensionW,
1545 char **mime_type)
1547 WCHAR *lower_extensionW;
1548 INT len;
1549 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1550 if (ret == FALSE || *mime_type != NULL)
1551 return ret;
1552 len = strlenW(extensionW);
1553 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1554 if (lower_extensionW)
1556 char *lower_extensionA;
1557 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1558 strlwrW(lower_extensionW);
1559 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1560 if (lower_extensionA)
1562 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1563 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1565 else
1567 ret = FALSE;
1568 WINE_FIXME("out of memory\n");
1570 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1572 else
1574 ret = FALSE;
1575 WINE_FIXME("out of memory\n");
1577 return ret;
1580 static CHAR* reg_get_valA(HKEY key, LPCSTR subkey, LPCSTR name)
1582 DWORD size;
1583 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1585 CHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1586 if (ret)
1588 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1589 return ret;
1591 HeapFree(GetProcessHeap(), 0, ret);
1593 return NULL;
1596 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1598 DWORD size;
1599 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1601 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1602 if (ret)
1604 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1605 return ret;
1607 HeapFree(GetProcessHeap(), 0, ret);
1609 return NULL;
1612 static HKEY open_associations_reg_key(void)
1614 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1615 '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};
1616 HKEY assocKey;
1617 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1618 return assocKey;
1619 return NULL;
1622 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1624 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1625 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1626 HKEY assocKey;
1627 BOOL ret;
1629 if ((assocKey = open_associations_reg_key()))
1631 CHAR *valueA;
1632 WCHAR *value;
1634 ret = FALSE;
1636 valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1637 if (!valueA || lstrcmpA(valueA, mimeType))
1638 ret = TRUE;
1639 HeapFree(GetProcessHeap(), 0, valueA);
1641 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1642 if (!value || strcmpW(value, progId))
1643 ret = TRUE;
1644 HeapFree(GetProcessHeap(), 0, value);
1646 valueA = reg_get_valA(assocKey, extensionA, "AppName");
1647 if (!valueA || lstrcmpA(valueA, appName))
1648 ret = TRUE;
1649 HeapFree(GetProcessHeap(), 0, valueA);
1651 value = reg_get_valW(assocKey, extensionW, DocNameW);
1652 if (docName && (!value || strcmpW(value, docName)))
1653 ret = TRUE;
1654 HeapFree(GetProcessHeap(), 0, value);
1656 RegCloseKey(assocKey);
1658 else
1660 WINE_ERR("error opening associations registry key\n");
1661 ret = FALSE;
1663 return ret;
1666 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1668 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1669 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1670 HKEY assocKey;
1672 if ((assocKey = open_associations_reg_key()))
1674 HKEY subkey;
1675 if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1677 RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (BYTE*) mimeType, lstrlenA(mimeType) + 1);
1678 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1679 RegSetValueExA(subkey, "AppName", 0, REG_SZ, (BYTE*) appName, lstrlenA(appName) + 1);
1680 if (docName)
1681 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1682 RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1683 RegCloseKey(subkey);
1685 else
1686 WINE_ERR("could not create extension subkey\n");
1687 RegCloseKey(assocKey);
1689 else
1690 WINE_ERR("could not open file associations key\n");
1693 static BOOL cleanup_associations(void)
1695 HKEY assocKey;
1696 BOOL hasChanged = FALSE;
1697 if ((assocKey = open_associations_reg_key()))
1699 int i;
1700 BOOL done = FALSE;
1701 for (i = 0; !done; i++)
1703 WCHAR *extensionW = NULL;
1704 char *extensionA = NULL;
1705 DWORD size = 1024;
1706 LSTATUS ret;
1710 HeapFree(GetProcessHeap(), 0, extensionW);
1711 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1712 if (extensionW == NULL)
1714 WINE_ERR("out of memory\n");
1715 ret = ERROR_OUTOFMEMORY;
1716 break;
1718 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1719 size *= 2;
1720 } while (ret == ERROR_MORE_DATA);
1722 if (ret == ERROR_SUCCESS)
1724 WCHAR *command;
1725 extensionA = wchars_to_utf8_chars(extensionW);
1726 if (extensionA == NULL)
1728 WINE_ERR("out of memory\n");
1729 done = TRUE;
1730 goto end;
1732 command = assoc_query(ASSOCSTR_COMMAND, extensionW, NULL);
1733 if (command == NULL)
1735 char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1736 if (desktopFile)
1738 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1739 remove(desktopFile);
1741 RegDeleteKeyW(assocKey, extensionW);
1742 hasChanged = TRUE;
1743 HeapFree(GetProcessHeap(), 0, desktopFile);
1745 HeapFree(GetProcessHeap(), 0, command);
1747 else
1749 if (ret != ERROR_NO_MORE_ITEMS)
1750 WINE_ERR("error %d while reading registry\n", ret);
1751 done = TRUE;
1753 end:
1754 HeapFree(GetProcessHeap(), 0, extensionA);
1755 HeapFree(GetProcessHeap(), 0, extensionW);
1757 RegCloseKey(assocKey);
1759 else
1760 WINE_ERR("could not open file associations key\n");
1761 return hasChanged;
1764 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1765 const char *mime_type, const char *comment)
1767 BOOL ret = FALSE;
1768 char *filename;
1770 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1771 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1773 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1774 if (filename)
1776 FILE *packageFile = fopen(filename, "w");
1777 if (packageFile)
1779 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1780 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1781 fprintf(packageFile, " <mime-type type=\"%s\">\n", mime_type);
1782 fprintf(packageFile, " <glob pattern=\"*%s\"/>\n", dot_extension);
1783 if (comment)
1784 fprintf(packageFile, " <comment>%s</comment>\n", comment);
1785 fprintf(packageFile, " </mime-type>\n");
1786 fprintf(packageFile, "</mime-info>\n");
1787 ret = TRUE;
1788 fclose(packageFile);
1790 else
1791 WINE_ERR("error writing file %s\n", filename);
1792 HeapFree(GetProcessHeap(), 0, filename);
1794 else
1795 WINE_ERR("out of memory\n");
1796 return ret;
1799 static BOOL is_extension_blacklisted(LPCWSTR extension)
1801 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1802 static const WCHAR comW[] = {'.','c','o','m',0};
1803 static const WCHAR exeW[] = {'.','e','x','e',0};
1804 static const WCHAR msiW[] = {'.','m','s','i',0};
1806 if (!strcmpiW(extension, comW) ||
1807 !strcmpiW(extension, exeW) ||
1808 !strcmpiW(extension, msiW))
1809 return TRUE;
1810 return FALSE;
1813 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1814 const char *friendlyAppName, const char *mimeType,
1815 const char *progId)
1817 BOOL ret = FALSE;
1818 FILE *desktop;
1820 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1821 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1822 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1824 desktop = fopen(desktopPath, "w");
1825 if (desktop)
1827 fprintf(desktop, "[Desktop Entry]\n");
1828 fprintf(desktop, "Type=Application\n");
1829 fprintf(desktop, "Name=%s\n", friendlyAppName);
1830 fprintf(desktop, "MimeType=%s\n", mimeType);
1831 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1832 fprintf(desktop, "NoDisplay=true\n");
1833 fprintf(desktop, "StartupNotify=true\n");
1834 ret = TRUE;
1835 fclose(desktop);
1837 else
1838 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1839 return ret;
1842 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1844 struct list *nativeMimeTypes = NULL;
1845 LSTATUS ret = 0;
1846 int i;
1847 BOOL hasChanged = FALSE;
1849 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1851 WINE_ERR("could not build native MIME types\n");
1852 return FALSE;
1855 for (i = 0; ; i++)
1857 WCHAR *extensionW = NULL;
1858 DWORD size = 1024;
1862 HeapFree(GetProcessHeap(), 0, extensionW);
1863 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1864 if (extensionW == NULL)
1866 WINE_ERR("out of memory\n");
1867 ret = ERROR_OUTOFMEMORY;
1868 break;
1870 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1871 size *= 2;
1872 } while (ret == ERROR_MORE_DATA);
1874 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1876 char *extensionA = NULL;
1877 WCHAR *commandW = NULL;
1878 WCHAR *friendlyDocNameW = NULL;
1879 char *friendlyDocNameA = NULL;
1880 WCHAR *iconW = NULL;
1881 char *iconA = NULL;
1882 WCHAR *contentTypeW = NULL;
1883 char *mimeTypeA = NULL;
1884 WCHAR *friendlyAppNameW = NULL;
1885 char *friendlyAppNameA = NULL;
1886 WCHAR *progIdW = NULL;
1887 char *progIdA = NULL;
1889 extensionA = wchars_to_utf8_chars(extensionW);
1890 if (extensionA == NULL)
1892 WINE_ERR("out of memory\n");
1893 goto end;
1896 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
1897 if (friendlyDocNameW)
1899 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
1900 if (friendlyDocNameA == NULL)
1902 WINE_ERR("out of memory\n");
1903 goto end;
1907 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
1908 if (iconW)
1910 WCHAR *comma = strrchrW(iconW, ',');
1911 int index = 0;
1912 if (comma)
1914 *comma = 0;
1915 index = atoiW(comma + 1);
1917 iconA = extract_icon(iconW, index, FALSE);
1920 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
1922 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
1923 goto end;
1925 if (mimeTypeA == NULL)
1927 if (contentTypeW != NULL)
1928 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
1929 else
1930 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
1932 if (mimeTypeA != NULL)
1934 /* Gnome seems to ignore the <icon> tag in MIME packages,
1935 * and the default name is more intuitive anyway.
1937 if (iconA)
1939 char *flattened_mime = slashes_to_minuses(mimeTypeA);
1940 if (flattened_mime)
1942 char *dstIconPath = heap_printf("%s/icons/%s%s", xdg_data_dir,
1943 flattened_mime, strrchr(iconA, '.'));
1944 if (dstIconPath)
1946 rename(iconA, dstIconPath);
1947 HeapFree(GetProcessHeap(), 0, dstIconPath);
1949 HeapFree(GetProcessHeap(), 0, flattened_mime);
1953 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
1954 hasChanged = TRUE;
1956 else
1958 WINE_FIXME("out of memory\n");
1959 goto end;
1963 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, NULL);
1964 if (commandW == NULL)
1965 /* no command => no application is associated */
1966 goto end;
1968 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
1969 if (friendlyAppNameW)
1971 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
1972 if (friendlyAppNameA == NULL)
1974 WINE_ERR("out of memory\n");
1975 goto end;
1978 else
1980 friendlyAppNameA = heap_printf("A Wine application");
1981 if (friendlyAppNameA == NULL)
1983 WINE_ERR("out of memory\n");
1984 goto end;
1988 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
1989 if (progIdW)
1991 progIdA = wchars_to_utf8_chars(progIdW);
1992 if (progIdA == NULL)
1994 WINE_ERR("out of memory\n");
1995 goto end;
1998 else
1999 goto end; /* no progID => not a file type association */
2001 if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2003 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2004 if (desktopPath)
2006 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2008 hasChanged = TRUE;
2009 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2011 HeapFree(GetProcessHeap(), 0, desktopPath);
2015 end:
2016 HeapFree(GetProcessHeap(), 0, extensionA);
2017 HeapFree(GetProcessHeap(), 0, commandW);
2018 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2019 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2020 HeapFree(GetProcessHeap(), 0, iconW);
2021 HeapFree(GetProcessHeap(), 0, iconA);
2022 HeapFree(GetProcessHeap(), 0, contentTypeW);
2023 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2024 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2025 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2026 HeapFree(GetProcessHeap(), 0, progIdW);
2027 HeapFree(GetProcessHeap(), 0, progIdA);
2029 HeapFree(GetProcessHeap(), 0, extensionW);
2030 if (ret != ERROR_SUCCESS)
2031 break;
2034 free_native_mime_types(nativeMimeTypes);
2035 return hasChanged;
2038 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2040 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2041 '\\','s','t','a','r','t','.','e','x','e',0};
2042 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2043 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
2044 WCHAR szTmp[INFOTIPSIZE];
2045 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2046 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2047 int iIconId = 0, r = -1;
2048 DWORD csidl = -1;
2049 HANDLE hsem = NULL;
2050 char *unix_link = NULL;
2052 if ( !link )
2054 WINE_ERR("Link name is null\n");
2055 return FALSE;
2058 if( !GetLinkLocation( link, &csidl, &link_name ) )
2060 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2061 return TRUE;
2063 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2065 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2066 return TRUE;
2068 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2070 szTmp[0] = 0;
2071 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2072 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2073 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2075 szTmp[0] = 0;
2076 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2077 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2078 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2080 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
2081 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2082 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2084 szTmp[0] = 0;
2085 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2086 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2087 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2089 if( !szPath[0] )
2091 LPITEMIDLIST pidl = NULL;
2092 IShellLinkW_GetIDList( sl, &pidl );
2093 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2094 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2097 /* extract the icon */
2098 if( szIconPath[0] )
2099 icon_name = extract_icon( szIconPath , iIconId, bWait );
2100 else
2101 icon_name = extract_icon( szPath, iIconId, bWait );
2103 /* fail - try once again after parent process exit */
2104 if( !icon_name )
2106 if (bWait)
2108 WINE_WARN("Unable to extract icon, deferring.\n");
2109 goto cleanup;
2111 WINE_ERR("failed to extract icon from %s\n",
2112 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2115 unix_link = wine_get_unix_file_name(link);
2116 if (unix_link == NULL)
2118 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2119 goto cleanup;
2122 /* check the path */
2123 if( szPath[0] )
2125 static const WCHAR exeW[] = {'.','e','x','e',0};
2126 WCHAR *p;
2128 /* check for .exe extension */
2129 if (!(p = strrchrW( szPath, '.' )) ||
2130 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2131 lstrcmpiW( p, exeW ))
2133 /* Not .exe - use 'start.exe' to launch this file */
2134 p = szArgs + lstrlenW(szPath) + 2;
2135 if (szArgs[0])
2137 p[0] = ' ';
2138 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2139 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2141 else
2142 p[0] = 0;
2144 szArgs[0] = '"';
2145 lstrcpyW(szArgs + 1, szPath);
2146 p[-1] = '"';
2148 GetWindowsDirectoryW(szPath, MAX_PATH);
2149 lstrcatW(szPath, startW);
2152 /* convert app working dir */
2153 if (szWorkDir[0])
2154 work_dir = wine_get_unix_file_name( szWorkDir );
2156 else
2158 /* if there's no path... try run the link itself */
2159 lstrcpynW(szArgs, link, MAX_PATH);
2160 GetWindowsDirectoryW(szPath, MAX_PATH);
2161 lstrcatW(szPath, startW);
2164 /* escape the path and parameters */
2165 escaped_path = escape(szPath);
2166 escaped_args = escape(szArgs);
2167 escaped_description = escape(szDescription);
2169 /* building multiple menus concurrently has race conditions */
2170 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2171 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2173 WINE_ERR("failed wait for semaphore\n");
2174 goto cleanup;
2177 if (in_desktop_dir(csidl))
2179 char *location;
2180 const char *lastEntry;
2181 lastEntry = strrchr(link_name, '/');
2182 if (lastEntry == NULL)
2183 lastEntry = link_name;
2184 else
2185 ++lastEntry;
2186 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2187 if (location)
2189 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2190 HeapFree(GetProcessHeap(), 0, location);
2193 else
2194 r = !write_menu_entry(unix_link, link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2196 ReleaseSemaphore( hsem, 1, NULL );
2198 cleanup:
2199 if (hsem) CloseHandle( hsem );
2200 HeapFree( GetProcessHeap(), 0, icon_name );
2201 HeapFree( GetProcessHeap(), 0, work_dir );
2202 HeapFree( GetProcessHeap(), 0, link_name );
2203 HeapFree( GetProcessHeap(), 0, escaped_args );
2204 HeapFree( GetProcessHeap(), 0, escaped_path );
2205 HeapFree( GetProcessHeap(), 0, escaped_description );
2206 HeapFree( GetProcessHeap(), 0, unix_link);
2208 if (r && !bWait)
2209 WINE_ERR("failed to build the menu\n" );
2211 return ( r == 0 );
2214 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2216 char *link_name = NULL;
2217 DWORD csidl = -1;
2218 LPWSTR urlPath;
2219 char *escaped_urlPath = NULL;
2220 HRESULT hr;
2221 HANDLE hSem = NULL;
2222 BOOL ret = TRUE;
2223 int r = -1;
2224 char *unix_link = NULL;
2226 if ( !link )
2228 WINE_ERR("Link name is null\n");
2229 return TRUE;
2232 if( !GetLinkLocation( link, &csidl, &link_name ) )
2234 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2235 return TRUE;
2237 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2239 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2240 ret = TRUE;
2241 goto cleanup;
2243 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2245 hr = url->lpVtbl->GetURL(url, &urlPath);
2246 if (FAILED(hr))
2248 ret = TRUE;
2249 goto cleanup;
2251 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2253 unix_link = wine_get_unix_file_name(link);
2254 if (unix_link == NULL)
2256 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2257 goto cleanup;
2260 escaped_urlPath = escape(urlPath);
2262 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2263 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2265 WINE_ERR("failed wait for semaphore\n");
2266 goto cleanup;
2268 if (in_desktop_dir(csidl))
2270 char *location;
2271 const char *lastEntry;
2272 lastEntry = strrchr(link_name, '/');
2273 if (lastEntry == NULL)
2274 lastEntry = link_name;
2275 else
2276 ++lastEntry;
2277 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2278 if (location)
2280 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2281 HeapFree(GetProcessHeap(), 0, location);
2284 else
2285 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2286 ret = (r != 0);
2287 ReleaseSemaphore(hSem, 1, NULL);
2289 cleanup:
2290 if (hSem)
2291 CloseHandle(hSem);
2292 HeapFree(GetProcessHeap(), 0, link_name);
2293 CoTaskMemFree( urlPath );
2294 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2295 HeapFree(GetProcessHeap(), 0, unix_link);
2296 return ret;
2299 static BOOL WaitForParentProcess( void )
2301 PROCESSENTRY32 procentry;
2302 HANDLE hsnapshot = NULL, hprocess = NULL;
2303 DWORD ourpid = GetCurrentProcessId();
2304 BOOL ret = FALSE, rc;
2306 WINE_TRACE("Waiting for parent process\n");
2307 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2308 INVALID_HANDLE_VALUE)
2310 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2311 goto done;
2314 procentry.dwSize = sizeof(PROCESSENTRY32);
2315 rc = Process32First( hsnapshot, &procentry );
2316 while (rc)
2318 if (procentry.th32ProcessID == ourpid) break;
2319 rc = Process32Next( hsnapshot, &procentry );
2321 if (!rc)
2323 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2324 goto done;
2327 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2328 NULL)
2330 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2331 GetLastError());
2332 goto done;
2335 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2336 ret = TRUE;
2337 else
2338 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2340 done:
2341 if (hprocess) CloseHandle( hprocess );
2342 if (hsnapshot) CloseHandle( hsnapshot );
2343 return ret;
2346 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2348 IShellLinkW *sl;
2349 IPersistFile *pf;
2350 HRESULT r;
2351 WCHAR fullname[MAX_PATH];
2352 DWORD len;
2354 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2356 if( !linkname[0] )
2358 WINE_ERR("link name missing\n");
2359 return 1;
2362 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2363 if (len==0 || len>MAX_PATH)
2365 WINE_ERR("couldn't get full path of link file\n");
2366 return 1;
2369 r = CoInitialize( NULL );
2370 if( FAILED( r ) )
2372 WINE_ERR("CoInitialize failed\n");
2373 return 1;
2376 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2377 &IID_IShellLinkW, (LPVOID *) &sl );
2378 if( FAILED( r ) )
2380 WINE_ERR("No IID_IShellLink\n");
2381 return 1;
2384 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2385 if( FAILED( r ) )
2387 WINE_ERR("No IID_IPersistFile\n");
2388 return 1;
2391 r = IPersistFile_Load( pf, fullname, STGM_READ );
2392 if( SUCCEEDED( r ) )
2394 /* If something fails (eg. Couldn't extract icon)
2395 * wait for parent process and try again
2397 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2399 WaitForParentProcess();
2400 InvokeShellLinker( sl, fullname, FALSE );
2403 else
2405 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2408 IPersistFile_Release( pf );
2409 IShellLinkW_Release( sl );
2411 CoUninitialize();
2413 return !r;
2416 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2418 IUniformResourceLocatorW *url;
2419 IPersistFile *pf;
2420 HRESULT r;
2421 WCHAR fullname[MAX_PATH];
2422 DWORD len;
2424 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2426 if( !urlname[0] )
2428 WINE_ERR("URL name missing\n");
2429 return 1;
2432 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2433 if (len==0 || len>MAX_PATH)
2435 WINE_ERR("couldn't get full path of URL file\n");
2436 return 1;
2439 r = CoInitialize( NULL );
2440 if( FAILED( r ) )
2442 WINE_ERR("CoInitialize failed\n");
2443 return 1;
2446 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2447 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2448 if( FAILED( r ) )
2450 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2451 return 1;
2454 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2455 if( FAILED( r ) )
2457 WINE_ERR("No IID_IPersistFile\n");
2458 return 1;
2460 r = IPersistFile_Load( pf, fullname, STGM_READ );
2461 if( SUCCEEDED( r ) )
2463 /* If something fails (eg. Couldn't extract icon)
2464 * wait for parent process and try again
2466 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2468 WaitForParentProcess();
2469 InvokeShellLinkerForURL( url, fullname, FALSE );
2473 IPersistFile_Release( pf );
2474 url->lpVtbl->Release( url );
2476 CoUninitialize();
2478 return !r;
2481 static void RefreshFileTypeAssociations(void)
2483 HANDLE hSem = NULL;
2484 char *mime_dir = NULL;
2485 char *packages_dir = NULL;
2486 char *applications_dir = NULL;
2487 BOOL hasChanged;
2489 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2490 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2492 WINE_ERR("failed wait for semaphore\n");
2493 CloseHandle(hSem);
2494 hSem = NULL;
2495 goto end;
2498 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2499 if (mime_dir == NULL)
2501 WINE_ERR("out of memory\n");
2502 goto end;
2504 create_directories(mime_dir);
2506 packages_dir = heap_printf("%s/packages", mime_dir);
2507 if (packages_dir == NULL)
2509 WINE_ERR("out of memory\n");
2510 goto end;
2512 create_directories(packages_dir);
2514 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2515 if (applications_dir == NULL)
2517 WINE_ERR("out of memory\n");
2518 goto end;
2520 create_directories(applications_dir);
2522 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2523 hasChanged |= cleanup_associations();
2524 if (hasChanged)
2526 char *command = heap_printf("update-mime-database %s", mime_dir);
2527 if (command)
2529 system(command);
2530 HeapFree(GetProcessHeap(), 0, command);
2532 else
2534 WINE_ERR("out of memory\n");
2535 goto end;
2538 command = heap_printf("update-desktop-database %s/applications", xdg_data_dir);
2539 if (command)
2541 system(command);
2542 HeapFree(GetProcessHeap(), 0, command);
2544 else
2546 WINE_ERR("out of memory\n");
2547 goto end;
2551 end:
2552 if (hSem)
2554 ReleaseSemaphore(hSem, 1, NULL);
2555 CloseHandle(hSem);
2557 HeapFree(GetProcessHeap(), 0, mime_dir);
2558 HeapFree(GetProcessHeap(), 0, packages_dir);
2559 HeapFree(GetProcessHeap(), 0, applications_dir);
2562 static void cleanup_menus(void)
2564 HKEY hkey;
2566 hkey = open_menus_reg_key();
2567 if (hkey)
2569 int i;
2570 LSTATUS lret = ERROR_SUCCESS;
2571 for (i = 0; lret == ERROR_SUCCESS; )
2573 char *value = NULL;
2574 char *data = NULL;
2575 DWORD valueSize = 4096;
2576 DWORD dataSize = 4096;
2577 while (1)
2579 lret = ERROR_OUTOFMEMORY;
2580 value = HeapAlloc(GetProcessHeap(), 0, valueSize);
2581 if (value == NULL)
2582 break;
2583 data = HeapAlloc(GetProcessHeap(), 0, dataSize);
2584 if (data == NULL)
2585 break;
2586 lret = RegEnumValueA(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2587 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2588 break;
2589 valueSize *= 2;
2590 dataSize *= 2;
2591 HeapFree(GetProcessHeap(), 0, value);
2592 HeapFree(GetProcessHeap(), 0, data);
2593 value = data = NULL;
2595 if (lret == ERROR_SUCCESS)
2597 struct stat filestats;
2598 if (stat(data, &filestats) < 0 && errno == ENOENT)
2600 WINE_TRACE("removing menu related file %s\n", value);
2601 remove(value);
2602 RegDeleteValueA(hkey, value);
2604 else
2605 i++;
2607 else if (lret != ERROR_NO_MORE_ITEMS)
2608 WINE_WARN("error %d reading registry\n", lret);
2609 HeapFree(GetProcessHeap(), 0, value);
2610 HeapFree(GetProcessHeap(), 0, data);
2612 RegCloseKey(hkey);
2614 else
2615 WINE_ERR("error opening registry key, menu cleanup failed\n");
2618 static CHAR *next_token( LPSTR *p )
2620 LPSTR token = NULL, t = *p;
2622 if( !t )
2623 return NULL;
2625 while( t && !token )
2627 switch( *t )
2629 case ' ':
2630 t++;
2631 continue;
2632 case '"':
2633 /* unquote the token */
2634 token = ++t;
2635 t = strchr( token, '"' );
2636 if( t )
2637 *t++ = 0;
2638 break;
2639 case 0:
2640 t = NULL;
2641 break;
2642 default:
2643 token = t;
2644 t = strchr( token, ' ' );
2645 if( t )
2646 *t++ = 0;
2647 break;
2650 *p = t;
2651 return token;
2654 static BOOL init_xdg(void)
2656 WCHAR shellDesktopPath[MAX_PATH];
2657 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2658 if (SUCCEEDED(hr))
2659 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2660 if (xdg_desktop_dir == NULL)
2662 WINE_ERR("error looking up the desktop directory\n");
2663 return FALSE;
2666 if (getenv("XDG_CONFIG_HOME"))
2667 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2668 else
2669 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2670 if (xdg_config_dir)
2672 create_directories(xdg_config_dir);
2673 if (getenv("XDG_DATA_HOME"))
2674 xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
2675 else
2676 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2677 if (xdg_data_dir)
2679 char *buffer;
2680 create_directories(xdg_data_dir);
2681 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2682 if (buffer)
2684 mkdir(buffer, 0777);
2685 HeapFree(GetProcessHeap(), 0, buffer);
2687 return TRUE;
2689 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2691 WINE_ERR("out of memory\n");
2692 return FALSE;
2695 /***********************************************************************
2697 * WinMain
2699 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
2701 LPSTR token = NULL, p;
2702 BOOL bWait = FALSE;
2703 BOOL bURL = FALSE;
2704 int ret = 0;
2706 if (!init_xdg())
2707 return 1;
2709 for( p = cmdline; p && *p; )
2711 token = next_token( &p );
2712 if( !token )
2713 break;
2714 if( !lstrcmpA( token, "-a" ) )
2716 RefreshFileTypeAssociations();
2717 break;
2719 if( !lstrcmpA( token, "-r" ) )
2721 cleanup_menus();
2722 break;
2724 if( !lstrcmpA( token, "-w" ) )
2725 bWait = TRUE;
2726 else if ( !lstrcmpA( token, "-u" ) )
2727 bURL = TRUE;
2728 else if( token[0] == '-' )
2730 WINE_ERR( "unknown option %s\n",token);
2732 else
2734 WCHAR link[MAX_PATH];
2735 BOOL bRet;
2737 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2738 if (bURL)
2739 bRet = Process_URL( link, bWait );
2740 else
2741 bRet = Process_Link( link, bWait );
2742 if (!bRet)
2744 WINE_ERR( "failed to build menu item for %s\n",token);
2745 ret = 1;
2750 return ret;