push 6377a023768d7480eb1b17e57456824888936b43
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blob15ce483f28754f0934757c1b51a0d38fdacb3857
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 *strdupA( const char *str )
697 char *ret;
699 if (!str) return NULL;
700 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
701 return ret;
704 static char* heap_printf(const char *format, ...)
706 va_list args;
707 int size = 4096;
708 char *buffer, *ret;
709 int n;
711 va_start(args, format);
712 while (1)
714 buffer = HeapAlloc(GetProcessHeap(), 0, size);
715 if (buffer == NULL)
716 break;
717 n = vsnprintf(buffer, size, format, args);
718 if (n == -1)
719 size *= 2;
720 else if (n >= size)
721 size = n + 1;
722 else
723 break;
724 HeapFree(GetProcessHeap(), 0, buffer);
726 va_end(args);
727 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
728 if (!ret) ret = buffer;
729 return ret;
732 static BOOL create_directories(char *directory)
734 BOOL ret = TRUE;
735 int i;
737 for (i = 0; directory[i]; i++)
739 if (i > 0 && directory[i] == '/')
741 directory[i] = 0;
742 mkdir(directory, 0777);
743 directory[i] = '/';
746 if (mkdir(directory, 0777) && errno != EEXIST)
747 ret = FALSE;
749 return ret;
752 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
753 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
755 unsigned short crc;
756 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
757 char* s;
758 int n;
760 /* Where should we save the icon? */
761 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
762 iconsdir = heap_printf("%s/icons", xdg_data_dir);
763 if (iconsdir)
765 if (mkdir(iconsdir, 0777) && errno != EEXIST)
767 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
768 goto end;
771 else
773 WINE_TRACE("no icon created\n");
774 return NULL;
777 /* Determine the icon base name */
778 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
779 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
780 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
781 s=ico_name=ico_path;
782 while (*s!='\0') {
783 if (*s=='/' || *s=='\\') {
784 *s='\\';
785 ico_name=s;
786 } else {
787 *s=tolower(*s);
789 s++;
791 if (*ico_name=='\\') *ico_name++='\0';
792 s=strrchr(ico_name,'.');
793 if (s) *s='\0';
795 /* Compute the source-path hash */
796 crc=crc16(ico_path);
798 /* Try to treat the source file as an exe */
799 if (destFilename)
800 xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
801 else
802 xpm_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
803 if (xpm_path == NULL)
805 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
806 return NULL;
809 if (ExtractFromEXEDLL( path, index, xpm_path ))
810 goto end;
812 /* Must be something else, ignore the index in that case */
813 if (destFilename)
814 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
815 else
816 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
817 if (ExtractFromICO( path, xpm_path))
818 goto end;
819 if (!bWait)
821 if (destFilename)
822 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
823 else
824 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
825 if (create_default_icon( xpm_path, ico_path ))
826 goto end;
829 HeapFree( GetProcessHeap(), 0, xpm_path );
830 xpm_path=NULL;
832 end:
833 HeapFree(GetProcessHeap(), 0, iconsdir);
834 HeapFree(GetProcessHeap(), 0, ico_path);
835 return xpm_path;
838 static HKEY open_menus_reg_key(void)
840 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
841 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
842 HKEY assocKey;
843 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
844 return assocKey;
845 return NULL;
848 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
849 const char *path, const char *args, const char *descr,
850 const char *workdir, const char *icon)
852 FILE *file;
854 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
855 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
856 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
858 file = fopen(location, "w");
859 if (file == NULL)
860 return FALSE;
862 fprintf(file, "[Desktop Entry]\n");
863 fprintf(file, "Name=%s\n", linkname);
864 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
865 wine_get_config_dir(), path, args);
866 fprintf(file, "Type=Application\n");
867 fprintf(file, "StartupNotify=true\n");
868 if (descr && lstrlenA(descr))
869 fprintf(file, "Comment=%s\n", descr);
870 if (workdir && lstrlenA(workdir))
871 fprintf(file, "Path=%s\n", workdir);
872 if (icon && lstrlenA(icon))
873 fprintf(file, "Icon=%s\n", icon);
875 fclose(file);
877 if (unix_link)
879 HKEY hkey = open_menus_reg_key();
880 if (hkey)
882 RegSetValueExA(hkey, location, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
883 RegCloseKey(hkey);
885 else
886 return FALSE;
889 return TRUE;
892 static BOOL write_directory_entry(const char *directory, const char *location)
894 FILE *file;
896 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
898 file = fopen(location, "w");
899 if (file == NULL)
900 return FALSE;
902 fprintf(file, "[Desktop Entry]\n");
903 fprintf(file, "Type=Directory\n");
904 if (strcmp(directory, "wine") == 0)
906 fprintf(file, "Name=Wine\n");
907 fprintf(file, "Icon=wine\n");
909 else
911 fprintf(file, "Name=%s\n", directory);
912 fprintf(file, "Icon=folder\n");
915 fclose(file);
916 return TRUE;
919 static BOOL write_menu_file(const char *unix_link, const char *filename)
921 char *tempfilename;
922 FILE *tempfile = NULL;
923 char *lastEntry;
924 char *name = NULL;
925 char *menuPath = NULL;
926 int i;
927 int count = 0;
928 BOOL ret = FALSE;
930 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
932 while (1)
934 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
935 if (tempfilename)
937 int tempfd = mkstemps(tempfilename, 0);
938 if (tempfd >= 0)
940 tempfile = fdopen(tempfd, "w");
941 if (tempfile)
942 break;
943 close(tempfd);
944 goto end;
946 else if (errno == EEXIST)
948 HeapFree(GetProcessHeap(), 0, tempfilename);
949 continue;
951 HeapFree(GetProcessHeap(), 0, tempfilename);
953 return FALSE;
956 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
957 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
958 fprintf(tempfile, "<Menu>\n");
959 fprintf(tempfile, " <Name>Applications</Name>\n");
961 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
962 if (name == NULL) goto end;
963 lastEntry = name;
964 for (i = 0; filename[i]; i++)
966 name[i] = filename[i];
967 if (filename[i] == '/')
969 char *dir_file_name;
970 struct stat st;
971 name[i] = 0;
972 fprintf(tempfile, " <Menu>\n");
973 fprintf(tempfile, " <Name>%s%s</Name>\n", count ? "" : "wine-", name);
974 fprintf(tempfile, " <Directory>%s%s.directory</Directory>\n", count ? "" : "wine-", name);
975 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
976 xdg_data_dir, count ? "" : "wine-", name);
977 if (dir_file_name)
979 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
980 write_directory_entry(lastEntry, dir_file_name);
981 HeapFree(GetProcessHeap(), 0, dir_file_name);
983 name[i] = '-';
984 lastEntry = &name[i+1];
985 ++count;
988 name[i] = 0;
990 fprintf(tempfile, " <Include>\n");
991 fprintf(tempfile, " <Filename>%s</Filename>\n", name);
992 fprintf(tempfile, " </Include>\n");
993 for (i = 0; i < count; i++)
994 fprintf(tempfile, " </Menu>\n");
995 fprintf(tempfile, "</Menu>\n");
997 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
998 if (menuPath == NULL) goto end;
999 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1000 ret = TRUE;
1002 end:
1003 if (tempfile)
1004 fclose(tempfile);
1005 if (ret)
1006 ret = (rename(tempfilename, menuPath) == 0);
1007 if (!ret && tempfilename)
1008 remove(tempfilename);
1009 HeapFree(GetProcessHeap(), 0, tempfilename);
1010 if (ret)
1012 HKEY hkey = open_menus_reg_key();
1013 if (hkey)
1015 RegSetValueExA(hkey, menuPath, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
1016 RegCloseKey(hkey);
1019 HeapFree(GetProcessHeap(), 0, name);
1020 HeapFree(GetProcessHeap(), 0, menuPath);
1021 return ret;
1024 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1025 const char *descr, const char *workdir, const char *icon)
1027 const char *linkname;
1028 char *desktopPath = NULL;
1029 char *desktopDir;
1030 char *filename = NULL;
1031 BOOL ret = TRUE;
1033 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1034 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1035 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1037 linkname = strrchr(link, '/');
1038 if (linkname == NULL)
1039 linkname = link;
1040 else
1041 ++linkname;
1043 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1044 if (!desktopPath)
1046 WINE_WARN("out of memory creating menu entry\n");
1047 ret = FALSE;
1048 goto end;
1050 desktopDir = strrchr(desktopPath, '/');
1051 *desktopDir = 0;
1052 if (!create_directories(desktopPath))
1054 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1055 ret = FALSE;
1056 goto end;
1058 *desktopDir = '/';
1059 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1061 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1062 ret = FALSE;
1063 goto end;
1066 filename = heap_printf("wine/%s.desktop", link);
1067 if (!filename || !write_menu_file(unix_link, filename))
1069 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1070 ret = FALSE;
1073 end:
1074 HeapFree(GetProcessHeap(), 0, desktopPath);
1075 HeapFree(GetProcessHeap(), 0, filename);
1076 return ret;
1079 /* This escapes \ in filenames */
1080 static LPSTR escape(LPCWSTR arg)
1082 LPSTR narg, x;
1083 LPCWSTR esc;
1084 int len = 0, n;
1086 esc = arg;
1087 while((esc = strchrW(esc, '\\')))
1089 esc++;
1090 len++;
1093 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1094 narg = HeapAlloc(GetProcessHeap(), 0, len);
1096 x = narg;
1097 while (*arg)
1099 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1100 x += n;
1101 len -= n;
1102 if (*arg == '\\')
1103 *x++='\\'; /* escape \ */
1104 arg++;
1106 *x = 0;
1107 return narg;
1110 /* Return a heap-allocated copy of the unix format difference between the two
1111 * Windows-format paths.
1112 * locn is the owning location
1113 * link is within locn
1115 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1117 char *unix_locn, *unix_link;
1118 char *relative = NULL;
1120 unix_locn = wine_get_unix_file_name(locn);
1121 unix_link = wine_get_unix_file_name(link);
1122 if (unix_locn && unix_link)
1124 size_t len_unix_locn, len_unix_link;
1125 len_unix_locn = strlen (unix_locn);
1126 len_unix_link = strlen (unix_link);
1127 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1129 size_t len_rel;
1130 char *p = strrchr (unix_link + len_unix_locn, '/');
1131 p = strrchr (p, '.');
1132 if (p)
1134 *p = '\0';
1135 len_unix_link = p - unix_link;
1137 len_rel = len_unix_link - len_unix_locn;
1138 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1139 if (relative)
1141 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1145 if (!relative)
1146 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1147 HeapFree(GetProcessHeap(), 0, unix_locn);
1148 HeapFree(GetProcessHeap(), 0, unix_link);
1149 return relative;
1152 /***********************************************************************
1154 * GetLinkLocation
1156 * returns TRUE if successful
1157 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1158 * *relative will contain the address of a heap-allocated copy of the portion
1159 * of the filename that is within the specified location, in unix form
1161 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1163 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1164 DWORD len, i, r, filelen;
1165 const DWORD locations[] = {
1166 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1167 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1168 CSIDL_COMMON_STARTMENU };
1170 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1171 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1172 if (filelen==0 || filelen>MAX_PATH)
1173 return FALSE;
1175 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1177 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1178 * expand or our hardcoded list won't match.
1180 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1181 if (filelen==0 || filelen>MAX_PATH)
1182 return FALSE;
1184 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1186 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1188 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1189 continue;
1191 len = lstrlenW(buffer);
1192 if (len >= MAX_PATH)
1193 continue; /* We've just trashed memory! Hopefully we are OK */
1195 if (len > filelen || filename[len]!='\\')
1196 continue;
1197 /* do a lstrcmpinW */
1198 filename[len] = 0;
1199 r = lstrcmpiW( filename, buffer );
1200 filename[len] = '\\';
1201 if ( r )
1202 continue;
1204 /* return the remainder of the string and link type */
1205 *loc = locations[i];
1206 *relative = relative_path (filename, buffer);
1207 return (*relative != NULL);
1210 return FALSE;
1213 /* gets the target path directly or through MSI */
1214 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1215 LPWSTR szArgs, DWORD argsSize)
1217 IShellLinkDataList *dl = NULL;
1218 EXP_DARWIN_LINK *dar = NULL;
1219 HRESULT hr;
1221 szPath[0] = 0;
1222 szArgs[0] = 0;
1224 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1225 if (hr == S_OK && szPath[0])
1227 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1228 return hr;
1231 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1232 if (FAILED(hr))
1233 return hr;
1235 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1236 if (SUCCEEDED(hr))
1238 WCHAR* szCmdline;
1239 DWORD cmdSize;
1241 cmdSize=0;
1242 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1243 if (hr == ERROR_SUCCESS)
1245 cmdSize++;
1246 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1247 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1248 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1249 if (hr == ERROR_SUCCESS)
1251 WCHAR *s, *d;
1252 int bcount, in_quotes;
1254 /* Extract the application path */
1255 bcount=0;
1256 in_quotes=0;
1257 s=szCmdline;
1258 d=szPath;
1259 while (*s)
1261 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1263 /* skip the remaining spaces */
1264 do {
1265 s++;
1266 } while (*s==0x0009 || *s==0x0020);
1267 break;
1269 else if (*s==0x005c)
1271 /* '\\' */
1272 *d++=*s++;
1273 bcount++;
1275 else if (*s==0x0022)
1277 /* '"' */
1278 if ((bcount & 1)==0)
1280 /* Preceded by an even number of '\', this is
1281 * half that number of '\', plus a quote which
1282 * we erase.
1284 d-=bcount/2;
1285 in_quotes=!in_quotes;
1286 s++;
1288 else
1290 /* Preceded by an odd number of '\', this is
1291 * half that number of '\' followed by a '"'
1293 d=d-bcount/2-1;
1294 *d++='"';
1295 s++;
1297 bcount=0;
1299 else
1301 /* a regular character */
1302 *d++=*s++;
1303 bcount=0;
1305 if ((d-szPath) == pathSize)
1307 /* Keep processing the path till we get to the
1308 * arguments, but 'stand still'
1310 d--;
1313 /* Close the application path */
1314 *d=0;
1316 lstrcpynW(szArgs, s, argsSize);
1318 HeapFree( GetProcessHeap(), 0, szCmdline );
1320 LocalFree( dar );
1323 IShellLinkDataList_Release( dl );
1324 return hr;
1327 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1329 HRESULT hr;
1330 WCHAR *value = NULL;
1331 DWORD size = 0;
1332 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1333 if (SUCCEEDED(hr))
1335 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1336 if (value)
1338 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1339 if (FAILED(hr))
1341 HeapFree(GetProcessHeap(), 0, value);
1342 value = NULL;
1346 return value;
1349 static char* wchars_to_utf8_chars(LPCWSTR string)
1351 char *ret;
1352 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
1353 ret = HeapAlloc(GetProcessHeap(), 0, size);
1354 if (ret)
1355 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
1356 return ret;
1359 static char *slashes_to_minuses(const char *string)
1361 int i;
1362 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1363 if (ret)
1365 for (i = 0; string[i]; i++)
1367 if (string[i] == '/')
1368 ret[i] = '-';
1369 else
1370 ret[i] = string[i];
1372 ret[i] = 0;
1373 return ret;
1375 return NULL;
1378 static BOOL next_line(FILE *file, char **line, int *size)
1380 int pos = 0;
1381 char *cr;
1382 if (*line == NULL)
1384 *size = 4096;
1385 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1387 while (*line != NULL)
1389 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1391 HeapFree(GetProcessHeap(), 0, *line);
1392 *line = NULL;
1393 if (feof(file))
1394 return TRUE;
1395 return FALSE;
1397 pos = strlen(*line);
1398 cr = strchr(*line, '\n');
1399 if (cr == NULL)
1401 char *line2;
1402 (*size) *= 2;
1403 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1404 if (line2)
1405 *line = line2;
1406 else
1408 HeapFree(GetProcessHeap(), 0, *line);
1409 *line = NULL;
1412 else
1414 *cr = 0;
1415 return TRUE;
1418 return FALSE;
1421 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1423 char *globs_filename = NULL;
1424 BOOL ret = TRUE;
1425 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1426 if (globs_filename)
1428 FILE *globs_file = fopen(globs_filename, "r");
1429 if (globs_file) /* doesn't have to exist */
1431 char *line = NULL;
1432 int size = 0;
1433 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1435 char *pos;
1436 struct xdg_mime_type *mime_type_entry = NULL;
1437 if (line[0] != '#' && (pos = strchr(line, ':')))
1439 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1440 if (mime_type_entry)
1442 *pos = 0;
1443 mime_type_entry->mimeType = strdupA(line);
1444 mime_type_entry->glob = strdupA(pos + 1);
1445 if (mime_type_entry->mimeType && mime_type_entry->glob)
1446 list_add_tail(mime_types, &mime_type_entry->entry);
1447 else
1449 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1450 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1451 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1452 ret = FALSE;
1455 else
1456 ret = FALSE;
1459 HeapFree(GetProcessHeap(), 0, line);
1460 fclose(globs_file);
1462 HeapFree(GetProcessHeap(), 0, globs_filename);
1464 else
1465 ret = FALSE;
1466 return ret;
1469 static void free_native_mime_types(struct list *native_mime_types)
1471 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1473 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1475 list_remove(&mime_type_entry->entry);
1476 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1477 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1478 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1480 HeapFree(GetProcessHeap(), 0, native_mime_types);
1483 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1485 char *xdg_data_dirs;
1486 BOOL ret;
1488 *mime_types = NULL;
1490 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1491 if (xdg_data_dirs == NULL)
1492 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1493 else
1494 xdg_data_dirs = strdupA(xdg_data_dirs);
1496 if (xdg_data_dirs)
1498 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1499 if (*mime_types)
1501 const char *begin;
1502 char *end;
1504 list_init(*mime_types);
1505 ret = add_mimes(xdg_data_home, *mime_types);
1506 if (ret)
1508 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1510 *end = '\0';
1511 ret = add_mimes(begin, *mime_types);
1512 *end = ':';
1513 if (!ret)
1514 break;
1516 if (ret)
1517 ret = add_mimes(begin, *mime_types);
1520 else
1521 ret = FALSE;
1522 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1524 else
1525 ret = FALSE;
1526 if (!ret && *mime_types)
1528 free_native_mime_types(*mime_types);
1529 *mime_types = NULL;
1531 return ret;
1534 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1535 char **match)
1537 #ifdef HAVE_FNMATCH
1538 struct xdg_mime_type *mime_type_entry;
1539 int matchLength = 0;
1541 *match = NULL;
1543 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1545 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1547 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1549 *match = mime_type_entry->mimeType;
1550 matchLength = strlen(mime_type_entry->glob);
1555 if (*match != NULL)
1557 *match = strdupA(*match);
1558 if (*match == NULL)
1559 return FALSE;
1561 #else
1562 *match = NULL;
1563 #endif
1564 return TRUE;
1567 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1568 const char *extensionA,
1569 LPCWSTR extensionW,
1570 char **mime_type)
1572 WCHAR *lower_extensionW;
1573 INT len;
1574 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1575 if (ret == FALSE || *mime_type != NULL)
1576 return ret;
1577 len = strlenW(extensionW);
1578 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1579 if (lower_extensionW)
1581 char *lower_extensionA;
1582 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1583 strlwrW(lower_extensionW);
1584 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1585 if (lower_extensionA)
1587 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1588 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1590 else
1592 ret = FALSE;
1593 WINE_FIXME("out of memory\n");
1595 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1597 else
1599 ret = FALSE;
1600 WINE_FIXME("out of memory\n");
1602 return ret;
1605 static CHAR* reg_get_valA(HKEY key, LPCSTR subkey, LPCSTR name)
1607 DWORD size;
1608 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1610 CHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1611 if (ret)
1613 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1614 return ret;
1616 HeapFree(GetProcessHeap(), 0, ret);
1618 return NULL;
1621 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1623 DWORD size;
1624 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1626 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1627 if (ret)
1629 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1630 return ret;
1632 HeapFree(GetProcessHeap(), 0, ret);
1634 return NULL;
1637 static HKEY open_associations_reg_key(void)
1639 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1640 '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};
1641 HKEY assocKey;
1642 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1643 return assocKey;
1644 return NULL;
1647 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1649 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1650 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1651 HKEY assocKey;
1652 BOOL ret;
1654 if ((assocKey = open_associations_reg_key()))
1656 CHAR *valueA;
1657 WCHAR *value;
1659 ret = FALSE;
1661 valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1662 if (!valueA || lstrcmpA(valueA, mimeType))
1663 ret = TRUE;
1664 HeapFree(GetProcessHeap(), 0, valueA);
1666 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1667 if (!value || strcmpW(value, progId))
1668 ret = TRUE;
1669 HeapFree(GetProcessHeap(), 0, value);
1671 valueA = reg_get_valA(assocKey, extensionA, "AppName");
1672 if (!valueA || lstrcmpA(valueA, appName))
1673 ret = TRUE;
1674 HeapFree(GetProcessHeap(), 0, valueA);
1676 value = reg_get_valW(assocKey, extensionW, DocNameW);
1677 if (docName && (!value || strcmpW(value, docName)))
1678 ret = TRUE;
1679 HeapFree(GetProcessHeap(), 0, value);
1681 RegCloseKey(assocKey);
1683 else
1685 WINE_ERR("error opening associations registry key\n");
1686 ret = FALSE;
1688 return ret;
1691 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1693 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1694 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1695 HKEY assocKey;
1697 if ((assocKey = open_associations_reg_key()))
1699 HKEY subkey;
1700 if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1702 RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (BYTE*) mimeType, lstrlenA(mimeType) + 1);
1703 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1704 RegSetValueExA(subkey, "AppName", 0, REG_SZ, (BYTE*) appName, lstrlenA(appName) + 1);
1705 if (docName)
1706 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1707 RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1708 RegCloseKey(subkey);
1710 else
1711 WINE_ERR("could not create extension subkey\n");
1712 RegCloseKey(assocKey);
1714 else
1715 WINE_ERR("could not open file associations key\n");
1718 static BOOL cleanup_associations(void)
1720 static const WCHAR openW[] = {'o','p','e','n',0};
1721 HKEY assocKey;
1722 BOOL hasChanged = FALSE;
1723 if ((assocKey = open_associations_reg_key()))
1725 int i;
1726 BOOL done = FALSE;
1727 for (i = 0; !done; i++)
1729 WCHAR *extensionW = NULL;
1730 char *extensionA = NULL;
1731 DWORD size = 1024;
1732 LSTATUS ret;
1736 HeapFree(GetProcessHeap(), 0, extensionW);
1737 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1738 if (extensionW == NULL)
1740 WINE_ERR("out of memory\n");
1741 ret = ERROR_OUTOFMEMORY;
1742 break;
1744 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1745 size *= 2;
1746 } while (ret == ERROR_MORE_DATA);
1748 if (ret == ERROR_SUCCESS)
1750 WCHAR *command;
1751 extensionA = wchars_to_utf8_chars(extensionW);
1752 if (extensionA == NULL)
1754 WINE_ERR("out of memory\n");
1755 done = TRUE;
1756 goto end;
1758 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1759 if (command == NULL)
1761 char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1762 if (desktopFile)
1764 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1765 remove(desktopFile);
1767 RegDeleteKeyW(assocKey, extensionW);
1768 hasChanged = TRUE;
1769 HeapFree(GetProcessHeap(), 0, desktopFile);
1771 HeapFree(GetProcessHeap(), 0, command);
1773 else
1775 if (ret != ERROR_NO_MORE_ITEMS)
1776 WINE_ERR("error %d while reading registry\n", ret);
1777 done = TRUE;
1779 end:
1780 HeapFree(GetProcessHeap(), 0, extensionA);
1781 HeapFree(GetProcessHeap(), 0, extensionW);
1783 RegCloseKey(assocKey);
1785 else
1786 WINE_ERR("could not open file associations key\n");
1787 return hasChanged;
1790 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1791 const char *mime_type, const char *comment)
1793 BOOL ret = FALSE;
1794 char *filename;
1796 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1797 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1799 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1800 if (filename)
1802 FILE *packageFile = fopen(filename, "w");
1803 if (packageFile)
1805 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1806 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1807 fprintf(packageFile, " <mime-type type=\"%s\">\n", mime_type);
1808 fprintf(packageFile, " <glob pattern=\"*%s\"/>\n", dot_extension);
1809 if (comment)
1810 fprintf(packageFile, " <comment>%s</comment>\n", comment);
1811 fprintf(packageFile, " </mime-type>\n");
1812 fprintf(packageFile, "</mime-info>\n");
1813 ret = TRUE;
1814 fclose(packageFile);
1816 else
1817 WINE_ERR("error writing file %s\n", filename);
1818 HeapFree(GetProcessHeap(), 0, filename);
1820 else
1821 WINE_ERR("out of memory\n");
1822 return ret;
1825 static BOOL is_extension_blacklisted(LPCWSTR extension)
1827 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1828 static const WCHAR comW[] = {'.','c','o','m',0};
1829 static const WCHAR exeW[] = {'.','e','x','e',0};
1830 static const WCHAR msiW[] = {'.','m','s','i',0};
1832 if (!strcmpiW(extension, comW) ||
1833 !strcmpiW(extension, exeW) ||
1834 !strcmpiW(extension, msiW))
1835 return TRUE;
1836 return FALSE;
1839 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1840 const char *friendlyAppName, const char *mimeType,
1841 const char *progId)
1843 BOOL ret = FALSE;
1844 FILE *desktop;
1846 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1847 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1848 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1850 desktop = fopen(desktopPath, "w");
1851 if (desktop)
1853 fprintf(desktop, "[Desktop Entry]\n");
1854 fprintf(desktop, "Type=Application\n");
1855 fprintf(desktop, "Name=%s\n", friendlyAppName);
1856 fprintf(desktop, "MimeType=%s\n", mimeType);
1857 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1858 fprintf(desktop, "NoDisplay=true\n");
1859 fprintf(desktop, "StartupNotify=true\n");
1860 ret = TRUE;
1861 fclose(desktop);
1863 else
1864 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1865 return ret;
1868 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1870 static const WCHAR openW[] = {'o','p','e','n',0};
1871 struct list *nativeMimeTypes = NULL;
1872 LSTATUS ret = 0;
1873 int i;
1874 BOOL hasChanged = FALSE;
1876 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1878 WINE_ERR("could not build native MIME types\n");
1879 return FALSE;
1882 for (i = 0; ; i++)
1884 WCHAR *extensionW = NULL;
1885 DWORD size = 1024;
1889 HeapFree(GetProcessHeap(), 0, extensionW);
1890 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1891 if (extensionW == NULL)
1893 WINE_ERR("out of memory\n");
1894 ret = ERROR_OUTOFMEMORY;
1895 break;
1897 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1898 size *= 2;
1899 } while (ret == ERROR_MORE_DATA);
1901 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1903 char *extensionA = NULL;
1904 WCHAR *commandW = NULL;
1905 WCHAR *friendlyDocNameW = NULL;
1906 char *friendlyDocNameA = NULL;
1907 WCHAR *iconW = NULL;
1908 char *iconA = NULL;
1909 WCHAR *contentTypeW = NULL;
1910 char *mimeTypeA = NULL;
1911 WCHAR *friendlyAppNameW = NULL;
1912 char *friendlyAppNameA = NULL;
1913 WCHAR *progIdW = NULL;
1914 char *progIdA = NULL;
1916 extensionA = wchars_to_utf8_chars(extensionW);
1917 if (extensionA == NULL)
1919 WINE_ERR("out of memory\n");
1920 goto end;
1923 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
1924 if (friendlyDocNameW)
1926 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
1927 if (friendlyDocNameA == NULL)
1929 WINE_ERR("out of memory\n");
1930 goto end;
1934 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
1936 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
1938 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
1939 goto end;
1941 if (mimeTypeA == NULL)
1943 if (contentTypeW != NULL)
1944 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
1945 else
1946 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
1948 if (mimeTypeA != NULL)
1950 /* Gnome seems to ignore the <icon> tag in MIME packages,
1951 * and the default name is more intuitive anyway.
1953 if (iconW)
1955 char *flattened_mime = slashes_to_minuses(mimeTypeA);
1956 if (flattened_mime)
1958 int index = 0;
1959 WCHAR *comma = strrchrW(iconW, ',');
1960 if (comma)
1962 *comma = 0;
1963 index = atoiW(comma + 1);
1965 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
1966 HeapFree(GetProcessHeap(), 0, flattened_mime);
1970 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
1971 hasChanged = TRUE;
1973 else
1975 WINE_FIXME("out of memory\n");
1976 goto end;
1980 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1981 if (commandW == NULL)
1982 /* no command => no application is associated */
1983 goto end;
1985 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
1986 if (friendlyAppNameW)
1988 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
1989 if (friendlyAppNameA == NULL)
1991 WINE_ERR("out of memory\n");
1992 goto end;
1995 else
1997 friendlyAppNameA = heap_printf("A Wine application");
1998 if (friendlyAppNameA == NULL)
2000 WINE_ERR("out of memory\n");
2001 goto end;
2005 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2006 if (progIdW)
2008 progIdA = wchars_to_utf8_chars(progIdW);
2009 if (progIdA == NULL)
2011 WINE_ERR("out of memory\n");
2012 goto end;
2015 else
2016 goto end; /* no progID => not a file type association */
2018 if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2020 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2021 if (desktopPath)
2023 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2025 hasChanged = TRUE;
2026 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2028 HeapFree(GetProcessHeap(), 0, desktopPath);
2032 end:
2033 HeapFree(GetProcessHeap(), 0, extensionA);
2034 HeapFree(GetProcessHeap(), 0, commandW);
2035 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2036 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2037 HeapFree(GetProcessHeap(), 0, iconW);
2038 HeapFree(GetProcessHeap(), 0, iconA);
2039 HeapFree(GetProcessHeap(), 0, contentTypeW);
2040 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2041 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2042 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2043 HeapFree(GetProcessHeap(), 0, progIdW);
2044 HeapFree(GetProcessHeap(), 0, progIdA);
2046 HeapFree(GetProcessHeap(), 0, extensionW);
2047 if (ret != ERROR_SUCCESS)
2048 break;
2051 free_native_mime_types(nativeMimeTypes);
2052 return hasChanged;
2055 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2057 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2058 '\\','s','t','a','r','t','.','e','x','e',0};
2059 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2060 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
2061 WCHAR szTmp[INFOTIPSIZE];
2062 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2063 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2064 int iIconId = 0, r = -1;
2065 DWORD csidl = -1;
2066 HANDLE hsem = NULL;
2067 char *unix_link = NULL;
2069 if ( !link )
2071 WINE_ERR("Link name is null\n");
2072 return FALSE;
2075 if( !GetLinkLocation( link, &csidl, &link_name ) )
2077 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2078 return TRUE;
2080 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2082 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2083 return TRUE;
2085 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2087 szTmp[0] = 0;
2088 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2089 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2090 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2092 szTmp[0] = 0;
2093 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2094 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2095 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2097 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
2098 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2099 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2101 szTmp[0] = 0;
2102 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2103 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2104 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2106 if( !szPath[0] )
2108 LPITEMIDLIST pidl = NULL;
2109 IShellLinkW_GetIDList( sl, &pidl );
2110 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2111 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2114 /* extract the icon */
2115 if( szIconPath[0] )
2116 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2117 else
2118 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2120 /* fail - try once again after parent process exit */
2121 if( !icon_name )
2123 if (bWait)
2125 WINE_WARN("Unable to extract icon, deferring.\n");
2126 goto cleanup;
2128 WINE_ERR("failed to extract icon from %s\n",
2129 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2132 unix_link = wine_get_unix_file_name(link);
2133 if (unix_link == NULL)
2135 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2136 goto cleanup;
2139 /* check the path */
2140 if( szPath[0] )
2142 static const WCHAR exeW[] = {'.','e','x','e',0};
2143 WCHAR *p;
2145 /* check for .exe extension */
2146 if (!(p = strrchrW( szPath, '.' )) ||
2147 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2148 lstrcmpiW( p, exeW ))
2150 /* Not .exe - use 'start.exe' to launch this file */
2151 p = szArgs + lstrlenW(szPath) + 2;
2152 if (szArgs[0])
2154 p[0] = ' ';
2155 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2156 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2158 else
2159 p[0] = 0;
2161 szArgs[0] = '"';
2162 lstrcpyW(szArgs + 1, szPath);
2163 p[-1] = '"';
2165 GetWindowsDirectoryW(szPath, MAX_PATH);
2166 lstrcatW(szPath, startW);
2169 /* convert app working dir */
2170 if (szWorkDir[0])
2171 work_dir = wine_get_unix_file_name( szWorkDir );
2173 else
2175 /* if there's no path... try run the link itself */
2176 lstrcpynW(szArgs, link, MAX_PATH);
2177 GetWindowsDirectoryW(szPath, MAX_PATH);
2178 lstrcatW(szPath, startW);
2181 /* escape the path and parameters */
2182 escaped_path = escape(szPath);
2183 escaped_args = escape(szArgs);
2184 escaped_description = escape(szDescription);
2186 /* building multiple menus concurrently has race conditions */
2187 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2188 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2190 WINE_ERR("failed wait for semaphore\n");
2191 goto cleanup;
2194 if (in_desktop_dir(csidl))
2196 char *location;
2197 const char *lastEntry;
2198 lastEntry = strrchr(link_name, '/');
2199 if (lastEntry == NULL)
2200 lastEntry = link_name;
2201 else
2202 ++lastEntry;
2203 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2204 if (location)
2206 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2207 HeapFree(GetProcessHeap(), 0, location);
2210 else
2211 r = !write_menu_entry(unix_link, link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2213 ReleaseSemaphore( hsem, 1, NULL );
2215 cleanup:
2216 if (hsem) CloseHandle( hsem );
2217 HeapFree( GetProcessHeap(), 0, icon_name );
2218 HeapFree( GetProcessHeap(), 0, work_dir );
2219 HeapFree( GetProcessHeap(), 0, link_name );
2220 HeapFree( GetProcessHeap(), 0, escaped_args );
2221 HeapFree( GetProcessHeap(), 0, escaped_path );
2222 HeapFree( GetProcessHeap(), 0, escaped_description );
2223 HeapFree( GetProcessHeap(), 0, unix_link);
2225 if (r && !bWait)
2226 WINE_ERR("failed to build the menu\n" );
2228 return ( r == 0 );
2231 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2233 char *link_name = NULL;
2234 DWORD csidl = -1;
2235 LPWSTR urlPath;
2236 char *escaped_urlPath = NULL;
2237 HRESULT hr;
2238 HANDLE hSem = NULL;
2239 BOOL ret = TRUE;
2240 int r = -1;
2241 char *unix_link = NULL;
2243 if ( !link )
2245 WINE_ERR("Link name is null\n");
2246 return TRUE;
2249 if( !GetLinkLocation( link, &csidl, &link_name ) )
2251 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2252 return TRUE;
2254 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2256 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2257 ret = TRUE;
2258 goto cleanup;
2260 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2262 hr = url->lpVtbl->GetURL(url, &urlPath);
2263 if (FAILED(hr))
2265 ret = TRUE;
2266 goto cleanup;
2268 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2270 unix_link = wine_get_unix_file_name(link);
2271 if (unix_link == NULL)
2273 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2274 goto cleanup;
2277 escaped_urlPath = escape(urlPath);
2279 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2280 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2282 WINE_ERR("failed wait for semaphore\n");
2283 goto cleanup;
2285 if (in_desktop_dir(csidl))
2287 char *location;
2288 const char *lastEntry;
2289 lastEntry = strrchr(link_name, '/');
2290 if (lastEntry == NULL)
2291 lastEntry = link_name;
2292 else
2293 ++lastEntry;
2294 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2295 if (location)
2297 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2298 HeapFree(GetProcessHeap(), 0, location);
2301 else
2302 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2303 ret = (r != 0);
2304 ReleaseSemaphore(hSem, 1, NULL);
2306 cleanup:
2307 if (hSem)
2308 CloseHandle(hSem);
2309 HeapFree(GetProcessHeap(), 0, link_name);
2310 CoTaskMemFree( urlPath );
2311 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2312 HeapFree(GetProcessHeap(), 0, unix_link);
2313 return ret;
2316 static BOOL WaitForParentProcess( void )
2318 PROCESSENTRY32 procentry;
2319 HANDLE hsnapshot = NULL, hprocess = NULL;
2320 DWORD ourpid = GetCurrentProcessId();
2321 BOOL ret = FALSE, rc;
2323 WINE_TRACE("Waiting for parent process\n");
2324 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2325 INVALID_HANDLE_VALUE)
2327 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2328 goto done;
2331 procentry.dwSize = sizeof(PROCESSENTRY32);
2332 rc = Process32First( hsnapshot, &procentry );
2333 while (rc)
2335 if (procentry.th32ProcessID == ourpid) break;
2336 rc = Process32Next( hsnapshot, &procentry );
2338 if (!rc)
2340 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2341 goto done;
2344 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2345 NULL)
2347 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2348 GetLastError());
2349 goto done;
2352 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2353 ret = TRUE;
2354 else
2355 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2357 done:
2358 if (hprocess) CloseHandle( hprocess );
2359 if (hsnapshot) CloseHandle( hsnapshot );
2360 return ret;
2363 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2365 IShellLinkW *sl;
2366 IPersistFile *pf;
2367 HRESULT r;
2368 WCHAR fullname[MAX_PATH];
2369 DWORD len;
2371 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2373 if( !linkname[0] )
2375 WINE_ERR("link name missing\n");
2376 return 1;
2379 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2380 if (len==0 || len>MAX_PATH)
2382 WINE_ERR("couldn't get full path of link file\n");
2383 return 1;
2386 r = CoInitialize( NULL );
2387 if( FAILED( r ) )
2389 WINE_ERR("CoInitialize failed\n");
2390 return 1;
2393 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2394 &IID_IShellLinkW, (LPVOID *) &sl );
2395 if( FAILED( r ) )
2397 WINE_ERR("No IID_IShellLink\n");
2398 return 1;
2401 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2402 if( FAILED( r ) )
2404 WINE_ERR("No IID_IPersistFile\n");
2405 return 1;
2408 r = IPersistFile_Load( pf, fullname, STGM_READ );
2409 if( SUCCEEDED( r ) )
2411 /* If something fails (eg. Couldn't extract icon)
2412 * wait for parent process and try again
2414 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2416 WaitForParentProcess();
2417 InvokeShellLinker( sl, fullname, FALSE );
2420 else
2422 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2425 IPersistFile_Release( pf );
2426 IShellLinkW_Release( sl );
2428 CoUninitialize();
2430 return !r;
2433 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2435 IUniformResourceLocatorW *url;
2436 IPersistFile *pf;
2437 HRESULT r;
2438 WCHAR fullname[MAX_PATH];
2439 DWORD len;
2441 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2443 if( !urlname[0] )
2445 WINE_ERR("URL name missing\n");
2446 return 1;
2449 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2450 if (len==0 || len>MAX_PATH)
2452 WINE_ERR("couldn't get full path of URL file\n");
2453 return 1;
2456 r = CoInitialize( NULL );
2457 if( FAILED( r ) )
2459 WINE_ERR("CoInitialize failed\n");
2460 return 1;
2463 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2464 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2465 if( FAILED( r ) )
2467 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2468 return 1;
2471 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2472 if( FAILED( r ) )
2474 WINE_ERR("No IID_IPersistFile\n");
2475 return 1;
2477 r = IPersistFile_Load( pf, fullname, STGM_READ );
2478 if( SUCCEEDED( r ) )
2480 /* If something fails (eg. Couldn't extract icon)
2481 * wait for parent process and try again
2483 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2485 WaitForParentProcess();
2486 InvokeShellLinkerForURL( url, fullname, FALSE );
2490 IPersistFile_Release( pf );
2491 url->lpVtbl->Release( url );
2493 CoUninitialize();
2495 return !r;
2498 static void RefreshFileTypeAssociations(void)
2500 HANDLE hSem = NULL;
2501 char *mime_dir = NULL;
2502 char *packages_dir = NULL;
2503 char *applications_dir = NULL;
2504 BOOL hasChanged;
2506 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2507 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2509 WINE_ERR("failed wait for semaphore\n");
2510 CloseHandle(hSem);
2511 hSem = NULL;
2512 goto end;
2515 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2516 if (mime_dir == NULL)
2518 WINE_ERR("out of memory\n");
2519 goto end;
2521 create_directories(mime_dir);
2523 packages_dir = heap_printf("%s/packages", mime_dir);
2524 if (packages_dir == NULL)
2526 WINE_ERR("out of memory\n");
2527 goto end;
2529 create_directories(packages_dir);
2531 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2532 if (applications_dir == NULL)
2534 WINE_ERR("out of memory\n");
2535 goto end;
2537 create_directories(applications_dir);
2539 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2540 hasChanged |= cleanup_associations();
2541 if (hasChanged)
2543 const char *argv[3];
2545 argv[0] = "update-mime-database";
2546 argv[1] = mime_dir;
2547 argv[2] = NULL;
2548 spawnvp( _P_NOWAIT, argv[0], argv );
2550 argv[0] = "update-desktop-database";
2551 argv[1] = applications_dir;
2552 spawnvp( _P_NOWAIT, argv[0], argv );
2555 end:
2556 if (hSem)
2558 ReleaseSemaphore(hSem, 1, NULL);
2559 CloseHandle(hSem);
2561 HeapFree(GetProcessHeap(), 0, mime_dir);
2562 HeapFree(GetProcessHeap(), 0, packages_dir);
2563 HeapFree(GetProcessHeap(), 0, applications_dir);
2566 static void cleanup_menus(void)
2568 HKEY hkey;
2570 hkey = open_menus_reg_key();
2571 if (hkey)
2573 int i;
2574 LSTATUS lret = ERROR_SUCCESS;
2575 for (i = 0; lret == ERROR_SUCCESS; )
2577 char *value = NULL;
2578 char *data = NULL;
2579 DWORD valueSize = 4096;
2580 DWORD dataSize = 4096;
2581 while (1)
2583 lret = ERROR_OUTOFMEMORY;
2584 value = HeapAlloc(GetProcessHeap(), 0, valueSize);
2585 if (value == NULL)
2586 break;
2587 data = HeapAlloc(GetProcessHeap(), 0, dataSize);
2588 if (data == NULL)
2589 break;
2590 lret = RegEnumValueA(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2591 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2592 break;
2593 valueSize *= 2;
2594 dataSize *= 2;
2595 HeapFree(GetProcessHeap(), 0, value);
2596 HeapFree(GetProcessHeap(), 0, data);
2597 value = data = NULL;
2599 if (lret == ERROR_SUCCESS)
2601 struct stat filestats;
2602 if (stat(data, &filestats) < 0 && errno == ENOENT)
2604 WINE_TRACE("removing menu related file %s\n", value);
2605 remove(value);
2606 RegDeleteValueA(hkey, value);
2608 else
2609 i++;
2611 else if (lret != ERROR_NO_MORE_ITEMS)
2612 WINE_WARN("error %d reading registry\n", lret);
2613 HeapFree(GetProcessHeap(), 0, value);
2614 HeapFree(GetProcessHeap(), 0, data);
2616 RegCloseKey(hkey);
2618 else
2619 WINE_ERR("error opening registry key, menu cleanup failed\n");
2622 static CHAR *next_token( LPSTR *p )
2624 LPSTR token = NULL, t = *p;
2626 if( !t )
2627 return NULL;
2629 while( t && !token )
2631 switch( *t )
2633 case ' ':
2634 t++;
2635 continue;
2636 case '"':
2637 /* unquote the token */
2638 token = ++t;
2639 t = strchr( token, '"' );
2640 if( t )
2641 *t++ = 0;
2642 break;
2643 case 0:
2644 t = NULL;
2645 break;
2646 default:
2647 token = t;
2648 t = strchr( token, ' ' );
2649 if( t )
2650 *t++ = 0;
2651 break;
2654 *p = t;
2655 return token;
2658 static BOOL init_xdg(void)
2660 WCHAR shellDesktopPath[MAX_PATH];
2661 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2662 if (SUCCEEDED(hr))
2663 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2664 if (xdg_desktop_dir == NULL)
2666 WINE_ERR("error looking up the desktop directory\n");
2667 return FALSE;
2670 if (getenv("XDG_CONFIG_HOME"))
2671 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2672 else
2673 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2674 if (xdg_config_dir)
2676 create_directories(xdg_config_dir);
2677 if (getenv("XDG_DATA_HOME"))
2678 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
2679 else
2680 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2681 if (xdg_data_dir)
2683 char *buffer;
2684 create_directories(xdg_data_dir);
2685 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2686 if (buffer)
2688 mkdir(buffer, 0777);
2689 HeapFree(GetProcessHeap(), 0, buffer);
2691 return TRUE;
2693 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2695 WINE_ERR("out of memory\n");
2696 return FALSE;
2699 /***********************************************************************
2701 * WinMain
2703 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
2705 LPSTR token = NULL, p;
2706 BOOL bWait = FALSE;
2707 BOOL bURL = FALSE;
2708 int ret = 0;
2710 if (!init_xdg())
2711 return 1;
2713 for( p = cmdline; p && *p; )
2715 token = next_token( &p );
2716 if( !token )
2717 break;
2718 if( !lstrcmpA( token, "-a" ) )
2720 RefreshFileTypeAssociations();
2721 continue;
2723 if( !lstrcmpA( token, "-r" ) )
2725 cleanup_menus();
2726 continue;
2728 if( !lstrcmpA( token, "-w" ) )
2729 bWait = TRUE;
2730 else if ( !lstrcmpA( token, "-u" ) )
2731 bURL = TRUE;
2732 else if( token[0] == '-' )
2734 WINE_ERR( "unknown option %s\n",token);
2736 else
2738 WCHAR link[MAX_PATH];
2739 BOOL bRet;
2741 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2742 if (bURL)
2743 bRet = Process_URL( link, bWait );
2744 else
2745 bRet = Process_Link( link, bWait );
2746 if (!bRet)
2748 WINE_ERR( "failed to build menu item for %s\n",token);
2749 ret = 1;
2754 return ret;