push b00f9bcd3487b4cb0fef1c9e26a0e57bdeabe83d
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blob9dafc16a13d493f14815c6beb6bfd68cb08c71c2
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.xpm"
83 #ifdef HAVE_PNG_H
84 #undef FAR
85 #include <png.h>
86 #endif
88 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
90 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
91 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
92 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
93 (csidl)==CSIDL_COMMON_STARTMENU)
95 /* link file formats */
97 #include "pshpack1.h"
99 typedef struct
101 BYTE bWidth;
102 BYTE bHeight;
103 BYTE bColorCount;
104 BYTE bReserved;
105 WORD wPlanes;
106 WORD wBitCount;
107 DWORD dwBytesInRes;
108 WORD nID;
109 } GRPICONDIRENTRY;
111 typedef struct
113 WORD idReserved;
114 WORD idType;
115 WORD idCount;
116 GRPICONDIRENTRY idEntries[1];
117 } GRPICONDIR;
119 typedef struct
121 BYTE bWidth;
122 BYTE bHeight;
123 BYTE bColorCount;
124 BYTE bReserved;
125 WORD wPlanes;
126 WORD wBitCount;
127 DWORD dwBytesInRes;
128 DWORD dwImageOffset;
129 } ICONDIRENTRY;
131 typedef struct
133 WORD idReserved;
134 WORD idType;
135 WORD idCount;
136 } ICONDIR;
139 #include "poppack.h"
141 typedef struct
143 HRSRC *pResInfo;
144 int nIndex;
145 } ENUMRESSTRUCT;
147 static char *xdg_config_dir;
148 static char *xdg_data_dir;
149 static char *xdg_desktop_dir;
151 /* Icon extraction routines
153 * FIXME: should use PrivateExtractIcons and friends
154 * FIXME: should not use stdio
157 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
159 /* PNG-specific code */
160 #ifdef SONAME_LIBPNG
162 static void *libpng_handle;
163 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
164 MAKE_FUNCPTR(png_create_info_struct);
165 MAKE_FUNCPTR(png_create_write_struct);
166 MAKE_FUNCPTR(png_destroy_write_struct);
167 MAKE_FUNCPTR(png_init_io);
168 MAKE_FUNCPTR(png_set_bgr);
169 MAKE_FUNCPTR(png_set_text);
170 MAKE_FUNCPTR(png_set_IHDR);
171 MAKE_FUNCPTR(png_write_end);
172 MAKE_FUNCPTR(png_write_info);
173 MAKE_FUNCPTR(png_write_row);
174 #undef MAKE_FUNCPTR
176 static void *load_libpng(void)
178 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
180 #define LOAD_FUNCPTR(f) \
181 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
182 libpng_handle = NULL; \
183 return NULL; \
185 LOAD_FUNCPTR(png_create_info_struct);
186 LOAD_FUNCPTR(png_create_write_struct);
187 LOAD_FUNCPTR(png_destroy_write_struct);
188 LOAD_FUNCPTR(png_init_io);
189 LOAD_FUNCPTR(png_set_bgr);
190 LOAD_FUNCPTR(png_set_IHDR);
191 LOAD_FUNCPTR(png_set_text);
192 LOAD_FUNCPTR(png_write_end);
193 LOAD_FUNCPTR(png_write_info);
194 LOAD_FUNCPTR(png_write_row);
195 #undef LOAD_FUNCPTR
197 return libpng_handle;
200 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
202 static const char comment_key[] = "Created from";
203 FILE *fp;
204 png_structp png_ptr;
205 png_infop info_ptr;
206 png_text comment;
207 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
208 BYTE *row, *copy = NULL;
209 const BYTE *pXOR, *pAND = NULL;
210 int nWidth = pIcon->bmiHeader.biWidth;
211 int nHeight = pIcon->bmiHeader.biHeight;
212 int nBpp = pIcon->bmiHeader.biBitCount;
214 switch (nBpp)
216 case 32:
217 color_type |= PNG_COLOR_MASK_ALPHA;
218 /* fall through */
219 case 24:
220 color_type |= PNG_COLOR_MASK_COLOR;
221 break;
222 default:
223 return FALSE;
226 if (!libpng_handle && !load_libpng())
228 WINE_WARN("Unable to load libpng\n");
229 return FALSE;
232 if (!(fp = fopen(png_filename, "w")))
234 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
235 return FALSE;
238 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
239 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
240 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
241 if (nHeight > nWidth)
243 nHeight /= 2;
244 pAND = pXOR + nHeight * nXORWidthBytes;
247 /* Apply mask if present */
248 if (pAND)
250 RGBQUAD bgColor;
252 /* copy bytes before modifying them */
253 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
254 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
255 pXOR = copy;
257 /* image and mask are upside down reversed */
258 row = copy + (nHeight - 1) * nXORWidthBytes;
260 /* top left corner */
261 bgColor.rgbRed = row[0];
262 bgColor.rgbGreen = row[1];
263 bgColor.rgbBlue = row[2];
264 bgColor.rgbReserved = 0;
266 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
267 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
268 if (MASK(j, i))
270 RGBQUAD *pixel = (RGBQUAD *)row;
271 pixel->rgbBlue = bgColor.rgbBlue;
272 pixel->rgbGreen = bgColor.rgbGreen;
273 pixel->rgbRed = bgColor.rgbRed;
274 if (nBpp == 32)
275 pixel->rgbReserved = bgColor.rgbReserved;
279 comment.text = NULL;
281 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
282 !(info_ptr = ppng_create_info_struct(png_ptr)))
283 goto error;
285 if (setjmp(png_jmpbuf(png_ptr)))
287 /* All future errors jump here */
288 WINE_ERR("png error\n");
289 goto error;
292 ppng_init_io(png_ptr, fp);
293 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
294 color_type,
295 PNG_INTERLACE_NONE,
296 PNG_COMPRESSION_TYPE_DEFAULT,
297 PNG_FILTER_TYPE_DEFAULT);
299 /* Set comment */
300 comment.compression = PNG_TEXT_COMPRESSION_NONE;
301 comment.key = (png_charp)comment_key;
302 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
303 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
304 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
305 comment.text_length = i - 1;
306 ppng_set_text(png_ptr, info_ptr, &comment, 1);
309 ppng_write_info(png_ptr, info_ptr);
310 ppng_set_bgr(png_ptr);
311 for (i = nHeight - 1; i >= 0 ; i--)
312 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
313 ppng_write_end(png_ptr, info_ptr);
315 ppng_destroy_write_struct(&png_ptr, &info_ptr);
316 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
317 fclose(fp);
318 HeapFree(GetProcessHeap(), 0, copy);
319 HeapFree(GetProcessHeap(), 0, comment.text);
320 return TRUE;
322 error:
323 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
324 fclose(fp);
325 unlink(png_filename);
326 HeapFree(GetProcessHeap(), 0, copy);
327 HeapFree(GetProcessHeap(), 0, comment.text);
328 return FALSE;
330 #endif /* SONAME_LIBPNG */
332 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
334 FILE *fXPMFile;
335 int nHeight;
336 int nXORWidthBytes;
337 int nANDWidthBytes;
338 BOOL b8BitColors;
339 int nColors;
340 const BYTE *pXOR;
341 const BYTE *pAND;
342 BOOL aColorUsed[256] = {0};
343 int nColorsUsed = 0;
344 int i,j;
345 char *comment;
347 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
349 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
350 return FALSE;
353 if (!(fXPMFile = fopen(szXPMFileName, "w")))
355 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
356 return FALSE;
359 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
360 comment = HeapAlloc(GetProcessHeap(), 0, i);
361 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
363 nHeight = pIcon->bmiHeader.biHeight / 2;
364 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
365 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
366 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
367 + ((pIcon->bmiHeader.biWidth % 32) > 0));
368 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
369 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
370 : 1 << pIcon->bmiHeader.biBitCount;
371 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
372 pAND = pXOR + nHeight * nXORWidthBytes;
374 #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)
376 for (i = 0; i < nHeight; i++) {
377 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
378 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
380 aColorUsed[COLOR(j,i)] = TRUE;
381 nColorsUsed++;
386 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
387 goto error;
388 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
389 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
390 goto error;
392 for (i = 0; i < nColors; i++) {
393 if (aColorUsed[i])
394 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
395 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
396 goto error;
398 if (fprintf(fXPMFile, "\" c None\"") <= 0)
399 goto error;
401 for (i = 0; i < nHeight; i++)
403 if (fprintf(fXPMFile, ",\n\"") <= 0)
404 goto error;
405 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
407 if MASK(j,i)
409 if (fprintf(fXPMFile, " ") <= 0)
410 goto error;
412 else
413 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
414 goto error;
416 if (fprintf(fXPMFile, "\"") <= 0)
417 goto error;
419 if (fprintf(fXPMFile, "};\n") <= 0)
420 goto error;
422 #undef MASK
423 #undef COLOR
425 HeapFree(GetProcessHeap(), 0, comment);
426 fclose(fXPMFile);
427 return TRUE;
429 error:
430 HeapFree(GetProcessHeap(), 0, comment);
431 fclose(fXPMFile);
432 unlink( szXPMFileName );
433 return FALSE;
436 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
438 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
440 if (!sEnumRes->nIndex--)
442 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
443 return FALSE;
445 else
446 return TRUE;
449 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
451 HMODULE hModule;
452 HRSRC hResInfo;
453 LPCWSTR lpName = NULL;
454 HGLOBAL hResData;
455 GRPICONDIR *pIconDir;
456 BITMAPINFO *pIcon;
457 ENUMRESSTRUCT sEnumRes;
458 int nMax = 0;
459 int nMaxBits = 0;
460 int i;
461 BOOL ret = FALSE;
463 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
464 if (!hModule)
466 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
467 wine_dbgstr_w(szFileName), GetLastError());
468 return FALSE;
471 if (nIndex < 0)
473 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
474 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
475 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
477 else
479 hResInfo=NULL;
480 sEnumRes.pResInfo = &hResInfo;
481 sEnumRes.nIndex = nIndex;
482 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
483 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
484 sEnumRes.nIndex != -1)
486 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
490 if (hResInfo)
492 if ((hResData = LoadResource(hModule, hResInfo)))
494 if ((pIconDir = LockResource(hResData)))
496 for (i = 0; i < pIconDir->idCount; i++)
498 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
500 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
502 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
503 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
504 nMaxBits = pIconDir->idEntries[i].wBitCount;
510 FreeResource(hResData);
513 else
515 WINE_WARN("found no icon\n");
516 FreeLibrary(hModule);
517 return FALSE;
520 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
522 if ((hResData = LoadResource(hModule, hResInfo)))
524 if ((pIcon = LockResource(hResData)))
526 #ifdef SONAME_LIBPNG
527 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
528 ret = TRUE;
529 else
530 #endif
532 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
533 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
534 ret = TRUE;
538 FreeResource(hResData);
542 FreeLibrary(hModule);
543 return ret;
546 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
548 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
549 !extract_icon16(szFileName, szXPMFileName)*/)
550 return FALSE;
551 return TRUE;
554 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
556 FILE *fICOFile = NULL;
557 ICONDIR iconDir;
558 ICONDIRENTRY *pIconDirEntry = NULL;
559 int nMax = 0, nMaxBits = 0;
560 int nIndex = 0;
561 void *pIcon = NULL;
562 int i;
563 char *filename = NULL;
565 filename = wine_get_unix_file_name(szFileName);
566 if (!(fICOFile = fopen(filename, "r")))
568 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
569 goto error;
572 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
573 (iconDir.idReserved != 0) || (iconDir.idType != 1))
575 WINE_WARN("Invalid ico file format\n");
576 goto error;
579 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
580 goto error;
581 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
582 goto error;
584 for (i = 0; i < iconDir.idCount; i++)
586 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
587 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
588 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
590 nIndex = i;
591 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
592 nMaxBits = pIconDirEntry[i].wBitCount;
595 WINE_TRACE("Selected: %d\n", nIndex);
597 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
598 goto error;
599 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
600 goto error;
601 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
602 goto error;
605 /* Prefer PNG over XPM */
606 #ifdef SONAME_LIBPNG
607 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
608 #endif
610 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
611 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
612 goto error;
615 HeapFree(GetProcessHeap(), 0, pIcon);
616 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
617 fclose(fICOFile);
618 HeapFree(GetProcessHeap(), 0, filename);
619 return 1;
621 error:
622 HeapFree(GetProcessHeap(), 0, pIcon);
623 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
624 if (fICOFile) fclose(fICOFile);
625 HeapFree(GetProcessHeap(), 0, filename);
626 return 0;
629 static BOOL create_default_icon( const char *filename, const char* comment )
631 FILE *fXPM;
632 unsigned int i;
634 if (!(fXPM = fopen(filename, "w"))) return FALSE;
635 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
636 goto error;
637 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
638 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
639 goto error;
641 if (fprintf( fXPM, "};\n" ) <=0)
642 goto error;
643 fclose( fXPM );
644 return TRUE;
645 error:
646 fclose( fXPM );
647 unlink( filename );
648 return FALSE;
652 static unsigned short crc16(const char* string)
654 unsigned short crc = 0;
655 int i, j, xor_poly;
657 for (i = 0; string[i] != 0; i++)
659 char c = string[i];
660 for (j = 0; j < 8; c >>= 1, j++)
662 xor_poly = (c ^ crc) & 1;
663 crc >>= 1;
664 if (xor_poly)
665 crc ^= 0xa001;
668 return crc;
671 static char* heap_printf(const char *format, ...)
673 va_list args;
674 int size = 4096;
675 char *buffer;
676 int n;
678 va_start(args, format);
679 while (1)
681 buffer = HeapAlloc(GetProcessHeap(), 0, size);
682 if (buffer == NULL)
683 break;
684 n = vsnprintf(buffer, size, format, args);
685 if (n == -1)
686 size *= 2;
687 else if (n >= size)
688 size = n + 1;
689 else
690 break;
691 HeapFree(GetProcessHeap(), 0, buffer);
693 va_end(args);
694 return buffer;
697 static BOOL create_directories(char *directory)
699 BOOL ret = TRUE;
700 int i;
702 for (i = 0; directory[i]; i++)
704 if (i > 0 && directory[i] == '/')
706 directory[i] = 0;
707 mkdir(directory, 0777);
708 directory[i] = '/';
711 if (mkdir(directory, 0777) && errno != EEXIST)
712 ret = FALSE;
714 return ret;
717 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
718 static char *extract_icon( LPCWSTR path, int index, BOOL bWait )
720 unsigned short crc;
721 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
722 char* s;
723 int n;
725 /* Where should we save the icon? */
726 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
727 iconsdir = heap_printf("%s/icons", xdg_data_dir);
728 if (iconsdir)
730 if (mkdir(iconsdir, 0777) && errno != EEXIST)
732 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
733 goto end;
736 else
738 WINE_TRACE("no icon created\n");
739 return NULL;
742 /* Determine the icon base name */
743 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
744 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
745 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
746 s=ico_name=ico_path;
747 while (*s!='\0') {
748 if (*s=='/' || *s=='\\') {
749 *s='\\';
750 ico_name=s;
751 } else {
752 *s=tolower(*s);
754 s++;
756 if (*ico_name=='\\') *ico_name++='\0';
757 s=strrchr(ico_name,'.');
758 if (s) *s='\0';
760 /* Compute the source-path hash */
761 crc=crc16(ico_path);
763 /* Try to treat the source file as an exe */
764 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
765 sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
766 if (ExtractFromEXEDLL( path, index, xpm_path ))
767 goto end;
769 /* Must be something else, ignore the index in that case */
770 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
771 if (ExtractFromICO( path, xpm_path))
772 goto end;
773 if (!bWait)
775 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
776 if (create_default_icon( xpm_path, ico_path ))
777 goto end;
780 HeapFree( GetProcessHeap(), 0, xpm_path );
781 xpm_path=NULL;
783 end:
784 HeapFree(GetProcessHeap(), 0, iconsdir);
785 HeapFree(GetProcessHeap(), 0, ico_path);
786 return xpm_path;
789 static BOOL write_desktop_entry(const char *location, const char *linkname, const char *path,
790 const char *args, const char *descr, const char *workdir,
791 const char *icon)
793 FILE *file;
795 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(location),
796 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
797 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
799 file = fopen(location, "w");
800 if (file == NULL)
801 return FALSE;
803 fprintf(file, "[Desktop Entry]\n");
804 fprintf(file, "Name=%s\n", linkname);
805 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
806 wine_get_config_dir(), path, args);
807 fprintf(file, "Type=Application\n");
808 fprintf(file, "StartupNotify=true\n");
809 if (descr && lstrlenA(descr))
810 fprintf(file, "Comment=%s\n", descr);
811 if (workdir && lstrlenA(workdir))
812 fprintf(file, "Path=%s\n", workdir);
813 if (icon && lstrlenA(icon))
814 fprintf(file, "Icon=%s\n", icon);
816 fclose(file);
817 return TRUE;
820 static BOOL write_directory_entry(const char *directory, const char *location)
822 FILE *file;
824 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
826 file = fopen(location, "w");
827 if (file == NULL)
828 return FALSE;
830 fprintf(file, "[Desktop Entry]\n");
831 fprintf(file, "Type=Directory\n");
832 if (strcmp(directory, "wine") == 0)
834 fprintf(file, "Name=Wine\n");
835 fprintf(file, "Icon=wine\n");
837 else
839 fprintf(file, "Name=%s\n", directory);
840 fprintf(file, "Icon=folder\n");
843 fclose(file);
844 return TRUE;
847 static BOOL write_menu_file(const char *filename)
849 char *tempfilename;
850 FILE *tempfile = NULL;
851 char *lastEntry;
852 char *name = NULL;
853 char *menuPath = NULL;
854 int i;
855 int count = 0;
856 BOOL ret = FALSE;
858 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
860 while (1)
862 tempfilename = tempnam(xdg_config_dir, "_wine");
863 if (tempfilename)
865 int tempfd = open(tempfilename, O_EXCL | O_CREAT | O_WRONLY, 0666);
866 if (tempfd >= 0)
868 tempfile = fdopen(tempfd, "w");
869 if (tempfile)
870 break;
871 close(tempfd);
872 goto end;
874 else if (errno == EEXIST)
876 free(tempfilename);
877 continue;
879 free(tempfilename);
881 return FALSE;
884 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
885 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
886 fprintf(tempfile, "<Menu>\n");
887 fprintf(tempfile, " <Name>Applications</Name>\n");
889 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
890 if (name == NULL) goto end;
891 lastEntry = name;
892 for (i = 0; filename[i]; i++)
894 name[i] = filename[i];
895 if (filename[i] == '/')
897 char *dir_file_name;
898 struct stat st;
899 name[i] = 0;
900 fprintf(tempfile, " <Menu>\n");
901 fprintf(tempfile, " <Name>%s%s</Name>\n", count ? "" : "wine-", name);
902 fprintf(tempfile, " <Directory>%s%s.directory</Directory>\n", count ? "" : "wine-", name);
903 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
904 xdg_data_dir, count ? "" : "wine-", name);
905 if (dir_file_name)
907 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
908 write_directory_entry(lastEntry, dir_file_name);
909 HeapFree(GetProcessHeap(), 0, dir_file_name);
911 name[i] = '-';
912 lastEntry = &name[i+1];
913 ++count;
916 name[i] = 0;
918 fprintf(tempfile, " <Include>\n");
919 fprintf(tempfile, " <Filename>%s</Filename>\n", name);
920 fprintf(tempfile, " </Include>\n");
921 for (i = 0; i < count; i++)
922 fprintf(tempfile, " </Menu>\n");
923 fprintf(tempfile, "</Menu>\n");
925 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
926 if (menuPath == NULL) goto end;
927 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
928 ret = TRUE;
930 end:
931 if (tempfile)
932 fclose(tempfile);
933 if (ret)
934 ret = (rename(tempfilename, menuPath) == 0);
935 if (!ret && tempfilename)
936 remove(tempfilename);
937 free(tempfilename);
938 HeapFree(GetProcessHeap(), 0, name);
939 HeapFree(GetProcessHeap(), 0, menuPath);
940 return ret;
943 static BOOL write_menu_entry(const char *link, const char *path, const char *args,
944 const char *descr, const char *workdir, const char *icon)
946 const char *linkname;
947 char *desktopPath = NULL;
948 char *desktopDir;
949 char *filename = NULL;
950 BOOL ret = TRUE;
952 WINE_TRACE("(%s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(link), wine_dbgstr_a(path),
953 wine_dbgstr_a(args), wine_dbgstr_a(descr), wine_dbgstr_a(workdir),
954 wine_dbgstr_a(icon));
956 linkname = strrchr(link, '/');
957 if (linkname == NULL)
958 linkname = link;
959 else
960 ++linkname;
962 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
963 if (!desktopPath)
965 WINE_WARN("out of memory creating menu entry\n");
966 ret = FALSE;
967 goto end;
969 desktopDir = strrchr(desktopPath, '/');
970 *desktopDir = 0;
971 if (!create_directories(desktopPath))
973 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
974 ret = FALSE;
975 goto end;
977 *desktopDir = '/';
978 if (!write_desktop_entry(desktopPath, linkname, path, args, descr, workdir, icon))
980 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
981 ret = FALSE;
982 goto end;
985 filename = heap_printf("wine/%s.desktop", link);
986 if (!filename || !write_menu_file(filename))
988 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
989 ret = FALSE;
992 end:
993 HeapFree(GetProcessHeap(), 0, desktopPath);
994 HeapFree(GetProcessHeap(), 0, filename);
995 return ret;
998 /* This escapes \ in filenames */
999 static LPSTR escape(LPCWSTR arg)
1001 LPSTR narg, x;
1002 LPCWSTR esc;
1003 int len = 0, n;
1005 esc = arg;
1006 while((esc = strchrW(esc, '\\')))
1008 esc++;
1009 len++;
1012 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1013 narg = HeapAlloc(GetProcessHeap(), 0, len);
1015 x = narg;
1016 while (*arg)
1018 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1019 x += n;
1020 len -= n;
1021 if (*arg == '\\')
1022 *x++='\\'; /* escape \ */
1023 arg++;
1025 *x = 0;
1026 return narg;
1029 /* Return a heap-allocated copy of the unix format difference between the two
1030 * Windows-format paths.
1031 * locn is the owning location
1032 * link is within locn
1034 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1036 char *unix_locn, *unix_link;
1037 char *relative = NULL;
1039 unix_locn = wine_get_unix_file_name(locn);
1040 unix_link = wine_get_unix_file_name(link);
1041 if (unix_locn && unix_link)
1043 size_t len_unix_locn, len_unix_link;
1044 len_unix_locn = strlen (unix_locn);
1045 len_unix_link = strlen (unix_link);
1046 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1048 size_t len_rel;
1049 char *p = strrchr (unix_link + len_unix_locn, '/');
1050 p = strrchr (p, '.');
1051 if (p)
1053 *p = '\0';
1054 len_unix_link = p - unix_link;
1056 len_rel = len_unix_link - len_unix_locn;
1057 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1058 if (relative)
1060 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1064 if (!relative)
1065 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1066 HeapFree(GetProcessHeap(), 0, unix_locn);
1067 HeapFree(GetProcessHeap(), 0, unix_link);
1068 return relative;
1071 /***********************************************************************
1073 * GetLinkLocation
1075 * returns TRUE if successful
1076 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1077 * *relative will contain the address of a heap-allocated copy of the portion
1078 * of the filename that is within the specified location, in unix form
1080 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1082 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1083 DWORD len, i, r, filelen;
1084 const DWORD locations[] = {
1085 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1086 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1087 CSIDL_COMMON_STARTMENU };
1089 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1090 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1091 if (filelen==0 || filelen>MAX_PATH)
1092 return FALSE;
1094 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1096 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1097 * expand or our hardcoded list won't match.
1099 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1100 if (filelen==0 || filelen>MAX_PATH)
1101 return FALSE;
1103 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1105 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1107 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1108 continue;
1110 len = lstrlenW(buffer);
1111 if (len >= MAX_PATH)
1112 continue; /* We've just trashed memory! Hopefully we are OK */
1114 if (len > filelen || filename[len]!='\\')
1115 continue;
1116 /* do a lstrcmpinW */
1117 filename[len] = 0;
1118 r = lstrcmpiW( filename, buffer );
1119 filename[len] = '\\';
1120 if ( r )
1121 continue;
1123 /* return the remainder of the string and link type */
1124 *loc = locations[i];
1125 *relative = relative_path (filename, buffer);
1126 return (*relative != NULL);
1129 return FALSE;
1132 /* gets the target path directly or through MSI */
1133 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1134 LPWSTR szArgs, DWORD argsSize)
1136 IShellLinkDataList *dl = NULL;
1137 EXP_DARWIN_LINK *dar = NULL;
1138 HRESULT hr;
1140 szPath[0] = 0;
1141 szArgs[0] = 0;
1143 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1144 if (hr == S_OK && szPath[0])
1146 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1147 return hr;
1150 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1151 if (FAILED(hr))
1152 return hr;
1154 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1155 if (SUCCEEDED(hr))
1157 WCHAR* szCmdline;
1158 DWORD cmdSize;
1160 cmdSize=0;
1161 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1162 if (hr == ERROR_SUCCESS)
1164 cmdSize++;
1165 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1166 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1167 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1168 if (hr == ERROR_SUCCESS)
1170 WCHAR *s, *d;
1171 int bcount, in_quotes;
1173 /* Extract the application path */
1174 bcount=0;
1175 in_quotes=0;
1176 s=szCmdline;
1177 d=szPath;
1178 while (*s)
1180 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1182 /* skip the remaining spaces */
1183 do {
1184 s++;
1185 } while (*s==0x0009 || *s==0x0020);
1186 break;
1188 else if (*s==0x005c)
1190 /* '\\' */
1191 *d++=*s++;
1192 bcount++;
1194 else if (*s==0x0022)
1196 /* '"' */
1197 if ((bcount & 1)==0)
1199 /* Preceded by an even number of '\', this is
1200 * half that number of '\', plus a quote which
1201 * we erase.
1203 d-=bcount/2;
1204 in_quotes=!in_quotes;
1205 s++;
1207 else
1209 /* Preceded by an odd number of '\', this is
1210 * half that number of '\' followed by a '"'
1212 d=d-bcount/2-1;
1213 *d++='"';
1214 s++;
1216 bcount=0;
1218 else
1220 /* a regular character */
1221 *d++=*s++;
1222 bcount=0;
1224 if ((d-szPath) == pathSize)
1226 /* Keep processing the path till we get to the
1227 * arguments, but 'stand still'
1229 d--;
1232 /* Close the application path */
1233 *d=0;
1235 lstrcpynW(szArgs, s, argsSize);
1237 HeapFree( GetProcessHeap(), 0, szCmdline );
1239 LocalFree( dar );
1242 IShellLinkDataList_Release( dl );
1243 return hr;
1246 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1248 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1249 '\\','s','t','a','r','t','.','e','x','e',0};
1250 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1251 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1252 WCHAR szTmp[INFOTIPSIZE];
1253 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1254 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1255 int iIconId = 0, r = -1;
1256 DWORD csidl = -1;
1257 HANDLE hsem = NULL;
1259 if ( !link )
1261 WINE_ERR("Link name is null\n");
1262 return FALSE;
1265 if( !GetLinkLocation( link, &csidl, &link_name ) )
1267 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1268 return TRUE;
1270 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1272 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1273 return TRUE;
1275 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1277 szTmp[0] = 0;
1278 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1279 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1280 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
1282 szTmp[0] = 0;
1283 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1284 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1285 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1287 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1288 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
1289 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
1291 szTmp[0] = 0;
1292 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1293 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1294 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
1296 if( !szPath[0] )
1298 LPITEMIDLIST pidl = NULL;
1299 IShellLinkW_GetIDList( sl, &pidl );
1300 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1301 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
1304 /* extract the icon */
1305 if( szIconPath[0] )
1306 icon_name = extract_icon( szIconPath , iIconId, bWait );
1307 else
1308 icon_name = extract_icon( szPath, iIconId, bWait );
1310 /* fail - try once again after parent process exit */
1311 if( !icon_name )
1313 if (bWait)
1315 WINE_WARN("Unable to extract icon, deferring.\n");
1316 goto cleanup;
1318 WINE_ERR("failed to extract icon from %s\n",
1319 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
1322 /* check the path */
1323 if( szPath[0] )
1325 static const WCHAR exeW[] = {'.','e','x','e',0};
1326 WCHAR *p;
1328 /* check for .exe extension */
1329 if (!(p = strrchrW( szPath, '.' )) ||
1330 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
1331 lstrcmpiW( p, exeW ))
1333 /* Not .exe - use 'start.exe' to launch this file */
1334 p = szArgs + lstrlenW(szPath) + 2;
1335 if (szArgs[0])
1337 p[0] = ' ';
1338 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
1339 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
1341 else
1342 p[0] = 0;
1344 szArgs[0] = '"';
1345 lstrcpyW(szArgs + 1, szPath);
1346 p[-1] = '"';
1348 GetWindowsDirectoryW(szPath, MAX_PATH);
1349 lstrcatW(szPath, startW);
1352 /* convert app working dir */
1353 if (szWorkDir[0])
1354 work_dir = wine_get_unix_file_name( szWorkDir );
1356 else
1358 /* if there's no path... try run the link itself */
1359 lstrcpynW(szArgs, link, MAX_PATH);
1360 GetWindowsDirectoryW(szPath, MAX_PATH);
1361 lstrcatW(szPath, startW);
1364 /* escape the path and parameters */
1365 escaped_path = escape(szPath);
1366 escaped_args = escape(szArgs);
1367 escaped_description = escape(szDescription);
1369 /* building multiple menus concurrently has race conditions */
1370 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1371 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
1373 WINE_ERR("failed wait for semaphore\n");
1374 goto cleanup;
1377 if (in_desktop_dir(csidl))
1379 char *location;
1380 const char *lastEntry;
1381 lastEntry = strrchr(link_name, '/');
1382 if (lastEntry == NULL)
1383 lastEntry = link_name;
1384 else
1385 ++lastEntry;
1386 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
1387 if (location)
1389 r = !write_desktop_entry(location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
1390 HeapFree(GetProcessHeap(), 0, location);
1393 else
1394 r = !write_menu_entry(link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
1396 ReleaseSemaphore( hsem, 1, NULL );
1398 cleanup:
1399 if (hsem) CloseHandle( hsem );
1400 HeapFree( GetProcessHeap(), 0, icon_name );
1401 HeapFree( GetProcessHeap(), 0, work_dir );
1402 HeapFree( GetProcessHeap(), 0, link_name );
1403 HeapFree( GetProcessHeap(), 0, escaped_args );
1404 HeapFree( GetProcessHeap(), 0, escaped_path );
1405 HeapFree( GetProcessHeap(), 0, escaped_description );
1407 if (r && !bWait)
1408 WINE_ERR("failed to build the menu\n" );
1410 return ( r == 0 );
1413 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
1415 char *link_name = NULL;
1416 DWORD csidl = -1;
1417 LPWSTR urlPath;
1418 char *escaped_urlPath = NULL;
1419 HRESULT hr;
1420 HANDLE hSem = NULL;
1421 BOOL ret = TRUE;
1422 int r = -1;
1424 if ( !link )
1426 WINE_ERR("Link name is null\n");
1427 return TRUE;
1430 if( !GetLinkLocation( link, &csidl, &link_name ) )
1432 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1433 return TRUE;
1435 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1437 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1438 ret = TRUE;
1439 goto cleanup;
1441 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1443 hr = url->lpVtbl->GetURL(url, &urlPath);
1444 if (FAILED(hr))
1446 ret = TRUE;
1447 goto cleanup;
1449 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
1451 escaped_urlPath = escape(urlPath);
1453 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1454 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
1456 WINE_ERR("failed wait for semaphore\n");
1457 goto cleanup;
1459 if (in_desktop_dir(csidl))
1461 char *location;
1462 const char *lastEntry;
1463 lastEntry = strrchr(link_name, '/');
1464 if (lastEntry == NULL)
1465 lastEntry = link_name;
1466 else
1467 ++lastEntry;
1468 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
1469 if (location)
1471 r = !write_desktop_entry(location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
1472 HeapFree(GetProcessHeap(), 0, location);
1475 else
1476 r = !write_menu_entry(link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
1477 ret = (r != 0);
1478 ReleaseSemaphore(hSem, 1, NULL);
1480 cleanup:
1481 if (hSem)
1482 CloseHandle(hSem);
1483 HeapFree(GetProcessHeap(), 0, link_name);
1484 CoTaskMemFree( urlPath );
1485 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
1486 return ret;
1489 static BOOL WaitForParentProcess( void )
1491 PROCESSENTRY32 procentry;
1492 HANDLE hsnapshot = NULL, hprocess = NULL;
1493 DWORD ourpid = GetCurrentProcessId();
1494 BOOL ret = FALSE, rc;
1496 WINE_TRACE("Waiting for parent process\n");
1497 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
1498 INVALID_HANDLE_VALUE)
1500 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
1501 goto done;
1504 procentry.dwSize = sizeof(PROCESSENTRY32);
1505 rc = Process32First( hsnapshot, &procentry );
1506 while (rc)
1508 if (procentry.th32ProcessID == ourpid) break;
1509 rc = Process32Next( hsnapshot, &procentry );
1511 if (!rc)
1513 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
1514 goto done;
1517 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
1518 NULL)
1520 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
1521 GetLastError());
1522 goto done;
1525 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
1526 ret = TRUE;
1527 else
1528 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
1530 done:
1531 if (hprocess) CloseHandle( hprocess );
1532 if (hsnapshot) CloseHandle( hsnapshot );
1533 return ret;
1536 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
1538 IShellLinkW *sl;
1539 IPersistFile *pf;
1540 HRESULT r;
1541 WCHAR fullname[MAX_PATH];
1542 DWORD len;
1544 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
1546 if( !linkname[0] )
1548 WINE_ERR("link name missing\n");
1549 return 1;
1552 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1553 if (len==0 || len>MAX_PATH)
1555 WINE_ERR("couldn't get full path of link file\n");
1556 return 1;
1559 r = CoInitialize( NULL );
1560 if( FAILED( r ) )
1562 WINE_ERR("CoInitialize failed\n");
1563 return 1;
1566 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1567 &IID_IShellLinkW, (LPVOID *) &sl );
1568 if( FAILED( r ) )
1570 WINE_ERR("No IID_IShellLink\n");
1571 return 1;
1574 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1575 if( FAILED( r ) )
1577 WINE_ERR("No IID_IPersistFile\n");
1578 return 1;
1581 r = IPersistFile_Load( pf, fullname, STGM_READ );
1582 if( SUCCEEDED( r ) )
1584 /* If something fails (eg. Couldn't extract icon)
1585 * wait for parent process and try again
1587 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
1589 WaitForParentProcess();
1590 InvokeShellLinker( sl, fullname, FALSE );
1593 else
1595 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
1598 IPersistFile_Release( pf );
1599 IShellLinkW_Release( sl );
1601 CoUninitialize();
1603 return !r;
1606 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
1608 IUniformResourceLocatorW *url;
1609 IPersistFile *pf;
1610 HRESULT r;
1611 WCHAR fullname[MAX_PATH];
1612 DWORD len;
1614 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
1616 if( !urlname[0] )
1618 WINE_ERR("URL name missing\n");
1619 return 1;
1622 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
1623 if (len==0 || len>MAX_PATH)
1625 WINE_ERR("couldn't get full path of URL file\n");
1626 return 1;
1629 r = CoInitialize( NULL );
1630 if( FAILED( r ) )
1632 WINE_ERR("CoInitialize failed\n");
1633 return 1;
1636 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
1637 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
1638 if( FAILED( r ) )
1640 WINE_ERR("No IID_IUniformResourceLocatorW\n");
1641 return 1;
1644 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
1645 if( FAILED( r ) )
1647 WINE_ERR("No IID_IPersistFile\n");
1648 return 1;
1650 r = IPersistFile_Load( pf, fullname, STGM_READ );
1651 if( SUCCEEDED( r ) )
1653 /* If something fails (eg. Couldn't extract icon)
1654 * wait for parent process and try again
1656 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
1658 WaitForParentProcess();
1659 InvokeShellLinkerForURL( url, fullname, FALSE );
1663 IPersistFile_Release( pf );
1664 url->lpVtbl->Release( url );
1666 CoUninitialize();
1668 return !r;
1671 static void RefreshFileTypeAssociations(void)
1673 HANDLE hSem = NULL;
1674 char *mime_dir = NULL;
1675 char *packages_dir = NULL;
1676 char *applications_dir = NULL;
1678 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1679 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
1681 WINE_ERR("failed wait for semaphore\n");
1682 CloseHandle(hSem);
1683 hSem = NULL;
1684 goto end;
1687 mime_dir = heap_printf("%s/mime", xdg_data_dir);
1688 if (mime_dir == NULL)
1690 WINE_ERR("out of memory\n");
1691 goto end;
1693 create_directories(mime_dir);
1695 packages_dir = heap_printf("%s/packages", mime_dir);
1696 if (packages_dir == NULL)
1698 WINE_ERR("out of memory\n");
1699 goto end;
1701 create_directories(packages_dir);
1703 applications_dir = heap_printf("%s/applications", xdg_data_dir);
1704 if (applications_dir == NULL)
1706 WINE_ERR("out of memory\n");
1707 goto end;
1709 create_directories(applications_dir);
1711 end:
1712 if (hSem)
1714 ReleaseSemaphore(hSem, 1, NULL);
1715 CloseHandle(hSem);
1717 HeapFree(GetProcessHeap(), 0, mime_dir);
1718 HeapFree(GetProcessHeap(), 0, packages_dir);
1719 HeapFree(GetProcessHeap(), 0, applications_dir);
1722 static CHAR *next_token( LPSTR *p )
1724 LPSTR token = NULL, t = *p;
1726 if( !t )
1727 return NULL;
1729 while( t && !token )
1731 switch( *t )
1733 case ' ':
1734 t++;
1735 continue;
1736 case '"':
1737 /* unquote the token */
1738 token = ++t;
1739 t = strchr( token, '"' );
1740 if( t )
1741 *t++ = 0;
1742 break;
1743 case 0:
1744 t = NULL;
1745 break;
1746 default:
1747 token = t;
1748 t = strchr( token, ' ' );
1749 if( t )
1750 *t++ = 0;
1751 break;
1754 *p = t;
1755 return token;
1758 static BOOL init_xdg(void)
1760 WCHAR shellDesktopPath[MAX_PATH];
1761 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
1762 if (SUCCEEDED(hr))
1763 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
1764 if (xdg_desktop_dir == NULL)
1766 WINE_ERR("error looking up the desktop directory\n");
1767 return FALSE;
1770 if (getenv("XDG_CONFIG_HOME"))
1771 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
1772 else
1773 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
1774 if (xdg_config_dir)
1776 create_directories(xdg_config_dir);
1777 if (getenv("XDG_DATA_HOME"))
1778 xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
1779 else
1780 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
1781 if (xdg_data_dir)
1783 char *buffer;
1784 create_directories(xdg_data_dir);
1785 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
1786 if (buffer)
1788 mkdir(buffer, 0777);
1789 HeapFree(GetProcessHeap(), 0, buffer);
1791 return TRUE;
1793 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
1795 WINE_ERR("out of memory\n");
1796 return FALSE;
1799 /***********************************************************************
1801 * WinMain
1803 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1805 LPSTR token = NULL, p;
1806 BOOL bWait = FALSE;
1807 BOOL bURL = FALSE;
1808 int ret = 0;
1810 if (!init_xdg())
1811 return 1;
1813 for( p = cmdline; p && *p; )
1815 token = next_token( &p );
1816 if( !token )
1817 break;
1818 if( !lstrcmpA( token, "-a" ) )
1820 RefreshFileTypeAssociations();
1821 break;
1823 if( !lstrcmpA( token, "-w" ) )
1824 bWait = TRUE;
1825 else if ( !lstrcmpA( token, "-u" ) )
1826 bURL = TRUE;
1827 else if( token[0] == '-' )
1829 WINE_ERR( "unknown option %s\n",token);
1831 else
1833 WCHAR link[MAX_PATH];
1834 BOOL bRet;
1836 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1837 if (bURL)
1838 bRet = Process_URL( link, bWait );
1839 else
1840 bRet = Process_Link( link, bWait );
1841 if (!bRet)
1843 WINE_ERR( "failed to build menu item for %s\n",token);
1844 ret = 1;
1849 return ret;