mapi32/tests: Centralize utility function pointer initialization.
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blobe14fe813ddc5953821c3c2e1c9563987ac1e0d3f
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 if (!buffer) return NULL;
728 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
729 if (!ret) ret = buffer;
730 return ret;
733 static void write_xml_text(FILE *file, const char *text)
735 int i;
736 for (i = 0; text[i]; i++)
738 if (text[i] == '&')
739 fputs("&amp;", file);
740 else if (text[i] == '<')
741 fputs("&lt;", file);
742 else if (text[i] == '>')
743 fputs("&gt;", file);
744 else if (text[i] == '\'')
745 fputs("&apos;", file);
746 else if (text[i] == '"')
747 fputs("&quot;", file);
748 else
749 fputc(text[i], file);
753 static BOOL create_directories(char *directory)
755 BOOL ret = TRUE;
756 int i;
758 for (i = 0; directory[i]; i++)
760 if (i > 0 && directory[i] == '/')
762 directory[i] = 0;
763 mkdir(directory, 0777);
764 directory[i] = '/';
767 if (mkdir(directory, 0777) && errno != EEXIST)
768 ret = FALSE;
770 return ret;
773 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
774 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
776 unsigned short crc;
777 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
778 char* s;
779 int n;
781 /* Where should we save the icon? */
782 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
783 iconsdir = heap_printf("%s/icons", xdg_data_dir);
784 if (iconsdir)
786 if (mkdir(iconsdir, 0777) && errno != EEXIST)
788 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
789 goto end;
792 else
794 WINE_TRACE("no icon created\n");
795 return NULL;
798 /* Determine the icon base name */
799 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
800 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
801 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
802 s=ico_name=ico_path;
803 while (*s!='\0') {
804 if (*s=='/' || *s=='\\') {
805 *s='\\';
806 ico_name=s;
807 } else {
808 *s=tolower(*s);
810 s++;
812 if (*ico_name=='\\') *ico_name++='\0';
813 s=strrchr(ico_name,'.');
814 if (s) *s='\0';
816 /* Compute the source-path hash */
817 crc=crc16(ico_path);
819 /* Try to treat the source file as an exe */
820 if (destFilename)
821 xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
822 else
823 xpm_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
824 if (xpm_path == NULL)
826 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
827 return NULL;
830 if (ExtractFromEXEDLL( path, index, xpm_path ))
831 goto end;
833 /* Must be something else, ignore the index in that case */
834 if (destFilename)
835 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
836 else
837 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
838 if (ExtractFromICO( path, xpm_path))
839 goto end;
840 if (!bWait)
842 if (destFilename)
843 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
844 else
845 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
846 if (create_default_icon( xpm_path, ico_path ))
847 goto end;
850 HeapFree( GetProcessHeap(), 0, xpm_path );
851 xpm_path=NULL;
853 end:
854 HeapFree(GetProcessHeap(), 0, iconsdir);
855 HeapFree(GetProcessHeap(), 0, ico_path);
856 return xpm_path;
859 static HKEY open_menus_reg_key(void)
861 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
862 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
863 HKEY assocKey;
864 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
865 return assocKey;
866 return NULL;
869 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
870 const char *path, const char *args, const char *descr,
871 const char *workdir, const char *icon)
873 FILE *file;
875 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
876 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
877 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
879 file = fopen(location, "w");
880 if (file == NULL)
881 return FALSE;
883 fprintf(file, "[Desktop Entry]\n");
884 fprintf(file, "Name=%s\n", linkname);
885 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
886 wine_get_config_dir(), path, args);
887 fprintf(file, "Type=Application\n");
888 fprintf(file, "StartupNotify=true\n");
889 if (descr && lstrlenA(descr))
890 fprintf(file, "Comment=%s\n", descr);
891 if (workdir && lstrlenA(workdir))
892 fprintf(file, "Path=%s\n", workdir);
893 if (icon && lstrlenA(icon))
894 fprintf(file, "Icon=%s\n", icon);
896 fclose(file);
898 if (unix_link)
900 HKEY hkey = open_menus_reg_key();
901 if (hkey)
903 RegSetValueExA(hkey, location, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
904 RegCloseKey(hkey);
906 else
907 return FALSE;
910 return TRUE;
913 static BOOL write_directory_entry(const char *directory, const char *location)
915 FILE *file;
917 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
919 file = fopen(location, "w");
920 if (file == NULL)
921 return FALSE;
923 fprintf(file, "[Desktop Entry]\n");
924 fprintf(file, "Type=Directory\n");
925 if (strcmp(directory, "wine") == 0)
927 fprintf(file, "Name=Wine\n");
928 fprintf(file, "Icon=wine\n");
930 else
932 fprintf(file, "Name=%s\n", directory);
933 fprintf(file, "Icon=folder\n");
936 fclose(file);
937 return TRUE;
940 static BOOL write_menu_file(const char *unix_link, const char *filename)
942 char *tempfilename;
943 FILE *tempfile = NULL;
944 char *lastEntry;
945 char *name = NULL;
946 char *menuPath = NULL;
947 int i;
948 int count = 0;
949 BOOL ret = FALSE;
951 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
953 while (1)
955 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
956 if (tempfilename)
958 int tempfd = mkstemps(tempfilename, 0);
959 if (tempfd >= 0)
961 tempfile = fdopen(tempfd, "w");
962 if (tempfile)
963 break;
964 close(tempfd);
965 goto end;
967 else if (errno == EEXIST)
969 HeapFree(GetProcessHeap(), 0, tempfilename);
970 continue;
972 HeapFree(GetProcessHeap(), 0, tempfilename);
974 return FALSE;
977 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
978 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
979 fprintf(tempfile, "<Menu>\n");
980 fprintf(tempfile, " <Name>Applications</Name>\n");
982 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
983 if (name == NULL) goto end;
984 lastEntry = name;
985 for (i = 0; filename[i]; i++)
987 name[i] = filename[i];
988 if (filename[i] == '/')
990 char *dir_file_name;
991 struct stat st;
992 name[i] = 0;
993 fprintf(tempfile, " <Menu>\n");
994 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
995 write_xml_text(tempfile, name);
996 fprintf(tempfile, "</Name>\n");
997 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
998 write_xml_text(tempfile, name);
999 fprintf(tempfile, ".directory</Directory>\n");
1000 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1001 xdg_data_dir, count ? "" : "wine-", name);
1002 if (dir_file_name)
1004 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1005 write_directory_entry(lastEntry, dir_file_name);
1006 HeapFree(GetProcessHeap(), 0, dir_file_name);
1008 name[i] = '-';
1009 lastEntry = &name[i+1];
1010 ++count;
1013 name[i] = 0;
1015 fprintf(tempfile, " <Include>\n");
1016 fprintf(tempfile, " <Filename>");
1017 write_xml_text(tempfile, name);
1018 fprintf(tempfile, "</Filename>\n");
1019 fprintf(tempfile, " </Include>\n");
1020 for (i = 0; i < count; i++)
1021 fprintf(tempfile, " </Menu>\n");
1022 fprintf(tempfile, "</Menu>\n");
1024 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1025 if (menuPath == NULL) goto end;
1026 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1027 ret = TRUE;
1029 end:
1030 if (tempfile)
1031 fclose(tempfile);
1032 if (ret)
1033 ret = (rename(tempfilename, menuPath) == 0);
1034 if (!ret && tempfilename)
1035 remove(tempfilename);
1036 HeapFree(GetProcessHeap(), 0, tempfilename);
1037 if (ret)
1039 HKEY hkey = open_menus_reg_key();
1040 if (hkey)
1042 RegSetValueExA(hkey, menuPath, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
1043 RegCloseKey(hkey);
1046 HeapFree(GetProcessHeap(), 0, name);
1047 HeapFree(GetProcessHeap(), 0, menuPath);
1048 return ret;
1051 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1052 const char *descr, const char *workdir, const char *icon)
1054 const char *linkname;
1055 char *desktopPath = NULL;
1056 char *desktopDir;
1057 char *filename = NULL;
1058 BOOL ret = TRUE;
1060 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1061 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1062 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1064 linkname = strrchr(link, '/');
1065 if (linkname == NULL)
1066 linkname = link;
1067 else
1068 ++linkname;
1070 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1071 if (!desktopPath)
1073 WINE_WARN("out of memory creating menu entry\n");
1074 ret = FALSE;
1075 goto end;
1077 desktopDir = strrchr(desktopPath, '/');
1078 *desktopDir = 0;
1079 if (!create_directories(desktopPath))
1081 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1082 ret = FALSE;
1083 goto end;
1085 *desktopDir = '/';
1086 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1088 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1089 ret = FALSE;
1090 goto end;
1093 filename = heap_printf("wine/%s.desktop", link);
1094 if (!filename || !write_menu_file(unix_link, filename))
1096 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1097 ret = FALSE;
1100 end:
1101 HeapFree(GetProcessHeap(), 0, desktopPath);
1102 HeapFree(GetProcessHeap(), 0, filename);
1103 return ret;
1106 /* This escapes \ in filenames */
1107 static LPSTR escape(LPCWSTR arg)
1109 LPSTR narg, x;
1110 LPCWSTR esc;
1111 int len = 0, n;
1113 esc = arg;
1114 while((esc = strchrW(esc, '\\')))
1116 esc++;
1117 len++;
1120 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1121 narg = HeapAlloc(GetProcessHeap(), 0, len);
1123 x = narg;
1124 while (*arg)
1126 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1127 x += n;
1128 len -= n;
1129 if (*arg == '\\')
1130 *x++='\\'; /* escape \ */
1131 arg++;
1133 *x = 0;
1134 return narg;
1137 /* Return a heap-allocated copy of the unix format difference between the two
1138 * Windows-format paths.
1139 * locn is the owning location
1140 * link is within locn
1142 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1144 char *unix_locn, *unix_link;
1145 char *relative = NULL;
1147 unix_locn = wine_get_unix_file_name(locn);
1148 unix_link = wine_get_unix_file_name(link);
1149 if (unix_locn && unix_link)
1151 size_t len_unix_locn, len_unix_link;
1152 len_unix_locn = strlen (unix_locn);
1153 len_unix_link = strlen (unix_link);
1154 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1156 size_t len_rel;
1157 char *p = strrchr (unix_link + len_unix_locn, '/');
1158 p = strrchr (p, '.');
1159 if (p)
1161 *p = '\0';
1162 len_unix_link = p - unix_link;
1164 len_rel = len_unix_link - len_unix_locn;
1165 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1166 if (relative)
1168 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1172 if (!relative)
1173 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1174 HeapFree(GetProcessHeap(), 0, unix_locn);
1175 HeapFree(GetProcessHeap(), 0, unix_link);
1176 return relative;
1179 /***********************************************************************
1181 * GetLinkLocation
1183 * returns TRUE if successful
1184 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1185 * *relative will contain the address of a heap-allocated copy of the portion
1186 * of the filename that is within the specified location, in unix form
1188 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1190 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1191 DWORD len, i, r, filelen;
1192 const DWORD locations[] = {
1193 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1194 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1195 CSIDL_COMMON_STARTMENU };
1197 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1198 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1199 if (filelen==0 || filelen>MAX_PATH)
1200 return FALSE;
1202 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1204 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1205 * expand or our hardcoded list won't match.
1207 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1208 if (filelen==0 || filelen>MAX_PATH)
1209 return FALSE;
1211 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1213 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1215 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1216 continue;
1218 len = lstrlenW(buffer);
1219 if (len >= MAX_PATH)
1220 continue; /* We've just trashed memory! Hopefully we are OK */
1222 if (len > filelen || filename[len]!='\\')
1223 continue;
1224 /* do a lstrcmpinW */
1225 filename[len] = 0;
1226 r = lstrcmpiW( filename, buffer );
1227 filename[len] = '\\';
1228 if ( r )
1229 continue;
1231 /* return the remainder of the string and link type */
1232 *loc = locations[i];
1233 *relative = relative_path (filename, buffer);
1234 return (*relative != NULL);
1237 return FALSE;
1240 /* gets the target path directly or through MSI */
1241 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1242 LPWSTR szArgs, DWORD argsSize)
1244 IShellLinkDataList *dl = NULL;
1245 EXP_DARWIN_LINK *dar = NULL;
1246 HRESULT hr;
1248 szPath[0] = 0;
1249 szArgs[0] = 0;
1251 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1252 if (hr == S_OK && szPath[0])
1254 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1255 return hr;
1258 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1259 if (FAILED(hr))
1260 return hr;
1262 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1263 if (SUCCEEDED(hr))
1265 WCHAR* szCmdline;
1266 DWORD cmdSize;
1268 cmdSize=0;
1269 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1270 if (hr == ERROR_SUCCESS)
1272 cmdSize++;
1273 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1274 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1275 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1276 if (hr == ERROR_SUCCESS)
1278 WCHAR *s, *d;
1279 int bcount, in_quotes;
1281 /* Extract the application path */
1282 bcount=0;
1283 in_quotes=0;
1284 s=szCmdline;
1285 d=szPath;
1286 while (*s)
1288 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1290 /* skip the remaining spaces */
1291 do {
1292 s++;
1293 } while (*s==0x0009 || *s==0x0020);
1294 break;
1296 else if (*s==0x005c)
1298 /* '\\' */
1299 *d++=*s++;
1300 bcount++;
1302 else if (*s==0x0022)
1304 /* '"' */
1305 if ((bcount & 1)==0)
1307 /* Preceded by an even number of '\', this is
1308 * half that number of '\', plus a quote which
1309 * we erase.
1311 d-=bcount/2;
1312 in_quotes=!in_quotes;
1313 s++;
1315 else
1317 /* Preceded by an odd number of '\', this is
1318 * half that number of '\' followed by a '"'
1320 d=d-bcount/2-1;
1321 *d++='"';
1322 s++;
1324 bcount=0;
1326 else
1328 /* a regular character */
1329 *d++=*s++;
1330 bcount=0;
1332 if ((d-szPath) == pathSize)
1334 /* Keep processing the path till we get to the
1335 * arguments, but 'stand still'
1337 d--;
1340 /* Close the application path */
1341 *d=0;
1343 lstrcpynW(szArgs, s, argsSize);
1345 HeapFree( GetProcessHeap(), 0, szCmdline );
1347 LocalFree( dar );
1350 IShellLinkDataList_Release( dl );
1351 return hr;
1354 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1356 HRESULT hr;
1357 WCHAR *value = NULL;
1358 DWORD size = 0;
1359 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1360 if (SUCCEEDED(hr))
1362 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1363 if (value)
1365 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1366 if (FAILED(hr))
1368 HeapFree(GetProcessHeap(), 0, value);
1369 value = NULL;
1373 return value;
1376 static char* wchars_to_utf8_chars(LPCWSTR string)
1378 char *ret;
1379 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
1380 ret = HeapAlloc(GetProcessHeap(), 0, size);
1381 if (ret)
1382 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
1383 return ret;
1386 static char *slashes_to_minuses(const char *string)
1388 int i;
1389 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1390 if (ret)
1392 for (i = 0; string[i]; i++)
1394 if (string[i] == '/')
1395 ret[i] = '-';
1396 else
1397 ret[i] = string[i];
1399 ret[i] = 0;
1400 return ret;
1402 return NULL;
1405 static BOOL next_line(FILE *file, char **line, int *size)
1407 int pos = 0;
1408 char *cr;
1409 if (*line == NULL)
1411 *size = 4096;
1412 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1414 while (*line != NULL)
1416 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1418 HeapFree(GetProcessHeap(), 0, *line);
1419 *line = NULL;
1420 if (feof(file))
1421 return TRUE;
1422 return FALSE;
1424 pos = strlen(*line);
1425 cr = strchr(*line, '\n');
1426 if (cr == NULL)
1428 char *line2;
1429 (*size) *= 2;
1430 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1431 if (line2)
1432 *line = line2;
1433 else
1435 HeapFree(GetProcessHeap(), 0, *line);
1436 *line = NULL;
1439 else
1441 *cr = 0;
1442 return TRUE;
1445 return FALSE;
1448 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1450 char *globs_filename = NULL;
1451 BOOL ret = TRUE;
1452 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1453 if (globs_filename)
1455 FILE *globs_file = fopen(globs_filename, "r");
1456 if (globs_file) /* doesn't have to exist */
1458 char *line = NULL;
1459 int size = 0;
1460 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1462 char *pos;
1463 struct xdg_mime_type *mime_type_entry = NULL;
1464 if (line[0] != '#' && (pos = strchr(line, ':')))
1466 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1467 if (mime_type_entry)
1469 *pos = 0;
1470 mime_type_entry->mimeType = strdupA(line);
1471 mime_type_entry->glob = strdupA(pos + 1);
1472 if (mime_type_entry->mimeType && mime_type_entry->glob)
1473 list_add_tail(mime_types, &mime_type_entry->entry);
1474 else
1476 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1477 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1478 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1479 ret = FALSE;
1482 else
1483 ret = FALSE;
1486 HeapFree(GetProcessHeap(), 0, line);
1487 fclose(globs_file);
1489 HeapFree(GetProcessHeap(), 0, globs_filename);
1491 else
1492 ret = FALSE;
1493 return ret;
1496 static void free_native_mime_types(struct list *native_mime_types)
1498 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1500 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1502 list_remove(&mime_type_entry->entry);
1503 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1504 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1505 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1507 HeapFree(GetProcessHeap(), 0, native_mime_types);
1510 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1512 char *xdg_data_dirs;
1513 BOOL ret;
1515 *mime_types = NULL;
1517 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1518 if (xdg_data_dirs == NULL)
1519 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1520 else
1521 xdg_data_dirs = strdupA(xdg_data_dirs);
1523 if (xdg_data_dirs)
1525 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1526 if (*mime_types)
1528 const char *begin;
1529 char *end;
1531 list_init(*mime_types);
1532 ret = add_mimes(xdg_data_home, *mime_types);
1533 if (ret)
1535 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1537 *end = '\0';
1538 ret = add_mimes(begin, *mime_types);
1539 *end = ':';
1540 if (!ret)
1541 break;
1543 if (ret)
1544 ret = add_mimes(begin, *mime_types);
1547 else
1548 ret = FALSE;
1549 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1551 else
1552 ret = FALSE;
1553 if (!ret && *mime_types)
1555 free_native_mime_types(*mime_types);
1556 *mime_types = NULL;
1558 return ret;
1561 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1562 char **match)
1564 #ifdef HAVE_FNMATCH
1565 struct xdg_mime_type *mime_type_entry;
1566 int matchLength = 0;
1568 *match = NULL;
1570 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1572 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1574 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1576 *match = mime_type_entry->mimeType;
1577 matchLength = strlen(mime_type_entry->glob);
1582 if (*match != NULL)
1584 *match = strdupA(*match);
1585 if (*match == NULL)
1586 return FALSE;
1588 #else
1589 *match = NULL;
1590 #endif
1591 return TRUE;
1594 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1595 const char *extensionA,
1596 LPCWSTR extensionW,
1597 char **mime_type)
1599 WCHAR *lower_extensionW;
1600 INT len;
1601 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1602 if (ret == FALSE || *mime_type != NULL)
1603 return ret;
1604 len = strlenW(extensionW);
1605 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1606 if (lower_extensionW)
1608 char *lower_extensionA;
1609 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1610 strlwrW(lower_extensionW);
1611 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1612 if (lower_extensionA)
1614 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1615 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1617 else
1619 ret = FALSE;
1620 WINE_FIXME("out of memory\n");
1622 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1624 else
1626 ret = FALSE;
1627 WINE_FIXME("out of memory\n");
1629 return ret;
1632 static CHAR* reg_get_valA(HKEY key, LPCSTR subkey, LPCSTR name)
1634 DWORD size;
1635 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1637 CHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1638 if (ret)
1640 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1641 return ret;
1643 HeapFree(GetProcessHeap(), 0, ret);
1645 return NULL;
1648 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1650 DWORD size;
1651 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1653 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1654 if (ret)
1656 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1657 return ret;
1659 HeapFree(GetProcessHeap(), 0, ret);
1661 return NULL;
1664 static HKEY open_associations_reg_key(void)
1666 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1667 '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};
1668 HKEY assocKey;
1669 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1670 return assocKey;
1671 return NULL;
1674 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1676 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1677 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1678 HKEY assocKey;
1679 BOOL ret;
1681 if ((assocKey = open_associations_reg_key()))
1683 CHAR *valueA;
1684 WCHAR *value;
1686 ret = FALSE;
1688 valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1689 if (!valueA || lstrcmpA(valueA, mimeType))
1690 ret = TRUE;
1691 HeapFree(GetProcessHeap(), 0, valueA);
1693 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1694 if (!value || strcmpW(value, progId))
1695 ret = TRUE;
1696 HeapFree(GetProcessHeap(), 0, value);
1698 valueA = reg_get_valA(assocKey, extensionA, "AppName");
1699 if (!valueA || lstrcmpA(valueA, appName))
1700 ret = TRUE;
1701 HeapFree(GetProcessHeap(), 0, valueA);
1703 value = reg_get_valW(assocKey, extensionW, DocNameW);
1704 if (docName && (!value || strcmpW(value, docName)))
1705 ret = TRUE;
1706 HeapFree(GetProcessHeap(), 0, value);
1708 RegCloseKey(assocKey);
1710 else
1712 WINE_ERR("error opening associations registry key\n");
1713 ret = FALSE;
1715 return ret;
1718 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1720 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1721 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1722 HKEY assocKey;
1724 if ((assocKey = open_associations_reg_key()))
1726 HKEY subkey;
1727 if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1729 RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (BYTE*) mimeType, lstrlenA(mimeType) + 1);
1730 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1731 RegSetValueExA(subkey, "AppName", 0, REG_SZ, (BYTE*) appName, lstrlenA(appName) + 1);
1732 if (docName)
1733 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1734 RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1735 RegCloseKey(subkey);
1737 else
1738 WINE_ERR("could not create extension subkey\n");
1739 RegCloseKey(assocKey);
1741 else
1742 WINE_ERR("could not open file associations key\n");
1745 static BOOL cleanup_associations(void)
1747 static const WCHAR openW[] = {'o','p','e','n',0};
1748 HKEY assocKey;
1749 BOOL hasChanged = FALSE;
1750 if ((assocKey = open_associations_reg_key()))
1752 int i;
1753 BOOL done = FALSE;
1754 for (i = 0; !done; i++)
1756 WCHAR *extensionW = NULL;
1757 char *extensionA = NULL;
1758 DWORD size = 1024;
1759 LSTATUS ret;
1763 HeapFree(GetProcessHeap(), 0, extensionW);
1764 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1765 if (extensionW == NULL)
1767 WINE_ERR("out of memory\n");
1768 ret = ERROR_OUTOFMEMORY;
1769 break;
1771 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1772 size *= 2;
1773 } while (ret == ERROR_MORE_DATA);
1775 if (ret == ERROR_SUCCESS)
1777 WCHAR *command;
1778 extensionA = wchars_to_utf8_chars(extensionW);
1779 if (extensionA == NULL)
1781 WINE_ERR("out of memory\n");
1782 done = TRUE;
1783 goto end;
1785 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1786 if (command == NULL)
1788 char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1789 if (desktopFile)
1791 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1792 remove(desktopFile);
1794 RegDeleteKeyW(assocKey, extensionW);
1795 hasChanged = TRUE;
1796 HeapFree(GetProcessHeap(), 0, desktopFile);
1798 HeapFree(GetProcessHeap(), 0, command);
1800 else
1802 if (ret != ERROR_NO_MORE_ITEMS)
1803 WINE_ERR("error %d while reading registry\n", ret);
1804 done = TRUE;
1806 end:
1807 HeapFree(GetProcessHeap(), 0, extensionA);
1808 HeapFree(GetProcessHeap(), 0, extensionW);
1810 RegCloseKey(assocKey);
1812 else
1813 WINE_ERR("could not open file associations key\n");
1814 return hasChanged;
1817 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1818 const char *mime_type, const char *comment)
1820 BOOL ret = FALSE;
1821 char *filename;
1823 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1824 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1826 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1827 if (filename)
1829 FILE *packageFile = fopen(filename, "w");
1830 if (packageFile)
1832 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1833 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1834 fprintf(packageFile, " <mime-type type=\"");
1835 write_xml_text(packageFile, mime_type);
1836 fprintf(packageFile, "\">\n");
1837 fprintf(packageFile, " <glob pattern=\"*");
1838 write_xml_text(packageFile, dot_extension);
1839 fprintf(packageFile, "\"/>\n");
1840 if (comment)
1842 fprintf(packageFile, " <comment>");
1843 write_xml_text(packageFile, comment);
1844 fprintf(packageFile, "</comment>\n");
1846 fprintf(packageFile, " </mime-type>\n");
1847 fprintf(packageFile, "</mime-info>\n");
1848 ret = TRUE;
1849 fclose(packageFile);
1851 else
1852 WINE_ERR("error writing file %s\n", filename);
1853 HeapFree(GetProcessHeap(), 0, filename);
1855 else
1856 WINE_ERR("out of memory\n");
1857 return ret;
1860 static BOOL is_extension_blacklisted(LPCWSTR extension)
1862 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1863 static const WCHAR comW[] = {'.','c','o','m',0};
1864 static const WCHAR exeW[] = {'.','e','x','e',0};
1865 static const WCHAR msiW[] = {'.','m','s','i',0};
1867 if (!strcmpiW(extension, comW) ||
1868 !strcmpiW(extension, exeW) ||
1869 !strcmpiW(extension, msiW))
1870 return TRUE;
1871 return FALSE;
1874 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1875 const char *friendlyAppName, const char *mimeType,
1876 const char *progId)
1878 BOOL ret = FALSE;
1879 FILE *desktop;
1881 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1882 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1883 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1885 desktop = fopen(desktopPath, "w");
1886 if (desktop)
1888 fprintf(desktop, "[Desktop Entry]\n");
1889 fprintf(desktop, "Type=Application\n");
1890 fprintf(desktop, "Name=%s\n", friendlyAppName);
1891 fprintf(desktop, "MimeType=%s\n", mimeType);
1892 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1893 fprintf(desktop, "NoDisplay=true\n");
1894 fprintf(desktop, "StartupNotify=true\n");
1895 ret = TRUE;
1896 fclose(desktop);
1898 else
1899 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1900 return ret;
1903 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1905 static const WCHAR openW[] = {'o','p','e','n',0};
1906 struct list *nativeMimeTypes = NULL;
1907 LSTATUS ret = 0;
1908 int i;
1909 BOOL hasChanged = FALSE;
1911 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1913 WINE_ERR("could not build native MIME types\n");
1914 return FALSE;
1917 for (i = 0; ; i++)
1919 WCHAR *extensionW = NULL;
1920 DWORD size = 1024;
1924 HeapFree(GetProcessHeap(), 0, extensionW);
1925 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1926 if (extensionW == NULL)
1928 WINE_ERR("out of memory\n");
1929 ret = ERROR_OUTOFMEMORY;
1930 break;
1932 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1933 size *= 2;
1934 } while (ret == ERROR_MORE_DATA);
1936 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1938 char *extensionA = NULL;
1939 WCHAR *commandW = NULL;
1940 WCHAR *friendlyDocNameW = NULL;
1941 char *friendlyDocNameA = NULL;
1942 WCHAR *iconW = NULL;
1943 char *iconA = NULL;
1944 WCHAR *contentTypeW = NULL;
1945 char *mimeTypeA = NULL;
1946 WCHAR *friendlyAppNameW = NULL;
1947 char *friendlyAppNameA = NULL;
1948 WCHAR *progIdW = NULL;
1949 char *progIdA = NULL;
1951 extensionA = wchars_to_utf8_chars(extensionW);
1952 if (extensionA == NULL)
1954 WINE_ERR("out of memory\n");
1955 goto end;
1958 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
1959 if (friendlyDocNameW)
1961 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
1962 if (friendlyDocNameA == NULL)
1964 WINE_ERR("out of memory\n");
1965 goto end;
1969 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
1971 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
1973 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
1974 goto end;
1976 if (mimeTypeA == NULL)
1978 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
1979 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
1980 else
1981 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
1983 if (mimeTypeA != NULL)
1985 /* Gnome seems to ignore the <icon> tag in MIME packages,
1986 * and the default name is more intuitive anyway.
1988 if (iconW)
1990 char *flattened_mime = slashes_to_minuses(mimeTypeA);
1991 if (flattened_mime)
1993 int index = 0;
1994 WCHAR *comma = strrchrW(iconW, ',');
1995 if (comma)
1997 *comma = 0;
1998 index = atoiW(comma + 1);
2000 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2001 HeapFree(GetProcessHeap(), 0, flattened_mime);
2005 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2006 hasChanged = TRUE;
2008 else
2010 WINE_FIXME("out of memory\n");
2011 goto end;
2015 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2016 if (commandW == NULL)
2017 /* no command => no application is associated */
2018 goto end;
2020 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2021 if (friendlyAppNameW)
2023 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2024 if (friendlyAppNameA == NULL)
2026 WINE_ERR("out of memory\n");
2027 goto end;
2030 else
2032 friendlyAppNameA = heap_printf("A Wine application");
2033 if (friendlyAppNameA == NULL)
2035 WINE_ERR("out of memory\n");
2036 goto end;
2040 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2041 if (progIdW)
2043 progIdA = wchars_to_utf8_chars(progIdW);
2044 if (progIdA == NULL)
2046 WINE_ERR("out of memory\n");
2047 goto end;
2050 else
2051 goto end; /* no progID => not a file type association */
2053 if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2055 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2056 if (desktopPath)
2058 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2060 hasChanged = TRUE;
2061 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2063 HeapFree(GetProcessHeap(), 0, desktopPath);
2067 end:
2068 HeapFree(GetProcessHeap(), 0, extensionA);
2069 HeapFree(GetProcessHeap(), 0, commandW);
2070 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2071 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2072 HeapFree(GetProcessHeap(), 0, iconW);
2073 HeapFree(GetProcessHeap(), 0, iconA);
2074 HeapFree(GetProcessHeap(), 0, contentTypeW);
2075 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2076 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2077 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2078 HeapFree(GetProcessHeap(), 0, progIdW);
2079 HeapFree(GetProcessHeap(), 0, progIdA);
2081 HeapFree(GetProcessHeap(), 0, extensionW);
2082 if (ret != ERROR_SUCCESS)
2083 break;
2086 free_native_mime_types(nativeMimeTypes);
2087 return hasChanged;
2090 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2092 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2093 '\\','s','t','a','r','t','.','e','x','e',0};
2094 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2095 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
2096 WCHAR szTmp[INFOTIPSIZE];
2097 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2098 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2099 int iIconId = 0, r = -1;
2100 DWORD csidl = -1;
2101 HANDLE hsem = NULL;
2102 char *unix_link = NULL;
2104 if ( !link )
2106 WINE_ERR("Link name is null\n");
2107 return FALSE;
2110 if( !GetLinkLocation( link, &csidl, &link_name ) )
2112 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2113 return TRUE;
2115 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2117 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2118 return TRUE;
2120 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2122 szTmp[0] = 0;
2123 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2124 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2125 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2127 szTmp[0] = 0;
2128 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2129 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2130 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2132 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
2133 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2134 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2136 szTmp[0] = 0;
2137 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2138 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2139 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2141 if( !szPath[0] )
2143 LPITEMIDLIST pidl = NULL;
2144 IShellLinkW_GetIDList( sl, &pidl );
2145 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2146 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2149 /* extract the icon */
2150 if( szIconPath[0] )
2151 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2152 else
2153 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2155 /* fail - try once again after parent process exit */
2156 if( !icon_name )
2158 if (bWait)
2160 WINE_WARN("Unable to extract icon, deferring.\n");
2161 goto cleanup;
2163 WINE_ERR("failed to extract icon from %s\n",
2164 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2167 unix_link = wine_get_unix_file_name(link);
2168 if (unix_link == NULL)
2170 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2171 goto cleanup;
2174 /* check the path */
2175 if( szPath[0] )
2177 static const WCHAR exeW[] = {'.','e','x','e',0};
2178 WCHAR *p;
2180 /* check for .exe extension */
2181 if (!(p = strrchrW( szPath, '.' )) ||
2182 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2183 lstrcmpiW( p, exeW ))
2185 /* Not .exe - use 'start.exe' to launch this file */
2186 p = szArgs + lstrlenW(szPath) + 2;
2187 if (szArgs[0])
2189 p[0] = ' ';
2190 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2191 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2193 else
2194 p[0] = 0;
2196 szArgs[0] = '"';
2197 lstrcpyW(szArgs + 1, szPath);
2198 p[-1] = '"';
2200 GetWindowsDirectoryW(szPath, MAX_PATH);
2201 lstrcatW(szPath, startW);
2204 /* convert app working dir */
2205 if (szWorkDir[0])
2206 work_dir = wine_get_unix_file_name( szWorkDir );
2208 else
2210 /* if there's no path... try run the link itself */
2211 lstrcpynW(szArgs, link, MAX_PATH);
2212 GetWindowsDirectoryW(szPath, MAX_PATH);
2213 lstrcatW(szPath, startW);
2216 /* escape the path and parameters */
2217 escaped_path = escape(szPath);
2218 escaped_args = escape(szArgs);
2219 escaped_description = escape(szDescription);
2221 /* building multiple menus concurrently has race conditions */
2222 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2223 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2225 WINE_ERR("failed wait for semaphore\n");
2226 goto cleanup;
2229 if (in_desktop_dir(csidl))
2231 char *location;
2232 const char *lastEntry;
2233 lastEntry = strrchr(link_name, '/');
2234 if (lastEntry == NULL)
2235 lastEntry = link_name;
2236 else
2237 ++lastEntry;
2238 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2239 if (location)
2241 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2242 HeapFree(GetProcessHeap(), 0, location);
2245 else
2246 r = !write_menu_entry(unix_link, link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2248 ReleaseSemaphore( hsem, 1, NULL );
2250 cleanup:
2251 if (hsem) CloseHandle( hsem );
2252 HeapFree( GetProcessHeap(), 0, icon_name );
2253 HeapFree( GetProcessHeap(), 0, work_dir );
2254 HeapFree( GetProcessHeap(), 0, link_name );
2255 HeapFree( GetProcessHeap(), 0, escaped_args );
2256 HeapFree( GetProcessHeap(), 0, escaped_path );
2257 HeapFree( GetProcessHeap(), 0, escaped_description );
2258 HeapFree( GetProcessHeap(), 0, unix_link);
2260 if (r && !bWait)
2261 WINE_ERR("failed to build the menu\n" );
2263 return ( r == 0 );
2266 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2268 char *link_name = NULL;
2269 DWORD csidl = -1;
2270 LPWSTR urlPath;
2271 char *escaped_urlPath = NULL;
2272 HRESULT hr;
2273 HANDLE hSem = NULL;
2274 BOOL ret = TRUE;
2275 int r = -1;
2276 char *unix_link = NULL;
2278 if ( !link )
2280 WINE_ERR("Link name is null\n");
2281 return TRUE;
2284 if( !GetLinkLocation( link, &csidl, &link_name ) )
2286 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2287 return TRUE;
2289 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2291 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2292 ret = TRUE;
2293 goto cleanup;
2295 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2297 hr = url->lpVtbl->GetURL(url, &urlPath);
2298 if (FAILED(hr))
2300 ret = TRUE;
2301 goto cleanup;
2303 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2305 unix_link = wine_get_unix_file_name(link);
2306 if (unix_link == NULL)
2308 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2309 goto cleanup;
2312 escaped_urlPath = escape(urlPath);
2314 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2315 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2317 WINE_ERR("failed wait for semaphore\n");
2318 goto cleanup;
2320 if (in_desktop_dir(csidl))
2322 char *location;
2323 const char *lastEntry;
2324 lastEntry = strrchr(link_name, '/');
2325 if (lastEntry == NULL)
2326 lastEntry = link_name;
2327 else
2328 ++lastEntry;
2329 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2330 if (location)
2332 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2333 HeapFree(GetProcessHeap(), 0, location);
2336 else
2337 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2338 ret = (r != 0);
2339 ReleaseSemaphore(hSem, 1, NULL);
2341 cleanup:
2342 if (hSem)
2343 CloseHandle(hSem);
2344 HeapFree(GetProcessHeap(), 0, link_name);
2345 CoTaskMemFree( urlPath );
2346 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2347 HeapFree(GetProcessHeap(), 0, unix_link);
2348 return ret;
2351 static BOOL WaitForParentProcess( void )
2353 PROCESSENTRY32 procentry;
2354 HANDLE hsnapshot = NULL, hprocess = NULL;
2355 DWORD ourpid = GetCurrentProcessId();
2356 BOOL ret = FALSE, rc;
2358 WINE_TRACE("Waiting for parent process\n");
2359 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2360 INVALID_HANDLE_VALUE)
2362 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2363 goto done;
2366 procentry.dwSize = sizeof(PROCESSENTRY32);
2367 rc = Process32First( hsnapshot, &procentry );
2368 while (rc)
2370 if (procentry.th32ProcessID == ourpid) break;
2371 rc = Process32Next( hsnapshot, &procentry );
2373 if (!rc)
2375 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2376 goto done;
2379 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2380 NULL)
2382 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2383 GetLastError());
2384 goto done;
2387 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2388 ret = TRUE;
2389 else
2390 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2392 done:
2393 if (hprocess) CloseHandle( hprocess );
2394 if (hsnapshot) CloseHandle( hsnapshot );
2395 return ret;
2398 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2400 IShellLinkW *sl;
2401 IPersistFile *pf;
2402 HRESULT r;
2403 WCHAR fullname[MAX_PATH];
2404 DWORD len;
2406 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2408 if( !linkname[0] )
2410 WINE_ERR("link name missing\n");
2411 return 1;
2414 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2415 if (len==0 || len>MAX_PATH)
2417 WINE_ERR("couldn't get full path of link file\n");
2418 return 1;
2421 r = CoInitialize( NULL );
2422 if( FAILED( r ) )
2424 WINE_ERR("CoInitialize failed\n");
2425 return 1;
2428 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2429 &IID_IShellLinkW, (LPVOID *) &sl );
2430 if( FAILED( r ) )
2432 WINE_ERR("No IID_IShellLink\n");
2433 return 1;
2436 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2437 if( FAILED( r ) )
2439 WINE_ERR("No IID_IPersistFile\n");
2440 return 1;
2443 r = IPersistFile_Load( pf, fullname, STGM_READ );
2444 if( SUCCEEDED( r ) )
2446 /* If something fails (eg. Couldn't extract icon)
2447 * wait for parent process and try again
2449 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2451 WaitForParentProcess();
2452 InvokeShellLinker( sl, fullname, FALSE );
2455 else
2457 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2460 IPersistFile_Release( pf );
2461 IShellLinkW_Release( sl );
2463 CoUninitialize();
2465 return !r;
2468 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2470 IUniformResourceLocatorW *url;
2471 IPersistFile *pf;
2472 HRESULT r;
2473 WCHAR fullname[MAX_PATH];
2474 DWORD len;
2476 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2478 if( !urlname[0] )
2480 WINE_ERR("URL name missing\n");
2481 return 1;
2484 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2485 if (len==0 || len>MAX_PATH)
2487 WINE_ERR("couldn't get full path of URL file\n");
2488 return 1;
2491 r = CoInitialize( NULL );
2492 if( FAILED( r ) )
2494 WINE_ERR("CoInitialize failed\n");
2495 return 1;
2498 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2499 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2500 if( FAILED( r ) )
2502 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2503 return 1;
2506 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2507 if( FAILED( r ) )
2509 WINE_ERR("No IID_IPersistFile\n");
2510 return 1;
2512 r = IPersistFile_Load( pf, fullname, STGM_READ );
2513 if( SUCCEEDED( r ) )
2515 /* If something fails (eg. Couldn't extract icon)
2516 * wait for parent process and try again
2518 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2520 WaitForParentProcess();
2521 InvokeShellLinkerForURL( url, fullname, FALSE );
2525 IPersistFile_Release( pf );
2526 url->lpVtbl->Release( url );
2528 CoUninitialize();
2530 return !r;
2533 static void RefreshFileTypeAssociations(void)
2535 HANDLE hSem = NULL;
2536 char *mime_dir = NULL;
2537 char *packages_dir = NULL;
2538 char *applications_dir = NULL;
2539 BOOL hasChanged;
2541 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2542 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2544 WINE_ERR("failed wait for semaphore\n");
2545 CloseHandle(hSem);
2546 hSem = NULL;
2547 goto end;
2550 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2551 if (mime_dir == NULL)
2553 WINE_ERR("out of memory\n");
2554 goto end;
2556 create_directories(mime_dir);
2558 packages_dir = heap_printf("%s/packages", mime_dir);
2559 if (packages_dir == NULL)
2561 WINE_ERR("out of memory\n");
2562 goto end;
2564 create_directories(packages_dir);
2566 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2567 if (applications_dir == NULL)
2569 WINE_ERR("out of memory\n");
2570 goto end;
2572 create_directories(applications_dir);
2574 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2575 hasChanged |= cleanup_associations();
2576 if (hasChanged)
2578 const char *argv[3];
2580 argv[0] = "update-mime-database";
2581 argv[1] = mime_dir;
2582 argv[2] = NULL;
2583 spawnvp( _P_NOWAIT, argv[0], argv );
2585 argv[0] = "update-desktop-database";
2586 argv[1] = applications_dir;
2587 spawnvp( _P_NOWAIT, argv[0], argv );
2590 end:
2591 if (hSem)
2593 ReleaseSemaphore(hSem, 1, NULL);
2594 CloseHandle(hSem);
2596 HeapFree(GetProcessHeap(), 0, mime_dir);
2597 HeapFree(GetProcessHeap(), 0, packages_dir);
2598 HeapFree(GetProcessHeap(), 0, applications_dir);
2601 static void cleanup_menus(void)
2603 HKEY hkey;
2605 hkey = open_menus_reg_key();
2606 if (hkey)
2608 int i;
2609 LSTATUS lret = ERROR_SUCCESS;
2610 for (i = 0; lret == ERROR_SUCCESS; )
2612 char *value = NULL;
2613 char *data = NULL;
2614 DWORD valueSize = 4096;
2615 DWORD dataSize = 4096;
2616 while (1)
2618 lret = ERROR_OUTOFMEMORY;
2619 value = HeapAlloc(GetProcessHeap(), 0, valueSize);
2620 if (value == NULL)
2621 break;
2622 data = HeapAlloc(GetProcessHeap(), 0, dataSize);
2623 if (data == NULL)
2624 break;
2625 lret = RegEnumValueA(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2626 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2627 break;
2628 valueSize *= 2;
2629 dataSize *= 2;
2630 HeapFree(GetProcessHeap(), 0, value);
2631 HeapFree(GetProcessHeap(), 0, data);
2632 value = data = NULL;
2634 if (lret == ERROR_SUCCESS)
2636 struct stat filestats;
2637 if (stat(data, &filestats) < 0 && errno == ENOENT)
2639 WINE_TRACE("removing menu related file %s\n", value);
2640 remove(value);
2641 RegDeleteValueA(hkey, value);
2643 else
2644 i++;
2646 else if (lret != ERROR_NO_MORE_ITEMS)
2647 WINE_WARN("error %d reading registry\n", lret);
2648 HeapFree(GetProcessHeap(), 0, value);
2649 HeapFree(GetProcessHeap(), 0, data);
2651 RegCloseKey(hkey);
2653 else
2654 WINE_ERR("error opening registry key, menu cleanup failed\n");
2657 static CHAR *next_token( LPSTR *p )
2659 LPSTR token = NULL, t = *p;
2661 if( !t )
2662 return NULL;
2664 while( t && !token )
2666 switch( *t )
2668 case ' ':
2669 t++;
2670 continue;
2671 case '"':
2672 /* unquote the token */
2673 token = ++t;
2674 t = strchr( token, '"' );
2675 if( t )
2676 *t++ = 0;
2677 break;
2678 case 0:
2679 t = NULL;
2680 break;
2681 default:
2682 token = t;
2683 t = strchr( token, ' ' );
2684 if( t )
2685 *t++ = 0;
2686 break;
2689 *p = t;
2690 return token;
2693 static BOOL init_xdg(void)
2695 WCHAR shellDesktopPath[MAX_PATH];
2696 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2697 if (SUCCEEDED(hr))
2698 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2699 if (xdg_desktop_dir == NULL)
2701 WINE_ERR("error looking up the desktop directory\n");
2702 return FALSE;
2705 if (getenv("XDG_CONFIG_HOME"))
2706 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2707 else
2708 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2709 if (xdg_config_dir)
2711 create_directories(xdg_config_dir);
2712 if (getenv("XDG_DATA_HOME"))
2713 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
2714 else
2715 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2716 if (xdg_data_dir)
2718 char *buffer;
2719 create_directories(xdg_data_dir);
2720 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2721 if (buffer)
2723 mkdir(buffer, 0777);
2724 HeapFree(GetProcessHeap(), 0, buffer);
2726 return TRUE;
2728 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2730 WINE_ERR("out of memory\n");
2731 return FALSE;
2734 /***********************************************************************
2736 * WinMain
2738 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
2740 LPSTR token = NULL, p;
2741 BOOL bWait = FALSE;
2742 BOOL bURL = FALSE;
2743 int ret = 0;
2745 if (!init_xdg())
2746 return 1;
2748 for( p = cmdline; p && *p; )
2750 token = next_token( &p );
2751 if( !token )
2752 break;
2753 if( !lstrcmpA( token, "-a" ) )
2755 RefreshFileTypeAssociations();
2756 continue;
2758 if( !lstrcmpA( token, "-r" ) )
2760 cleanup_menus();
2761 continue;
2763 if( !lstrcmpA( token, "-w" ) )
2764 bWait = TRUE;
2765 else if ( !lstrcmpA( token, "-u" ) )
2766 bURL = TRUE;
2767 else if( token[0] == '-' )
2769 WINE_ERR( "unknown option %s\n",token);
2771 else
2773 WCHAR link[MAX_PATH];
2774 BOOL bRet;
2776 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2777 if (bURL)
2778 bRet = Process_URL( link, bWait );
2779 else
2780 bRet = Process_Link( link, bWait );
2781 if (!bRet)
2783 WINE_ERR( "failed to build menu item for %s\n",token);
2784 ret = 1;
2789 return ret;