push c6bab2db4fc296bd36abf8f7d9cf443d4a73048e
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blob58e84c6acba153633cdb89bb6501416be14d1050
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.
56 #include "config.h"
57 #include "wine/port.h"
59 #include <ctype.h>
60 #include <stdio.h>
61 #include <string.h>
62 #ifdef HAVE_UNISTD_H
63 #include <unistd.h>
64 #endif
65 #include <errno.h>
66 #include <stdarg.h>
68 #define COBJMACROS
70 #include <windows.h>
71 #include <shlobj.h>
72 #include <objidl.h>
73 #include <shlguid.h>
74 #include <appmgmt.h>
75 #include <tlhelp32.h>
76 #include <intshcut.h>
78 #include "wine/unicode.h"
79 #include "wine/debug.h"
80 #include "wine/library.h"
81 #include "wine/list.h"
82 #include "wine.xpm"
84 #ifdef HAVE_PNG_H
85 #undef FAR
86 #include <png.h>
87 #endif
89 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
91 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
92 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
93 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
94 (csidl)==CSIDL_COMMON_STARTMENU)
96 /* link file formats */
98 #include "pshpack1.h"
100 typedef struct
102 BYTE bWidth;
103 BYTE bHeight;
104 BYTE bColorCount;
105 BYTE bReserved;
106 WORD wPlanes;
107 WORD wBitCount;
108 DWORD dwBytesInRes;
109 WORD nID;
110 } GRPICONDIRENTRY;
112 typedef struct
114 WORD idReserved;
115 WORD idType;
116 WORD idCount;
117 GRPICONDIRENTRY idEntries[1];
118 } GRPICONDIR;
120 typedef struct
122 BYTE bWidth;
123 BYTE bHeight;
124 BYTE bColorCount;
125 BYTE bReserved;
126 WORD wPlanes;
127 WORD wBitCount;
128 DWORD dwBytesInRes;
129 DWORD dwImageOffset;
130 } ICONDIRENTRY;
132 typedef struct
134 WORD idReserved;
135 WORD idType;
136 WORD idCount;
137 } ICONDIR;
140 #include "poppack.h"
142 typedef struct
144 HRSRC *pResInfo;
145 int nIndex;
146 } ENUMRESSTRUCT;
148 struct xdg_mime_type
150 char *mimeType;
151 char *glob;
152 struct list entry;
155 static char *xdg_config_dir;
156 static char *xdg_data_dir;
157 static char *xdg_desktop_dir;
159 /* Icon extraction routines
161 * FIXME: should use PrivateExtractIcons and friends
162 * FIXME: should not use stdio
165 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
167 /* PNG-specific code */
168 #ifdef SONAME_LIBPNG
170 static void *libpng_handle;
171 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
172 MAKE_FUNCPTR(png_create_info_struct);
173 MAKE_FUNCPTR(png_create_write_struct);
174 MAKE_FUNCPTR(png_destroy_write_struct);
175 MAKE_FUNCPTR(png_init_io);
176 MAKE_FUNCPTR(png_set_bgr);
177 MAKE_FUNCPTR(png_set_text);
178 MAKE_FUNCPTR(png_set_IHDR);
179 MAKE_FUNCPTR(png_write_end);
180 MAKE_FUNCPTR(png_write_info);
181 MAKE_FUNCPTR(png_write_row);
182 #undef MAKE_FUNCPTR
184 static void *load_libpng(void)
186 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
188 #define LOAD_FUNCPTR(f) \
189 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
190 libpng_handle = NULL; \
191 return NULL; \
193 LOAD_FUNCPTR(png_create_info_struct);
194 LOAD_FUNCPTR(png_create_write_struct);
195 LOAD_FUNCPTR(png_destroy_write_struct);
196 LOAD_FUNCPTR(png_init_io);
197 LOAD_FUNCPTR(png_set_bgr);
198 LOAD_FUNCPTR(png_set_IHDR);
199 LOAD_FUNCPTR(png_set_text);
200 LOAD_FUNCPTR(png_write_end);
201 LOAD_FUNCPTR(png_write_info);
202 LOAD_FUNCPTR(png_write_row);
203 #undef LOAD_FUNCPTR
205 return libpng_handle;
208 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
210 static const char comment_key[] = "Created from";
211 FILE *fp;
212 png_structp png_ptr;
213 png_infop info_ptr;
214 png_text comment;
215 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
216 BYTE *row, *copy = NULL;
217 const BYTE *pXOR, *pAND = NULL;
218 int nWidth = pIcon->bmiHeader.biWidth;
219 int nHeight = pIcon->bmiHeader.biHeight;
220 int nBpp = pIcon->bmiHeader.biBitCount;
222 switch (nBpp)
224 case 32:
225 color_type |= PNG_COLOR_MASK_ALPHA;
226 /* fall through */
227 case 24:
228 color_type |= PNG_COLOR_MASK_COLOR;
229 break;
230 default:
231 return FALSE;
234 if (!libpng_handle && !load_libpng())
236 WINE_WARN("Unable to load libpng\n");
237 return FALSE;
240 if (!(fp = fopen(png_filename, "w")))
242 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
243 return FALSE;
246 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
247 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
248 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
249 if (nHeight > nWidth)
251 nHeight /= 2;
252 pAND = pXOR + nHeight * nXORWidthBytes;
255 /* Apply mask if present */
256 if (pAND)
258 RGBQUAD bgColor;
260 /* copy bytes before modifying them */
261 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
262 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
263 pXOR = copy;
265 /* image and mask are upside down reversed */
266 row = copy + (nHeight - 1) * nXORWidthBytes;
268 /* top left corner */
269 bgColor.rgbRed = row[0];
270 bgColor.rgbGreen = row[1];
271 bgColor.rgbBlue = row[2];
272 bgColor.rgbReserved = 0;
274 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
275 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
276 if (MASK(j, i))
278 RGBQUAD *pixel = (RGBQUAD *)row;
279 pixel->rgbBlue = bgColor.rgbBlue;
280 pixel->rgbGreen = bgColor.rgbGreen;
281 pixel->rgbRed = bgColor.rgbRed;
282 if (nBpp == 32)
283 pixel->rgbReserved = bgColor.rgbReserved;
287 comment.text = NULL;
289 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
290 !(info_ptr = ppng_create_info_struct(png_ptr)))
291 goto error;
293 if (setjmp(png_jmpbuf(png_ptr)))
295 /* All future errors jump here */
296 WINE_ERR("png error\n");
297 goto error;
300 ppng_init_io(png_ptr, fp);
301 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
302 color_type,
303 PNG_INTERLACE_NONE,
304 PNG_COMPRESSION_TYPE_DEFAULT,
305 PNG_FILTER_TYPE_DEFAULT);
307 /* Set comment */
308 comment.compression = PNG_TEXT_COMPRESSION_NONE;
309 comment.key = (png_charp)comment_key;
310 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
311 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
312 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
313 comment.text_length = i - 1;
314 ppng_set_text(png_ptr, info_ptr, &comment, 1);
317 ppng_write_info(png_ptr, info_ptr);
318 ppng_set_bgr(png_ptr);
319 for (i = nHeight - 1; i >= 0 ; i--)
320 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
321 ppng_write_end(png_ptr, info_ptr);
323 ppng_destroy_write_struct(&png_ptr, &info_ptr);
324 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
325 fclose(fp);
326 HeapFree(GetProcessHeap(), 0, copy);
327 HeapFree(GetProcessHeap(), 0, comment.text);
328 return TRUE;
330 error:
331 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
332 fclose(fp);
333 unlink(png_filename);
334 HeapFree(GetProcessHeap(), 0, copy);
335 HeapFree(GetProcessHeap(), 0, comment.text);
336 return FALSE;
338 #endif /* SONAME_LIBPNG */
340 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
342 FILE *fXPMFile;
343 int nHeight;
344 int nXORWidthBytes;
345 int nANDWidthBytes;
346 BOOL b8BitColors;
347 int nColors;
348 const BYTE *pXOR;
349 const BYTE *pAND;
350 BOOL aColorUsed[256] = {0};
351 int nColorsUsed = 0;
352 int i,j;
353 char *comment;
355 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
357 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
358 return FALSE;
361 if (!(fXPMFile = fopen(szXPMFileName, "w")))
363 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
364 return FALSE;
367 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
368 comment = HeapAlloc(GetProcessHeap(), 0, i);
369 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
371 nHeight = pIcon->bmiHeader.biHeight / 2;
372 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
373 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
374 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
375 + ((pIcon->bmiHeader.biWidth % 32) > 0));
376 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
377 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
378 : 1 << pIcon->bmiHeader.biBitCount;
379 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
380 pAND = pXOR + nHeight * nXORWidthBytes;
382 #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)
384 for (i = 0; i < nHeight; i++) {
385 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
386 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
388 aColorUsed[COLOR(j,i)] = TRUE;
389 nColorsUsed++;
394 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
395 goto error;
396 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
397 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
398 goto error;
400 for (i = 0; i < nColors; i++) {
401 if (aColorUsed[i])
402 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
403 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
404 goto error;
406 if (fprintf(fXPMFile, "\" c None\"") <= 0)
407 goto error;
409 for (i = 0; i < nHeight; i++)
411 if (fprintf(fXPMFile, ",\n\"") <= 0)
412 goto error;
413 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
415 if MASK(j,i)
417 if (fprintf(fXPMFile, " ") <= 0)
418 goto error;
420 else
421 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
422 goto error;
424 if (fprintf(fXPMFile, "\"") <= 0)
425 goto error;
427 if (fprintf(fXPMFile, "};\n") <= 0)
428 goto error;
430 #undef MASK
431 #undef COLOR
433 HeapFree(GetProcessHeap(), 0, comment);
434 fclose(fXPMFile);
435 return TRUE;
437 error:
438 HeapFree(GetProcessHeap(), 0, comment);
439 fclose(fXPMFile);
440 unlink( szXPMFileName );
441 return FALSE;
444 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
446 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
448 if (!sEnumRes->nIndex--)
450 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
451 return FALSE;
453 else
454 return TRUE;
457 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
459 HMODULE hModule;
460 HRSRC hResInfo;
461 LPCWSTR lpName = NULL;
462 HGLOBAL hResData;
463 GRPICONDIR *pIconDir;
464 BITMAPINFO *pIcon;
465 ENUMRESSTRUCT sEnumRes;
466 int nMax = 0;
467 int nMaxBits = 0;
468 int i;
469 BOOL ret = FALSE;
471 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
472 if (!hModule)
474 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
475 wine_dbgstr_w(szFileName), GetLastError());
476 return FALSE;
479 if (nIndex < 0)
481 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
482 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
483 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
485 else
487 hResInfo=NULL;
488 sEnumRes.pResInfo = &hResInfo;
489 sEnumRes.nIndex = nIndex;
490 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
491 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
492 sEnumRes.nIndex != -1)
494 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
498 if (hResInfo)
500 if ((hResData = LoadResource(hModule, hResInfo)))
502 if ((pIconDir = LockResource(hResData)))
504 for (i = 0; i < pIconDir->idCount; i++)
506 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
508 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
510 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
511 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
512 nMaxBits = pIconDir->idEntries[i].wBitCount;
518 FreeResource(hResData);
521 else
523 WINE_WARN("found no icon\n");
524 FreeLibrary(hModule);
525 return FALSE;
528 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
530 if ((hResData = LoadResource(hModule, hResInfo)))
532 if ((pIcon = LockResource(hResData)))
534 #ifdef SONAME_LIBPNG
535 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
536 ret = TRUE;
537 else
538 #endif
540 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
541 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
542 ret = TRUE;
546 FreeResource(hResData);
550 FreeLibrary(hModule);
551 return ret;
554 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
556 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
557 !extract_icon16(szFileName, szXPMFileName)*/)
558 return FALSE;
559 return TRUE;
562 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
564 FILE *fICOFile = NULL;
565 ICONDIR iconDir;
566 ICONDIRENTRY *pIconDirEntry = NULL;
567 int nMax = 0, nMaxBits = 0;
568 int nIndex = 0;
569 void *pIcon = NULL;
570 int i;
571 char *filename = NULL;
573 filename = wine_get_unix_file_name(szFileName);
574 if (!(fICOFile = fopen(filename, "r")))
576 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
577 goto error;
580 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
581 (iconDir.idReserved != 0) || (iconDir.idType != 1))
583 WINE_WARN("Invalid ico file format\n");
584 goto error;
587 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
588 goto error;
589 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
590 goto error;
592 for (i = 0; i < iconDir.idCount; i++)
594 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
595 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
596 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
598 nIndex = i;
599 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
600 nMaxBits = pIconDirEntry[i].wBitCount;
603 WINE_TRACE("Selected: %d\n", nIndex);
605 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
606 goto error;
607 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
608 goto error;
609 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
610 goto error;
613 /* Prefer PNG over XPM */
614 #ifdef SONAME_LIBPNG
615 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
616 #endif
618 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
619 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
620 goto error;
623 HeapFree(GetProcessHeap(), 0, pIcon);
624 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
625 fclose(fICOFile);
626 HeapFree(GetProcessHeap(), 0, filename);
627 return 1;
629 error:
630 HeapFree(GetProcessHeap(), 0, pIcon);
631 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
632 if (fICOFile) fclose(fICOFile);
633 HeapFree(GetProcessHeap(), 0, filename);
634 return 0;
637 static BOOL create_default_icon( const char *filename, const char* comment )
639 FILE *fXPM;
640 unsigned int i;
642 if (!(fXPM = fopen(filename, "w"))) return FALSE;
643 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
644 goto error;
645 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
646 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
647 goto error;
649 if (fprintf( fXPM, "};\n" ) <=0)
650 goto error;
651 fclose( fXPM );
652 return TRUE;
653 error:
654 fclose( fXPM );
655 unlink( filename );
656 return FALSE;
660 static unsigned short crc16(const char* string)
662 unsigned short crc = 0;
663 int i, j, xor_poly;
665 for (i = 0; string[i] != 0; i++)
667 char c = string[i];
668 for (j = 0; j < 8; c >>= 1, j++)
670 xor_poly = (c ^ crc) & 1;
671 crc >>= 1;
672 if (xor_poly)
673 crc ^= 0xa001;
676 return crc;
679 static char* heap_printf(const char *format, ...)
681 va_list args;
682 int size = 4096;
683 char *buffer;
684 int n;
686 va_start(args, format);
687 while (1)
689 buffer = HeapAlloc(GetProcessHeap(), 0, size);
690 if (buffer == NULL)
691 break;
692 n = vsnprintf(buffer, size, format, args);
693 if (n == -1)
694 size *= 2;
695 else if (n >= size)
696 size = n + 1;
697 else
698 break;
699 HeapFree(GetProcessHeap(), 0, buffer);
701 va_end(args);
702 return buffer;
705 static BOOL create_directories(char *directory)
707 BOOL ret = TRUE;
708 int i;
710 for (i = 0; directory[i]; i++)
712 if (i > 0 && directory[i] == '/')
714 directory[i] = 0;
715 mkdir(directory, 0777);
716 directory[i] = '/';
719 if (mkdir(directory, 0777) && errno != EEXIST)
720 ret = FALSE;
722 return ret;
725 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
726 static char *extract_icon( LPCWSTR path, int index, BOOL bWait )
728 unsigned short crc;
729 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
730 char* s;
731 int n;
733 /* Where should we save the icon? */
734 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
735 iconsdir = heap_printf("%s/icons", xdg_data_dir);
736 if (iconsdir)
738 if (mkdir(iconsdir, 0777) && errno != EEXIST)
740 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
741 goto end;
744 else
746 WINE_TRACE("no icon created\n");
747 return NULL;
750 /* Determine the icon base name */
751 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
752 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
753 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
754 s=ico_name=ico_path;
755 while (*s!='\0') {
756 if (*s=='/' || *s=='\\') {
757 *s='\\';
758 ico_name=s;
759 } else {
760 *s=tolower(*s);
762 s++;
764 if (*ico_name=='\\') *ico_name++='\0';
765 s=strrchr(ico_name,'.');
766 if (s) *s='\0';
768 /* Compute the source-path hash */
769 crc=crc16(ico_path);
771 /* Try to treat the source file as an exe */
772 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
773 sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
774 if (ExtractFromEXEDLL( path, index, xpm_path ))
775 goto end;
777 /* Must be something else, ignore the index in that case */
778 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
779 if (ExtractFromICO( path, xpm_path))
780 goto end;
781 if (!bWait)
783 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
784 if (create_default_icon( xpm_path, ico_path ))
785 goto end;
788 HeapFree( GetProcessHeap(), 0, xpm_path );
789 xpm_path=NULL;
791 end:
792 HeapFree(GetProcessHeap(), 0, iconsdir);
793 HeapFree(GetProcessHeap(), 0, ico_path);
794 return xpm_path;
797 static BOOL write_desktop_entry(const char *location, const char *linkname, const char *path,
798 const char *args, const char *descr, const char *workdir,
799 const char *icon)
801 FILE *file;
803 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(location),
804 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
805 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
807 file = fopen(location, "w");
808 if (file == NULL)
809 return FALSE;
811 fprintf(file, "[Desktop Entry]\n");
812 fprintf(file, "Name=%s\n", linkname);
813 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
814 wine_get_config_dir(), path, args);
815 fprintf(file, "Type=Application\n");
816 fprintf(file, "StartupNotify=true\n");
817 if (descr && lstrlenA(descr))
818 fprintf(file, "Comment=%s\n", descr);
819 if (workdir && lstrlenA(workdir))
820 fprintf(file, "Path=%s\n", workdir);
821 if (icon && lstrlenA(icon))
822 fprintf(file, "Icon=%s\n", icon);
824 fclose(file);
825 return TRUE;
828 static BOOL write_directory_entry(const char *directory, const char *location)
830 FILE *file;
832 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
834 file = fopen(location, "w");
835 if (file == NULL)
836 return FALSE;
838 fprintf(file, "[Desktop Entry]\n");
839 fprintf(file, "Type=Directory\n");
840 if (strcmp(directory, "wine") == 0)
842 fprintf(file, "Name=Wine\n");
843 fprintf(file, "Icon=wine\n");
845 else
847 fprintf(file, "Name=%s\n", directory);
848 fprintf(file, "Icon=folder\n");
851 fclose(file);
852 return TRUE;
855 static BOOL write_menu_file(const char *filename)
857 char *tempfilename;
858 FILE *tempfile = NULL;
859 char *lastEntry;
860 char *name = NULL;
861 char *menuPath = NULL;
862 int i;
863 int count = 0;
864 BOOL ret = FALSE;
866 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
868 while (1)
870 tempfilename = tempnam(xdg_config_dir, "_wine");
871 if (tempfilename)
873 int tempfd = open(tempfilename, O_EXCL | O_CREAT | O_WRONLY, 0666);
874 if (tempfd >= 0)
876 tempfile = fdopen(tempfd, "w");
877 if (tempfile)
878 break;
879 close(tempfd);
880 goto end;
882 else if (errno == EEXIST)
884 free(tempfilename);
885 continue;
887 free(tempfilename);
889 return FALSE;
892 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
893 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
894 fprintf(tempfile, "<Menu>\n");
895 fprintf(tempfile, " <Name>Applications</Name>\n");
897 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
898 if (name == NULL) goto end;
899 lastEntry = name;
900 for (i = 0; filename[i]; i++)
902 name[i] = filename[i];
903 if (filename[i] == '/')
905 char *dir_file_name;
906 struct stat st;
907 name[i] = 0;
908 fprintf(tempfile, " <Menu>\n");
909 fprintf(tempfile, " <Name>%s%s</Name>\n", count ? "" : "wine-", name);
910 fprintf(tempfile, " <Directory>%s%s.directory</Directory>\n", count ? "" : "wine-", name);
911 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
912 xdg_data_dir, count ? "" : "wine-", name);
913 if (dir_file_name)
915 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
916 write_directory_entry(lastEntry, dir_file_name);
917 HeapFree(GetProcessHeap(), 0, dir_file_name);
919 name[i] = '-';
920 lastEntry = &name[i+1];
921 ++count;
924 name[i] = 0;
926 fprintf(tempfile, " <Include>\n");
927 fprintf(tempfile, " <Filename>%s</Filename>\n", name);
928 fprintf(tempfile, " </Include>\n");
929 for (i = 0; i < count; i++)
930 fprintf(tempfile, " </Menu>\n");
931 fprintf(tempfile, "</Menu>\n");
933 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
934 if (menuPath == NULL) goto end;
935 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
936 ret = TRUE;
938 end:
939 if (tempfile)
940 fclose(tempfile);
941 if (ret)
942 ret = (rename(tempfilename, menuPath) == 0);
943 if (!ret && tempfilename)
944 remove(tempfilename);
945 free(tempfilename);
946 HeapFree(GetProcessHeap(), 0, name);
947 HeapFree(GetProcessHeap(), 0, menuPath);
948 return ret;
951 static BOOL write_menu_entry(const char *link, const char *path, const char *args,
952 const char *descr, const char *workdir, const char *icon)
954 const char *linkname;
955 char *desktopPath = NULL;
956 char *desktopDir;
957 char *filename = NULL;
958 BOOL ret = TRUE;
960 WINE_TRACE("(%s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(link), wine_dbgstr_a(path),
961 wine_dbgstr_a(args), wine_dbgstr_a(descr), wine_dbgstr_a(workdir),
962 wine_dbgstr_a(icon));
964 linkname = strrchr(link, '/');
965 if (linkname == NULL)
966 linkname = link;
967 else
968 ++linkname;
970 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
971 if (!desktopPath)
973 WINE_WARN("out of memory creating menu entry\n");
974 ret = FALSE;
975 goto end;
977 desktopDir = strrchr(desktopPath, '/');
978 *desktopDir = 0;
979 if (!create_directories(desktopPath))
981 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
982 ret = FALSE;
983 goto end;
985 *desktopDir = '/';
986 if (!write_desktop_entry(desktopPath, linkname, path, args, descr, workdir, icon))
988 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
989 ret = FALSE;
990 goto end;
993 filename = heap_printf("wine/%s.desktop", link);
994 if (!filename || !write_menu_file(filename))
996 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
997 ret = FALSE;
1000 end:
1001 HeapFree(GetProcessHeap(), 0, desktopPath);
1002 HeapFree(GetProcessHeap(), 0, filename);
1003 return ret;
1006 /* This escapes \ in filenames */
1007 static LPSTR escape(LPCWSTR arg)
1009 LPSTR narg, x;
1010 LPCWSTR esc;
1011 int len = 0, n;
1013 esc = arg;
1014 while((esc = strchrW(esc, '\\')))
1016 esc++;
1017 len++;
1020 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1021 narg = HeapAlloc(GetProcessHeap(), 0, len);
1023 x = narg;
1024 while (*arg)
1026 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1027 x += n;
1028 len -= n;
1029 if (*arg == '\\')
1030 *x++='\\'; /* escape \ */
1031 arg++;
1033 *x = 0;
1034 return narg;
1037 /* Return a heap-allocated copy of the unix format difference between the two
1038 * Windows-format paths.
1039 * locn is the owning location
1040 * link is within locn
1042 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1044 char *unix_locn, *unix_link;
1045 char *relative = NULL;
1047 unix_locn = wine_get_unix_file_name(locn);
1048 unix_link = wine_get_unix_file_name(link);
1049 if (unix_locn && unix_link)
1051 size_t len_unix_locn, len_unix_link;
1052 len_unix_locn = strlen (unix_locn);
1053 len_unix_link = strlen (unix_link);
1054 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1056 size_t len_rel;
1057 char *p = strrchr (unix_link + len_unix_locn, '/');
1058 p = strrchr (p, '.');
1059 if (p)
1061 *p = '\0';
1062 len_unix_link = p - unix_link;
1064 len_rel = len_unix_link - len_unix_locn;
1065 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1066 if (relative)
1068 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1072 if (!relative)
1073 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1074 HeapFree(GetProcessHeap(), 0, unix_locn);
1075 HeapFree(GetProcessHeap(), 0, unix_link);
1076 return relative;
1079 /***********************************************************************
1081 * GetLinkLocation
1083 * returns TRUE if successful
1084 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1085 * *relative will contain the address of a heap-allocated copy of the portion
1086 * of the filename that is within the specified location, in unix form
1088 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1090 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1091 DWORD len, i, r, filelen;
1092 const DWORD locations[] = {
1093 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1094 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1095 CSIDL_COMMON_STARTMENU };
1097 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1098 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1099 if (filelen==0 || filelen>MAX_PATH)
1100 return FALSE;
1102 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1104 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1105 * expand or our hardcoded list won't match.
1107 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1108 if (filelen==0 || filelen>MAX_PATH)
1109 return FALSE;
1111 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1113 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1115 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1116 continue;
1118 len = lstrlenW(buffer);
1119 if (len >= MAX_PATH)
1120 continue; /* We've just trashed memory! Hopefully we are OK */
1122 if (len > filelen || filename[len]!='\\')
1123 continue;
1124 /* do a lstrcmpinW */
1125 filename[len] = 0;
1126 r = lstrcmpiW( filename, buffer );
1127 filename[len] = '\\';
1128 if ( r )
1129 continue;
1131 /* return the remainder of the string and link type */
1132 *loc = locations[i];
1133 *relative = relative_path (filename, buffer);
1134 return (*relative != NULL);
1137 return FALSE;
1140 /* gets the target path directly or through MSI */
1141 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1142 LPWSTR szArgs, DWORD argsSize)
1144 IShellLinkDataList *dl = NULL;
1145 EXP_DARWIN_LINK *dar = NULL;
1146 HRESULT hr;
1148 szPath[0] = 0;
1149 szArgs[0] = 0;
1151 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1152 if (hr == S_OK && szPath[0])
1154 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1155 return hr;
1158 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1159 if (FAILED(hr))
1160 return hr;
1162 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1163 if (SUCCEEDED(hr))
1165 WCHAR* szCmdline;
1166 DWORD cmdSize;
1168 cmdSize=0;
1169 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1170 if (hr == ERROR_SUCCESS)
1172 cmdSize++;
1173 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1174 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1175 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1176 if (hr == ERROR_SUCCESS)
1178 WCHAR *s, *d;
1179 int bcount, in_quotes;
1181 /* Extract the application path */
1182 bcount=0;
1183 in_quotes=0;
1184 s=szCmdline;
1185 d=szPath;
1186 while (*s)
1188 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1190 /* skip the remaining spaces */
1191 do {
1192 s++;
1193 } while (*s==0x0009 || *s==0x0020);
1194 break;
1196 else if (*s==0x005c)
1198 /* '\\' */
1199 *d++=*s++;
1200 bcount++;
1202 else if (*s==0x0022)
1204 /* '"' */
1205 if ((bcount & 1)==0)
1207 /* Preceded by an even number of '\', this is
1208 * half that number of '\', plus a quote which
1209 * we erase.
1211 d-=bcount/2;
1212 in_quotes=!in_quotes;
1213 s++;
1215 else
1217 /* Preceded by an odd number of '\', this is
1218 * half that number of '\' followed by a '"'
1220 d=d-bcount/2-1;
1221 *d++='"';
1222 s++;
1224 bcount=0;
1226 else
1228 /* a regular character */
1229 *d++=*s++;
1230 bcount=0;
1232 if ((d-szPath) == pathSize)
1234 /* Keep processing the path till we get to the
1235 * arguments, but 'stand still'
1237 d--;
1240 /* Close the application path */
1241 *d=0;
1243 lstrcpynW(szArgs, s, argsSize);
1245 HeapFree( GetProcessHeap(), 0, szCmdline );
1247 LocalFree( dar );
1250 IShellLinkDataList_Release( dl );
1251 return hr;
1254 static BOOL next_line(FILE *file, char **line, int *size)
1256 int pos = 0;
1257 char *cr;
1258 if (*line == NULL)
1260 *size = 4096;
1261 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1263 while (*line != NULL)
1265 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1267 HeapFree(GetProcessHeap(), 0, *line);
1268 *line = NULL;
1269 if (feof(file))
1270 return TRUE;
1271 return FALSE;
1273 pos = strlen(*line);
1274 cr = strchr(*line, '\n');
1275 if (cr == NULL)
1277 char *line2;
1278 (*size) *= 2;
1279 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1280 if (line2)
1281 *line = line2;
1282 else
1284 HeapFree(GetProcessHeap(), 0, *line);
1285 *line = NULL;
1288 else
1290 *cr = 0;
1291 return TRUE;
1294 return FALSE;
1297 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1299 char *globs_filename = NULL;
1300 BOOL ret = TRUE;
1301 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1302 if (globs_filename)
1304 FILE *globs_file = fopen(globs_filename, "r");
1305 if (globs_file) /* doesn't have to exist */
1307 char *line = NULL;
1308 int size = 0;
1309 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1311 char *pos;
1312 struct xdg_mime_type *mime_type_entry = NULL;
1313 if (line[0] != '#' && (pos = strchr(line, ':')))
1315 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1316 if (mime_type_entry)
1318 *pos = 0;
1319 mime_type_entry->mimeType = line;
1320 mime_type_entry->glob = pos + 1;
1321 list_add_tail(mime_types, &mime_type_entry->entry);
1323 else
1324 ret = FALSE;
1327 HeapFree(GetProcessHeap(), 0, line);
1328 fclose(globs_file);
1330 HeapFree(GetProcessHeap(), 0, globs_filename);
1332 else
1333 ret = FALSE;
1334 return ret;
1337 static void free_native_mime_types(struct list *native_mime_types)
1339 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1341 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1343 list_remove(&mime_type_entry->entry);
1344 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1345 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1347 HeapFree(GetProcessHeap(), 0, native_mime_types);
1350 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1352 char *xdg_data_dirs;
1353 BOOL ret;
1355 *mime_types = NULL;
1357 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1358 if (xdg_data_dirs == NULL)
1359 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1360 else
1361 xdg_data_dirs = heap_printf("%s", xdg_data_dirs);
1363 if (xdg_data_dirs)
1365 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1366 if (*mime_types)
1368 const char *begin;
1369 char *end;
1371 list_init(*mime_types);
1372 ret = add_mimes(xdg_data_home, *mime_types);
1373 if (ret)
1375 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1377 *end = '\0';
1378 ret = add_mimes(begin, *mime_types);
1379 *end = ':';
1380 if (!ret)
1381 break;
1383 if (ret)
1384 ret = add_mimes(begin, *mime_types);
1387 else
1388 ret = FALSE;
1389 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1391 else
1392 ret = FALSE;
1393 if (!ret && *mime_types)
1395 free_native_mime_types(*mime_types);
1396 *mime_types = NULL;
1398 return ret;
1401 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1403 struct list *nativeMimeTypes = NULL;
1405 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1407 WINE_ERR("could not build native MIME types\n");
1408 return FALSE;
1410 return TRUE;
1413 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1415 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1416 '\\','s','t','a','r','t','.','e','x','e',0};
1417 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1418 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1419 WCHAR szTmp[INFOTIPSIZE];
1420 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1421 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1422 int iIconId = 0, r = -1;
1423 DWORD csidl = -1;
1424 HANDLE hsem = NULL;
1426 if ( !link )
1428 WINE_ERR("Link name is null\n");
1429 return FALSE;
1432 if( !GetLinkLocation( link, &csidl, &link_name ) )
1434 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1435 return TRUE;
1437 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1439 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1440 return TRUE;
1442 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1444 szTmp[0] = 0;
1445 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1446 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1447 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
1449 szTmp[0] = 0;
1450 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1451 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1452 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1454 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1455 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
1456 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
1458 szTmp[0] = 0;
1459 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1460 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1461 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
1463 if( !szPath[0] )
1465 LPITEMIDLIST pidl = NULL;
1466 IShellLinkW_GetIDList( sl, &pidl );
1467 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1468 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
1471 /* extract the icon */
1472 if( szIconPath[0] )
1473 icon_name = extract_icon( szIconPath , iIconId, bWait );
1474 else
1475 icon_name = extract_icon( szPath, iIconId, bWait );
1477 /* fail - try once again after parent process exit */
1478 if( !icon_name )
1480 if (bWait)
1482 WINE_WARN("Unable to extract icon, deferring.\n");
1483 goto cleanup;
1485 WINE_ERR("failed to extract icon from %s\n",
1486 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
1489 /* check the path */
1490 if( szPath[0] )
1492 static const WCHAR exeW[] = {'.','e','x','e',0};
1493 WCHAR *p;
1495 /* check for .exe extension */
1496 if (!(p = strrchrW( szPath, '.' )) ||
1497 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
1498 lstrcmpiW( p, exeW ))
1500 /* Not .exe - use 'start.exe' to launch this file */
1501 p = szArgs + lstrlenW(szPath) + 2;
1502 if (szArgs[0])
1504 p[0] = ' ';
1505 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
1506 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
1508 else
1509 p[0] = 0;
1511 szArgs[0] = '"';
1512 lstrcpyW(szArgs + 1, szPath);
1513 p[-1] = '"';
1515 GetWindowsDirectoryW(szPath, MAX_PATH);
1516 lstrcatW(szPath, startW);
1519 /* convert app working dir */
1520 if (szWorkDir[0])
1521 work_dir = wine_get_unix_file_name( szWorkDir );
1523 else
1525 /* if there's no path... try run the link itself */
1526 lstrcpynW(szArgs, link, MAX_PATH);
1527 GetWindowsDirectoryW(szPath, MAX_PATH);
1528 lstrcatW(szPath, startW);
1531 /* escape the path and parameters */
1532 escaped_path = escape(szPath);
1533 escaped_args = escape(szArgs);
1534 escaped_description = escape(szDescription);
1536 /* building multiple menus concurrently has race conditions */
1537 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1538 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
1540 WINE_ERR("failed wait for semaphore\n");
1541 goto cleanup;
1544 if (in_desktop_dir(csidl))
1546 char *location;
1547 const char *lastEntry;
1548 lastEntry = strrchr(link_name, '/');
1549 if (lastEntry == NULL)
1550 lastEntry = link_name;
1551 else
1552 ++lastEntry;
1553 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
1554 if (location)
1556 r = !write_desktop_entry(location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
1557 HeapFree(GetProcessHeap(), 0, location);
1560 else
1561 r = !write_menu_entry(link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
1563 ReleaseSemaphore( hsem, 1, NULL );
1565 cleanup:
1566 if (hsem) CloseHandle( hsem );
1567 HeapFree( GetProcessHeap(), 0, icon_name );
1568 HeapFree( GetProcessHeap(), 0, work_dir );
1569 HeapFree( GetProcessHeap(), 0, link_name );
1570 HeapFree( GetProcessHeap(), 0, escaped_args );
1571 HeapFree( GetProcessHeap(), 0, escaped_path );
1572 HeapFree( GetProcessHeap(), 0, escaped_description );
1574 if (r && !bWait)
1575 WINE_ERR("failed to build the menu\n" );
1577 return ( r == 0 );
1580 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
1582 char *link_name = NULL;
1583 DWORD csidl = -1;
1584 LPWSTR urlPath;
1585 char *escaped_urlPath = NULL;
1586 HRESULT hr;
1587 HANDLE hSem = NULL;
1588 BOOL ret = TRUE;
1589 int r = -1;
1591 if ( !link )
1593 WINE_ERR("Link name is null\n");
1594 return TRUE;
1597 if( !GetLinkLocation( link, &csidl, &link_name ) )
1599 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1600 return TRUE;
1602 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1604 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1605 ret = TRUE;
1606 goto cleanup;
1608 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1610 hr = url->lpVtbl->GetURL(url, &urlPath);
1611 if (FAILED(hr))
1613 ret = TRUE;
1614 goto cleanup;
1616 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
1618 escaped_urlPath = escape(urlPath);
1620 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1621 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
1623 WINE_ERR("failed wait for semaphore\n");
1624 goto cleanup;
1626 if (in_desktop_dir(csidl))
1628 char *location;
1629 const char *lastEntry;
1630 lastEntry = strrchr(link_name, '/');
1631 if (lastEntry == NULL)
1632 lastEntry = link_name;
1633 else
1634 ++lastEntry;
1635 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
1636 if (location)
1638 r = !write_desktop_entry(location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
1639 HeapFree(GetProcessHeap(), 0, location);
1642 else
1643 r = !write_menu_entry(link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
1644 ret = (r != 0);
1645 ReleaseSemaphore(hSem, 1, NULL);
1647 cleanup:
1648 if (hSem)
1649 CloseHandle(hSem);
1650 HeapFree(GetProcessHeap(), 0, link_name);
1651 CoTaskMemFree( urlPath );
1652 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
1653 return ret;
1656 static BOOL WaitForParentProcess( void )
1658 PROCESSENTRY32 procentry;
1659 HANDLE hsnapshot = NULL, hprocess = NULL;
1660 DWORD ourpid = GetCurrentProcessId();
1661 BOOL ret = FALSE, rc;
1663 WINE_TRACE("Waiting for parent process\n");
1664 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
1665 INVALID_HANDLE_VALUE)
1667 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
1668 goto done;
1671 procentry.dwSize = sizeof(PROCESSENTRY32);
1672 rc = Process32First( hsnapshot, &procentry );
1673 while (rc)
1675 if (procentry.th32ProcessID == ourpid) break;
1676 rc = Process32Next( hsnapshot, &procentry );
1678 if (!rc)
1680 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
1681 goto done;
1684 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
1685 NULL)
1687 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
1688 GetLastError());
1689 goto done;
1692 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
1693 ret = TRUE;
1694 else
1695 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
1697 done:
1698 if (hprocess) CloseHandle( hprocess );
1699 if (hsnapshot) CloseHandle( hsnapshot );
1700 return ret;
1703 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
1705 IShellLinkW *sl;
1706 IPersistFile *pf;
1707 HRESULT r;
1708 WCHAR fullname[MAX_PATH];
1709 DWORD len;
1711 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
1713 if( !linkname[0] )
1715 WINE_ERR("link name missing\n");
1716 return 1;
1719 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1720 if (len==0 || len>MAX_PATH)
1722 WINE_ERR("couldn't get full path of link file\n");
1723 return 1;
1726 r = CoInitialize( NULL );
1727 if( FAILED( r ) )
1729 WINE_ERR("CoInitialize failed\n");
1730 return 1;
1733 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1734 &IID_IShellLinkW, (LPVOID *) &sl );
1735 if( FAILED( r ) )
1737 WINE_ERR("No IID_IShellLink\n");
1738 return 1;
1741 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1742 if( FAILED( r ) )
1744 WINE_ERR("No IID_IPersistFile\n");
1745 return 1;
1748 r = IPersistFile_Load( pf, fullname, STGM_READ );
1749 if( SUCCEEDED( r ) )
1751 /* If something fails (eg. Couldn't extract icon)
1752 * wait for parent process and try again
1754 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
1756 WaitForParentProcess();
1757 InvokeShellLinker( sl, fullname, FALSE );
1760 else
1762 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
1765 IPersistFile_Release( pf );
1766 IShellLinkW_Release( sl );
1768 CoUninitialize();
1770 return !r;
1773 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
1775 IUniformResourceLocatorW *url;
1776 IPersistFile *pf;
1777 HRESULT r;
1778 WCHAR fullname[MAX_PATH];
1779 DWORD len;
1781 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
1783 if( !urlname[0] )
1785 WINE_ERR("URL name missing\n");
1786 return 1;
1789 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
1790 if (len==0 || len>MAX_PATH)
1792 WINE_ERR("couldn't get full path of URL file\n");
1793 return 1;
1796 r = CoInitialize( NULL );
1797 if( FAILED( r ) )
1799 WINE_ERR("CoInitialize failed\n");
1800 return 1;
1803 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
1804 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
1805 if( FAILED( r ) )
1807 WINE_ERR("No IID_IUniformResourceLocatorW\n");
1808 return 1;
1811 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
1812 if( FAILED( r ) )
1814 WINE_ERR("No IID_IPersistFile\n");
1815 return 1;
1817 r = IPersistFile_Load( pf, fullname, STGM_READ );
1818 if( SUCCEEDED( r ) )
1820 /* If something fails (eg. Couldn't extract icon)
1821 * wait for parent process and try again
1823 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
1825 WaitForParentProcess();
1826 InvokeShellLinkerForURL( url, fullname, FALSE );
1830 IPersistFile_Release( pf );
1831 url->lpVtbl->Release( url );
1833 CoUninitialize();
1835 return !r;
1838 static void RefreshFileTypeAssociations(void)
1840 HANDLE hSem = NULL;
1841 char *mime_dir = NULL;
1842 char *packages_dir = NULL;
1843 char *applications_dir = NULL;
1845 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1846 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
1848 WINE_ERR("failed wait for semaphore\n");
1849 CloseHandle(hSem);
1850 hSem = NULL;
1851 goto end;
1854 mime_dir = heap_printf("%s/mime", xdg_data_dir);
1855 if (mime_dir == NULL)
1857 WINE_ERR("out of memory\n");
1858 goto end;
1860 create_directories(mime_dir);
1862 packages_dir = heap_printf("%s/packages", mime_dir);
1863 if (packages_dir == NULL)
1865 WINE_ERR("out of memory\n");
1866 goto end;
1868 create_directories(packages_dir);
1870 applications_dir = heap_printf("%s/applications", xdg_data_dir);
1871 if (applications_dir == NULL)
1873 WINE_ERR("out of memory\n");
1874 goto end;
1876 create_directories(applications_dir);
1878 generate_associations(xdg_data_dir, packages_dir, applications_dir);
1880 end:
1881 if (hSem)
1883 ReleaseSemaphore(hSem, 1, NULL);
1884 CloseHandle(hSem);
1886 HeapFree(GetProcessHeap(), 0, mime_dir);
1887 HeapFree(GetProcessHeap(), 0, packages_dir);
1888 HeapFree(GetProcessHeap(), 0, applications_dir);
1891 static CHAR *next_token( LPSTR *p )
1893 LPSTR token = NULL, t = *p;
1895 if( !t )
1896 return NULL;
1898 while( t && !token )
1900 switch( *t )
1902 case ' ':
1903 t++;
1904 continue;
1905 case '"':
1906 /* unquote the token */
1907 token = ++t;
1908 t = strchr( token, '"' );
1909 if( t )
1910 *t++ = 0;
1911 break;
1912 case 0:
1913 t = NULL;
1914 break;
1915 default:
1916 token = t;
1917 t = strchr( token, ' ' );
1918 if( t )
1919 *t++ = 0;
1920 break;
1923 *p = t;
1924 return token;
1927 static BOOL init_xdg(void)
1929 WCHAR shellDesktopPath[MAX_PATH];
1930 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
1931 if (SUCCEEDED(hr))
1932 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
1933 if (xdg_desktop_dir == NULL)
1935 WINE_ERR("error looking up the desktop directory\n");
1936 return FALSE;
1939 if (getenv("XDG_CONFIG_HOME"))
1940 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
1941 else
1942 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
1943 if (xdg_config_dir)
1945 create_directories(xdg_config_dir);
1946 if (getenv("XDG_DATA_HOME"))
1947 xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
1948 else
1949 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
1950 if (xdg_data_dir)
1952 char *buffer;
1953 create_directories(xdg_data_dir);
1954 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
1955 if (buffer)
1957 mkdir(buffer, 0777);
1958 HeapFree(GetProcessHeap(), 0, buffer);
1960 return TRUE;
1962 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
1964 WINE_ERR("out of memory\n");
1965 return FALSE;
1968 /***********************************************************************
1970 * WinMain
1972 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1974 LPSTR token = NULL, p;
1975 BOOL bWait = FALSE;
1976 BOOL bURL = FALSE;
1977 int ret = 0;
1979 if (!init_xdg())
1980 return 1;
1982 for( p = cmdline; p && *p; )
1984 token = next_token( &p );
1985 if( !token )
1986 break;
1987 if( !lstrcmpA( token, "-a" ) )
1989 RefreshFileTypeAssociations();
1990 break;
1992 if( !lstrcmpA( token, "-w" ) )
1993 bWait = TRUE;
1994 else if ( !lstrcmpA( token, "-u" ) )
1995 bURL = TRUE;
1996 else if( token[0] == '-' )
1998 WINE_ERR( "unknown option %s\n",token);
2000 else
2002 WCHAR link[MAX_PATH];
2003 BOOL bRet;
2005 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2006 if (bURL)
2007 bRet = Process_URL( link, bWait );
2008 else
2009 bRet = Process_Link( link, bWait );
2010 if (!bRet)
2012 WINE_ERR( "failed to build menu item for %s\n",token);
2013 ret = 1;
2018 return ret;