push 87b6981010d7405c33b14cddcceec21b47729eba
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blob62165f6a3c9c590b059bbd12788da2373c1bf5e4
1 /*
2 * Helper program to build unix menu entries
4 * Copyright 1997 Marcus Meissner
5 * Copyright 1998 Juergen Schmied
6 * Copyright 2003 Mike McCormack for CodeWeavers
7 * Copyright 2004 Dmitry Timoshkov
8 * Copyright 2005 Bill Medland
9 * Copyright 2008 Damjan Jovanovic
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 * This program is used to replicate the Windows desktop and start menu
27 * into the native desktop's copies. Desktop entries are merged directly
28 * into the native desktop. The Windows Start Menu corresponds to a Wine
29 * entry within the native "start" menu and replicates the whole tree
30 * structure of the Windows Start Menu. Currently it does not differentiate
31 * between the user's desktop/start menu and the "All Users" copies.
33 * This program will read a Windows shortcut file using the IShellLink
34 * interface, then create a KDE/Gnome menu entry for the shortcut.
36 * winemenubuilder [ -w ] <shortcut.lnk>
38 * If the -w parameter is passed, and the shortcut cannot be created,
39 * this program will wait for the parent process to finish and then try
40 * again. This covers the case when a ShortCut is created before the
41 * executable containing its icon.
43 * TODO
44 * Handle data lnk files. There is no icon in the file; the icon is in
45 * the handler for the file type (or pointed to by the lnk file). Also it
46 * might be better to use a native handler (e.g. a native acroread for pdf
47 * files).
48 * Differentiate between the user's entries and the "All Users" entries.
49 * If it is possible to add the desktop files to the native system's
50 * shared location for an "All Users" entry then do so. As a suggestion the
51 * shared menu Wine base could be writable to the wine group, or a wineadm
52 * group.
53 * Clean up fd.o menu icons and .directory files when the menu is deleted
54 * in Windows.
55 * Generate icons for file open handlers to go into the "Open with..."
56 * list. What does Windows use, the default icon for the .EXE file? It's
57 * not in the registry.
58 * Associate applications under HKCR\Applications to open any MIME type
59 * (by associating with application/octet-stream, or how?).
60 * Clean up fd.o MIME types when they are deleted in Windows, their icons
61 * too. Very hard - once we associate them with fd.o, we can't tell whether
62 * they are ours or not, and the extension <-> MIME type mapping isn't
63 * one-to-one either.
64 * Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
65 * that write associations there won't associate (#17019).
68 #include "config.h"
69 #include "wine/port.h"
71 #include <ctype.h>
72 #include <stdio.h>
73 #include <string.h>
74 #ifdef HAVE_UNISTD_H
75 #include <unistd.h>
76 #endif
77 #include <errno.h>
78 #include <stdarg.h>
79 #ifdef HAVE_FNMATCH_H
80 #include <fnmatch.h>
81 #endif
83 #define COBJMACROS
85 #include <windows.h>
86 #include <shlobj.h>
87 #include <objidl.h>
88 #include <shlguid.h>
89 #include <appmgmt.h>
90 #include <tlhelp32.h>
91 #include <intshcut.h>
92 #include <shlwapi.h>
94 #include "wine/unicode.h"
95 #include "wine/debug.h"
96 #include "wine/library.h"
97 #include "wine/list.h"
98 #include "wine.xpm"
100 #ifdef HAVE_PNG_H
101 #undef FAR
102 #include <png.h>
103 #endif
105 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
107 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
108 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
109 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
110 (csidl)==CSIDL_COMMON_STARTMENU)
112 /* link file formats */
114 #include "pshpack1.h"
116 typedef struct
118 BYTE bWidth;
119 BYTE bHeight;
120 BYTE bColorCount;
121 BYTE bReserved;
122 WORD wPlanes;
123 WORD wBitCount;
124 DWORD dwBytesInRes;
125 WORD nID;
126 } GRPICONDIRENTRY;
128 typedef struct
130 WORD idReserved;
131 WORD idType;
132 WORD idCount;
133 GRPICONDIRENTRY idEntries[1];
134 } GRPICONDIR;
136 typedef struct
138 BYTE bWidth;
139 BYTE bHeight;
140 BYTE bColorCount;
141 BYTE bReserved;
142 WORD wPlanes;
143 WORD wBitCount;
144 DWORD dwBytesInRes;
145 DWORD dwImageOffset;
146 } ICONDIRENTRY;
148 typedef struct
150 WORD idReserved;
151 WORD idType;
152 WORD idCount;
153 } ICONDIR;
156 #include "poppack.h"
158 typedef struct
160 HRSRC *pResInfo;
161 int nIndex;
162 } ENUMRESSTRUCT;
164 struct xdg_mime_type
166 char *mimeType;
167 char *glob;
168 struct list entry;
171 static char *xdg_config_dir;
172 static char *xdg_data_dir;
173 static char *xdg_desktop_dir;
175 /* Icon extraction routines
177 * FIXME: should use PrivateExtractIcons and friends
178 * FIXME: should not use stdio
181 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
183 /* PNG-specific code */
184 #ifdef SONAME_LIBPNG
186 static void *libpng_handle;
187 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
188 MAKE_FUNCPTR(png_create_info_struct);
189 MAKE_FUNCPTR(png_create_write_struct);
190 MAKE_FUNCPTR(png_destroy_write_struct);
191 MAKE_FUNCPTR(png_get_error_ptr);
192 MAKE_FUNCPTR(png_init_io);
193 MAKE_FUNCPTR(png_set_bgr);
194 MAKE_FUNCPTR(png_set_error_fn);
195 MAKE_FUNCPTR(png_set_text);
196 MAKE_FUNCPTR(png_set_IHDR);
197 MAKE_FUNCPTR(png_write_end);
198 MAKE_FUNCPTR(png_write_info);
199 MAKE_FUNCPTR(png_write_row);
200 #undef MAKE_FUNCPTR
202 static void *load_libpng(void)
204 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
206 #define LOAD_FUNCPTR(f) \
207 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
208 libpng_handle = NULL; \
209 return NULL; \
211 LOAD_FUNCPTR(png_create_info_struct);
212 LOAD_FUNCPTR(png_create_write_struct);
213 LOAD_FUNCPTR(png_destroy_write_struct);
214 LOAD_FUNCPTR(png_get_error_ptr);
215 LOAD_FUNCPTR(png_init_io);
216 LOAD_FUNCPTR(png_set_bgr);
217 LOAD_FUNCPTR(png_set_error_fn);
218 LOAD_FUNCPTR(png_set_IHDR);
219 LOAD_FUNCPTR(png_set_text);
220 LOAD_FUNCPTR(png_write_end);
221 LOAD_FUNCPTR(png_write_info);
222 LOAD_FUNCPTR(png_write_row);
223 #undef LOAD_FUNCPTR
225 return libpng_handle;
228 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
230 jmp_buf *pjmpbuf;
232 /* This uses setjmp/longjmp just like the default. We can't use the
233 * default because there's no way to access the jmp buffer in the png_struct
234 * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
235 WINE_ERR("PNG error: %s\n", wine_dbgstr_an(error_message, -1));
236 pjmpbuf = ppng_get_error_ptr(png_ptr);
237 longjmp(*pjmpbuf, 1);
240 static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
242 WINE_WARN("PNG warning: %s\n", wine_dbgstr_an(warning_message, -1));
245 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
247 static const char comment_key[] = "Created from";
248 FILE *fp;
249 png_structp png_ptr;
250 png_infop info_ptr;
251 png_text comment;
252 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
253 BYTE *row, *copy = NULL;
254 const BYTE *pXOR, *pAND = NULL;
255 int nWidth = pIcon->bmiHeader.biWidth;
256 int nHeight = pIcon->bmiHeader.biHeight;
257 int nBpp = pIcon->bmiHeader.biBitCount;
258 jmp_buf jmpbuf;
260 switch (nBpp)
262 case 32:
263 color_type |= PNG_COLOR_MASK_ALPHA;
264 /* fall through */
265 case 24:
266 color_type |= PNG_COLOR_MASK_COLOR;
267 break;
268 default:
269 return FALSE;
272 if (!libpng_handle && !load_libpng())
274 WINE_WARN("Unable to load libpng\n");
275 return FALSE;
278 if (!(fp = fopen(png_filename, "w")))
280 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
281 return FALSE;
284 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
285 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
286 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
287 if (nHeight > nWidth)
289 nHeight /= 2;
290 pAND = pXOR + nHeight * nXORWidthBytes;
293 /* Apply mask if present */
294 if (pAND)
296 RGBQUAD bgColor;
298 /* copy bytes before modifying them */
299 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
300 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
301 pXOR = copy;
303 /* image and mask are upside down reversed */
304 row = copy + (nHeight - 1) * nXORWidthBytes;
306 /* top left corner */
307 bgColor.rgbRed = row[0];
308 bgColor.rgbGreen = row[1];
309 bgColor.rgbBlue = row[2];
310 bgColor.rgbReserved = 0;
312 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
313 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
314 if (MASK(j, i))
316 RGBQUAD *pixel = (RGBQUAD *)row;
317 pixel->rgbBlue = bgColor.rgbBlue;
318 pixel->rgbGreen = bgColor.rgbGreen;
319 pixel->rgbRed = bgColor.rgbRed;
320 if (nBpp == 32)
321 pixel->rgbReserved = bgColor.rgbReserved;
325 comment.text = NULL;
327 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
328 !(info_ptr = ppng_create_info_struct(png_ptr)))
329 goto error;
331 if (setjmp(jmpbuf))
333 /* All future errors jump here */
334 goto error;
336 ppng_set_error_fn(png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
338 ppng_init_io(png_ptr, fp);
339 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
340 color_type,
341 PNG_INTERLACE_NONE,
342 PNG_COMPRESSION_TYPE_DEFAULT,
343 PNG_FILTER_TYPE_DEFAULT);
345 /* Set comment */
346 comment.compression = PNG_TEXT_COMPRESSION_NONE;
347 comment.key = (png_charp)comment_key;
348 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
349 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
350 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
351 comment.text_length = i - 1;
352 ppng_set_text(png_ptr, info_ptr, &comment, 1);
355 ppng_write_info(png_ptr, info_ptr);
356 ppng_set_bgr(png_ptr);
357 for (i = nHeight - 1; i >= 0 ; i--)
358 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
359 ppng_write_end(png_ptr, info_ptr);
361 ppng_destroy_write_struct(&png_ptr, &info_ptr);
362 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
363 fclose(fp);
364 HeapFree(GetProcessHeap(), 0, copy);
365 HeapFree(GetProcessHeap(), 0, comment.text);
366 return TRUE;
368 error:
369 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
370 fclose(fp);
371 unlink(png_filename);
372 HeapFree(GetProcessHeap(), 0, copy);
373 HeapFree(GetProcessHeap(), 0, comment.text);
374 return FALSE;
376 #endif /* SONAME_LIBPNG */
378 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
380 FILE *fXPMFile;
381 int nHeight;
382 int nXORWidthBytes;
383 int nANDWidthBytes;
384 BOOL b8BitColors;
385 int nColors;
386 const BYTE *pXOR;
387 const BYTE *pAND;
388 BOOL aColorUsed[256] = {0};
389 int nColorsUsed = 0;
390 int i,j;
391 char *comment;
393 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
395 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
396 return FALSE;
399 if (!(fXPMFile = fopen(szXPMFileName, "w")))
401 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
402 return FALSE;
405 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
406 comment = HeapAlloc(GetProcessHeap(), 0, i);
407 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
409 nHeight = pIcon->bmiHeader.biHeight / 2;
410 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
411 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
412 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
413 + ((pIcon->bmiHeader.biWidth % 32) > 0));
414 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
415 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
416 : 1 << pIcon->bmiHeader.biBitCount;
417 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
418 pAND = pXOR + nHeight * nXORWidthBytes;
420 #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)
422 for (i = 0; i < nHeight; i++) {
423 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
424 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
426 aColorUsed[COLOR(j,i)] = TRUE;
427 nColorsUsed++;
432 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
433 goto error;
434 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
435 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
436 goto error;
438 for (i = 0; i < nColors; i++) {
439 if (aColorUsed[i])
440 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
441 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
442 goto error;
444 if (fprintf(fXPMFile, "\" c None\"") <= 0)
445 goto error;
447 for (i = 0; i < nHeight; i++)
449 if (fprintf(fXPMFile, ",\n\"") <= 0)
450 goto error;
451 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
453 if MASK(j,i)
455 if (fprintf(fXPMFile, " ") <= 0)
456 goto error;
458 else
459 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
460 goto error;
462 if (fprintf(fXPMFile, "\"") <= 0)
463 goto error;
465 if (fprintf(fXPMFile, "};\n") <= 0)
466 goto error;
468 #undef MASK
469 #undef COLOR
471 HeapFree(GetProcessHeap(), 0, comment);
472 fclose(fXPMFile);
473 return TRUE;
475 error:
476 HeapFree(GetProcessHeap(), 0, comment);
477 fclose(fXPMFile);
478 unlink( szXPMFileName );
479 return FALSE;
482 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
484 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
486 if (!sEnumRes->nIndex--)
488 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
489 return FALSE;
491 else
492 return TRUE;
495 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
497 HMODULE hModule;
498 HRSRC hResInfo;
499 LPCWSTR lpName = NULL;
500 HGLOBAL hResData;
501 GRPICONDIR *pIconDir;
502 BITMAPINFO *pIcon;
503 ENUMRESSTRUCT sEnumRes;
504 int nMax = 0;
505 int nMaxBits = 0;
506 int i;
507 BOOL ret = FALSE;
509 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
510 if (!hModule)
512 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
513 wine_dbgstr_w(szFileName), GetLastError());
514 return FALSE;
517 if (nIndex < 0)
519 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
520 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
521 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
523 else
525 hResInfo=NULL;
526 sEnumRes.pResInfo = &hResInfo;
527 sEnumRes.nIndex = nIndex;
528 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
529 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
530 sEnumRes.nIndex != -1)
532 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
536 if (hResInfo)
538 if ((hResData = LoadResource(hModule, hResInfo)))
540 if ((pIconDir = LockResource(hResData)))
542 for (i = 0; i < pIconDir->idCount; i++)
544 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
546 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
548 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
549 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
550 nMaxBits = pIconDir->idEntries[i].wBitCount;
556 FreeResource(hResData);
559 else
561 WINE_WARN("found no icon\n");
562 FreeLibrary(hModule);
563 return FALSE;
566 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
568 if ((hResData = LoadResource(hModule, hResInfo)))
570 if ((pIcon = LockResource(hResData)))
572 #ifdef SONAME_LIBPNG
573 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
574 ret = TRUE;
575 else
576 #endif
578 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
579 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
580 ret = TRUE;
584 FreeResource(hResData);
588 FreeLibrary(hModule);
589 return ret;
592 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
594 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
595 !extract_icon16(szFileName, szXPMFileName)*/)
596 return FALSE;
597 return TRUE;
600 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
602 FILE *fICOFile = NULL;
603 ICONDIR iconDir;
604 ICONDIRENTRY *pIconDirEntry = NULL;
605 int nMax = 0, nMaxBits = 0;
606 int nIndex = 0;
607 void *pIcon = NULL;
608 int i;
609 char *filename = NULL;
611 filename = wine_get_unix_file_name(szFileName);
612 if (!(fICOFile = fopen(filename, "r")))
614 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
615 goto error;
618 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
619 (iconDir.idReserved != 0) || (iconDir.idType != 1))
621 WINE_WARN("Invalid ico file format\n");
622 goto error;
625 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
626 goto error;
627 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
628 goto error;
630 for (i = 0; i < iconDir.idCount; i++)
632 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
633 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
634 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
636 nIndex = i;
637 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
638 nMaxBits = pIconDirEntry[i].wBitCount;
641 WINE_TRACE("Selected: %d\n", nIndex);
643 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
644 goto error;
645 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
646 goto error;
647 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
648 goto error;
651 /* Prefer PNG over XPM */
652 #ifdef SONAME_LIBPNG
653 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
654 #endif
656 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
657 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
658 goto error;
661 HeapFree(GetProcessHeap(), 0, pIcon);
662 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
663 fclose(fICOFile);
664 HeapFree(GetProcessHeap(), 0, filename);
665 return 1;
667 error:
668 HeapFree(GetProcessHeap(), 0, pIcon);
669 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
670 if (fICOFile) fclose(fICOFile);
671 HeapFree(GetProcessHeap(), 0, filename);
672 return 0;
675 static BOOL create_default_icon( const char *filename, const char* comment )
677 FILE *fXPM;
678 unsigned int i;
680 if (!(fXPM = fopen(filename, "w"))) return FALSE;
681 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
682 goto error;
683 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
684 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
685 goto error;
687 if (fprintf( fXPM, "};\n" ) <=0)
688 goto error;
689 fclose( fXPM );
690 return TRUE;
691 error:
692 fclose( fXPM );
693 unlink( filename );
694 return FALSE;
698 static unsigned short crc16(const char* string)
700 unsigned short crc = 0;
701 int i, j, xor_poly;
703 for (i = 0; string[i] != 0; i++)
705 char c = string[i];
706 for (j = 0; j < 8; c >>= 1, j++)
708 xor_poly = (c ^ crc) & 1;
709 crc >>= 1;
710 if (xor_poly)
711 crc ^= 0xa001;
714 return crc;
717 static char *strdupA( const char *str )
719 char *ret;
721 if (!str) return NULL;
722 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
723 return ret;
726 static char* heap_printf(const char *format, ...)
728 va_list args;
729 int size = 4096;
730 char *buffer, *ret;
731 int n;
733 va_start(args, format);
734 while (1)
736 buffer = HeapAlloc(GetProcessHeap(), 0, size);
737 if (buffer == NULL)
738 break;
739 n = vsnprintf(buffer, size, format, args);
740 if (n == -1)
741 size *= 2;
742 else if (n >= size)
743 size = n + 1;
744 else
745 break;
746 HeapFree(GetProcessHeap(), 0, buffer);
748 va_end(args);
749 if (!buffer) return NULL;
750 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
751 if (!ret) ret = buffer;
752 return ret;
755 static void write_xml_text(FILE *file, const char *text)
757 int i;
758 for (i = 0; text[i]; i++)
760 if (text[i] == '&')
761 fputs("&amp;", file);
762 else if (text[i] == '<')
763 fputs("&lt;", file);
764 else if (text[i] == '>')
765 fputs("&gt;", file);
766 else if (text[i] == '\'')
767 fputs("&apos;", file);
768 else if (text[i] == '"')
769 fputs("&quot;", file);
770 else
771 fputc(text[i], file);
775 static BOOL create_directories(char *directory)
777 BOOL ret = TRUE;
778 int i;
780 for (i = 0; directory[i]; i++)
782 if (i > 0 && directory[i] == '/')
784 directory[i] = 0;
785 mkdir(directory, 0777);
786 directory[i] = '/';
789 if (mkdir(directory, 0777) && errno != EEXIST)
790 ret = FALSE;
792 return ret;
795 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
796 static char *extract_icon( LPCWSTR path, int index, const char *destFilename, BOOL bWait )
798 unsigned short crc;
799 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
800 char* s;
801 int n;
803 /* Where should we save the icon? */
804 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
805 iconsdir = heap_printf("%s/icons", xdg_data_dir);
806 if (iconsdir)
808 if (mkdir(iconsdir, 0777) && errno != EEXIST)
810 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
811 goto end;
814 else
816 WINE_TRACE("no icon created\n");
817 return NULL;
820 /* Determine the icon base name */
821 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
822 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
823 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
824 s=ico_name=ico_path;
825 while (*s!='\0') {
826 if (*s=='/' || *s=='\\') {
827 *s='\\';
828 ico_name=s;
829 } else {
830 *s=tolower(*s);
832 s++;
834 if (*ico_name=='\\') *ico_name++='\0';
835 s=strrchr(ico_name,'.');
836 if (s) *s='\0';
838 /* Compute the source-path hash */
839 crc=crc16(ico_path);
841 /* Try to treat the source file as an exe */
842 if (destFilename)
843 xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
844 else
845 xpm_path=heap_printf("%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
846 if (xpm_path == NULL)
848 WINE_ERR("could not extract icon %s, out of memory\n", wine_dbgstr_a(ico_name));
849 return NULL;
852 if (ExtractFromEXEDLL( path, index, xpm_path ))
853 goto end;
855 /* Must be something else, ignore the index in that case */
856 if (destFilename)
857 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
858 else
859 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
860 if (ExtractFromICO( path, xpm_path))
861 goto end;
862 if (!bWait)
864 if (destFilename)
865 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
866 else
867 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
868 if (create_default_icon( xpm_path, ico_path ))
869 goto end;
872 HeapFree( GetProcessHeap(), 0, xpm_path );
873 xpm_path=NULL;
875 end:
876 HeapFree(GetProcessHeap(), 0, iconsdir);
877 HeapFree(GetProcessHeap(), 0, ico_path);
878 return xpm_path;
881 static HKEY open_menus_reg_key(void)
883 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
884 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
885 HKEY assocKey;
886 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
887 return assocKey;
888 return NULL;
891 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
892 const char *path, const char *args, const char *descr,
893 const char *workdir, const char *icon)
895 FILE *file;
897 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
898 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
899 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
901 file = fopen(location, "w");
902 if (file == NULL)
903 return FALSE;
905 fprintf(file, "[Desktop Entry]\n");
906 fprintf(file, "Name=%s\n", linkname);
907 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
908 wine_get_config_dir(), path, args);
909 fprintf(file, "Type=Application\n");
910 fprintf(file, "StartupNotify=true\n");
911 if (descr && lstrlenA(descr))
912 fprintf(file, "Comment=%s\n", descr);
913 if (workdir && lstrlenA(workdir))
914 fprintf(file, "Path=%s\n", workdir);
915 if (icon && lstrlenA(icon))
916 fprintf(file, "Icon=%s\n", icon);
918 fclose(file);
920 if (unix_link)
922 HKEY hkey = open_menus_reg_key();
923 if (hkey)
925 RegSetValueExA(hkey, location, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
926 RegCloseKey(hkey);
928 else
929 return FALSE;
932 return TRUE;
935 static BOOL write_directory_entry(const char *directory, const char *location)
937 FILE *file;
939 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
941 file = fopen(location, "w");
942 if (file == NULL)
943 return FALSE;
945 fprintf(file, "[Desktop Entry]\n");
946 fprintf(file, "Type=Directory\n");
947 if (strcmp(directory, "wine") == 0)
949 fprintf(file, "Name=Wine\n");
950 fprintf(file, "Icon=wine\n");
952 else
954 fprintf(file, "Name=%s\n", directory);
955 fprintf(file, "Icon=folder\n");
958 fclose(file);
959 return TRUE;
962 static BOOL write_menu_file(const char *unix_link, const char *filename)
964 char *tempfilename;
965 FILE *tempfile = NULL;
966 char *lastEntry;
967 char *name = NULL;
968 char *menuPath = NULL;
969 int i;
970 int count = 0;
971 BOOL ret = FALSE;
973 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
975 while (1)
977 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
978 if (tempfilename)
980 int tempfd = mkstemps(tempfilename, 0);
981 if (tempfd >= 0)
983 tempfile = fdopen(tempfd, "w");
984 if (tempfile)
985 break;
986 close(tempfd);
987 goto end;
989 else if (errno == EEXIST)
991 HeapFree(GetProcessHeap(), 0, tempfilename);
992 continue;
994 HeapFree(GetProcessHeap(), 0, tempfilename);
996 return FALSE;
999 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1000 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1001 fprintf(tempfile, "<Menu>\n");
1002 fprintf(tempfile, " <Name>Applications</Name>\n");
1004 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1005 if (name == NULL) goto end;
1006 lastEntry = name;
1007 for (i = 0; filename[i]; i++)
1009 name[i] = filename[i];
1010 if (filename[i] == '/')
1012 char *dir_file_name;
1013 struct stat st;
1014 name[i] = 0;
1015 fprintf(tempfile, " <Menu>\n");
1016 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1017 write_xml_text(tempfile, name);
1018 fprintf(tempfile, "</Name>\n");
1019 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1020 write_xml_text(tempfile, name);
1021 fprintf(tempfile, ".directory</Directory>\n");
1022 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1023 xdg_data_dir, count ? "" : "wine-", name);
1024 if (dir_file_name)
1026 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1027 write_directory_entry(lastEntry, dir_file_name);
1028 HeapFree(GetProcessHeap(), 0, dir_file_name);
1030 name[i] = '-';
1031 lastEntry = &name[i+1];
1032 ++count;
1035 name[i] = 0;
1037 fprintf(tempfile, " <Include>\n");
1038 fprintf(tempfile, " <Filename>");
1039 write_xml_text(tempfile, name);
1040 fprintf(tempfile, "</Filename>\n");
1041 fprintf(tempfile, " </Include>\n");
1042 for (i = 0; i < count; i++)
1043 fprintf(tempfile, " </Menu>\n");
1044 fprintf(tempfile, "</Menu>\n");
1046 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1047 if (menuPath == NULL) goto end;
1048 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1049 ret = TRUE;
1051 end:
1052 if (tempfile)
1053 fclose(tempfile);
1054 if (ret)
1055 ret = (rename(tempfilename, menuPath) == 0);
1056 if (!ret && tempfilename)
1057 remove(tempfilename);
1058 HeapFree(GetProcessHeap(), 0, tempfilename);
1059 if (ret)
1061 HKEY hkey = open_menus_reg_key();
1062 if (hkey)
1064 RegSetValueExA(hkey, menuPath, 0, REG_SZ, (BYTE*) unix_link, lstrlenA(unix_link) + 1);
1065 RegCloseKey(hkey);
1068 HeapFree(GetProcessHeap(), 0, name);
1069 HeapFree(GetProcessHeap(), 0, menuPath);
1070 return ret;
1073 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1074 const char *descr, const char *workdir, const char *icon)
1076 const char *linkname;
1077 char *desktopPath = NULL;
1078 char *desktopDir;
1079 char *filename = NULL;
1080 BOOL ret = TRUE;
1082 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1083 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1084 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1086 linkname = strrchr(link, '/');
1087 if (linkname == NULL)
1088 linkname = link;
1089 else
1090 ++linkname;
1092 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1093 if (!desktopPath)
1095 WINE_WARN("out of memory creating menu entry\n");
1096 ret = FALSE;
1097 goto end;
1099 desktopDir = strrchr(desktopPath, '/');
1100 *desktopDir = 0;
1101 if (!create_directories(desktopPath))
1103 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1104 ret = FALSE;
1105 goto end;
1107 *desktopDir = '/';
1108 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1110 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1111 ret = FALSE;
1112 goto end;
1115 filename = heap_printf("wine/%s.desktop", link);
1116 if (!filename || !write_menu_file(unix_link, filename))
1118 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1119 ret = FALSE;
1122 end:
1123 HeapFree(GetProcessHeap(), 0, desktopPath);
1124 HeapFree(GetProcessHeap(), 0, filename);
1125 return ret;
1128 /* This escapes \ in filenames */
1129 static LPSTR escape(LPCWSTR arg)
1131 LPSTR narg, x;
1132 LPCWSTR esc;
1133 int len = 0, n;
1135 esc = arg;
1136 while((esc = strchrW(esc, '\\')))
1138 esc++;
1139 len++;
1142 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1143 narg = HeapAlloc(GetProcessHeap(), 0, len);
1145 x = narg;
1146 while (*arg)
1148 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1149 x += n;
1150 len -= n;
1151 if (*arg == '\\')
1152 *x++='\\'; /* escape \ */
1153 arg++;
1155 *x = 0;
1156 return narg;
1159 /* Return a heap-allocated copy of the unix format difference between the two
1160 * Windows-format paths.
1161 * locn is the owning location
1162 * link is within locn
1164 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1166 char *unix_locn, *unix_link;
1167 char *relative = NULL;
1169 unix_locn = wine_get_unix_file_name(locn);
1170 unix_link = wine_get_unix_file_name(link);
1171 if (unix_locn && unix_link)
1173 size_t len_unix_locn, len_unix_link;
1174 len_unix_locn = strlen (unix_locn);
1175 len_unix_link = strlen (unix_link);
1176 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1178 size_t len_rel;
1179 char *p = strrchr (unix_link + len_unix_locn, '/');
1180 p = strrchr (p, '.');
1181 if (p)
1183 *p = '\0';
1184 len_unix_link = p - unix_link;
1186 len_rel = len_unix_link - len_unix_locn;
1187 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1188 if (relative)
1190 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1194 if (!relative)
1195 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1196 HeapFree(GetProcessHeap(), 0, unix_locn);
1197 HeapFree(GetProcessHeap(), 0, unix_link);
1198 return relative;
1201 /***********************************************************************
1203 * GetLinkLocation
1205 * returns TRUE if successful
1206 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1207 * *relative will contain the address of a heap-allocated copy of the portion
1208 * of the filename that is within the specified location, in unix form
1210 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1212 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1213 DWORD len, i, r, filelen;
1214 const DWORD locations[] = {
1215 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1216 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1217 CSIDL_COMMON_STARTMENU };
1219 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1220 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1221 if (filelen==0 || filelen>MAX_PATH)
1222 return FALSE;
1224 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1226 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1227 * expand or our hardcoded list won't match.
1229 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1230 if (filelen==0 || filelen>MAX_PATH)
1231 return FALSE;
1233 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1235 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1237 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1238 continue;
1240 len = lstrlenW(buffer);
1241 if (len >= MAX_PATH)
1242 continue; /* We've just trashed memory! Hopefully we are OK */
1244 if (len > filelen || filename[len]!='\\')
1245 continue;
1246 /* do a lstrcmpinW */
1247 filename[len] = 0;
1248 r = lstrcmpiW( filename, buffer );
1249 filename[len] = '\\';
1250 if ( r )
1251 continue;
1253 /* return the remainder of the string and link type */
1254 *loc = locations[i];
1255 *relative = relative_path (filename, buffer);
1256 return (*relative != NULL);
1259 return FALSE;
1262 /* gets the target path directly or through MSI */
1263 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1264 LPWSTR szArgs, DWORD argsSize)
1266 IShellLinkDataList *dl = NULL;
1267 EXP_DARWIN_LINK *dar = NULL;
1268 HRESULT hr;
1270 szPath[0] = 0;
1271 szArgs[0] = 0;
1273 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1274 if (hr == S_OK && szPath[0])
1276 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1277 return hr;
1280 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1281 if (FAILED(hr))
1282 return hr;
1284 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1285 if (SUCCEEDED(hr))
1287 WCHAR* szCmdline;
1288 DWORD cmdSize;
1290 cmdSize=0;
1291 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1292 if (hr == ERROR_SUCCESS)
1294 cmdSize++;
1295 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1296 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1297 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1298 if (hr == ERROR_SUCCESS)
1300 WCHAR *s, *d;
1301 int bcount, in_quotes;
1303 /* Extract the application path */
1304 bcount=0;
1305 in_quotes=0;
1306 s=szCmdline;
1307 d=szPath;
1308 while (*s)
1310 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1312 /* skip the remaining spaces */
1313 do {
1314 s++;
1315 } while (*s==0x0009 || *s==0x0020);
1316 break;
1318 else if (*s==0x005c)
1320 /* '\\' */
1321 *d++=*s++;
1322 bcount++;
1324 else if (*s==0x0022)
1326 /* '"' */
1327 if ((bcount & 1)==0)
1329 /* Preceded by an even number of '\', this is
1330 * half that number of '\', plus a quote which
1331 * we erase.
1333 d-=bcount/2;
1334 in_quotes=!in_quotes;
1335 s++;
1337 else
1339 /* Preceded by an odd number of '\', this is
1340 * half that number of '\' followed by a '"'
1342 d=d-bcount/2-1;
1343 *d++='"';
1344 s++;
1346 bcount=0;
1348 else
1350 /* a regular character */
1351 *d++=*s++;
1352 bcount=0;
1354 if ((d-szPath) == pathSize)
1356 /* Keep processing the path till we get to the
1357 * arguments, but 'stand still'
1359 d--;
1362 /* Close the application path */
1363 *d=0;
1365 lstrcpynW(szArgs, s, argsSize);
1367 HeapFree( GetProcessHeap(), 0, szCmdline );
1369 LocalFree( dar );
1372 IShellLinkDataList_Release( dl );
1373 return hr;
1376 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1378 HRESULT hr;
1379 WCHAR *value = NULL;
1380 DWORD size = 0;
1381 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1382 if (SUCCEEDED(hr))
1384 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1385 if (value)
1387 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1388 if (FAILED(hr))
1390 HeapFree(GetProcessHeap(), 0, value);
1391 value = NULL;
1395 return value;
1398 static char* wchars_to_utf8_chars(LPCWSTR string)
1400 char *ret;
1401 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
1402 ret = HeapAlloc(GetProcessHeap(), 0, size);
1403 if (ret)
1404 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
1405 return ret;
1408 static char *slashes_to_minuses(const char *string)
1410 int i;
1411 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1412 if (ret)
1414 for (i = 0; string[i]; i++)
1416 if (string[i] == '/')
1417 ret[i] = '-';
1418 else
1419 ret[i] = string[i];
1421 ret[i] = 0;
1422 return ret;
1424 return NULL;
1427 static BOOL next_line(FILE *file, char **line, int *size)
1429 int pos = 0;
1430 char *cr;
1431 if (*line == NULL)
1433 *size = 4096;
1434 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1436 while (*line != NULL)
1438 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1440 HeapFree(GetProcessHeap(), 0, *line);
1441 *line = NULL;
1442 if (feof(file))
1443 return TRUE;
1444 return FALSE;
1446 pos = strlen(*line);
1447 cr = strchr(*line, '\n');
1448 if (cr == NULL)
1450 char *line2;
1451 (*size) *= 2;
1452 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1453 if (line2)
1454 *line = line2;
1455 else
1457 HeapFree(GetProcessHeap(), 0, *line);
1458 *line = NULL;
1461 else
1463 *cr = 0;
1464 return TRUE;
1467 return FALSE;
1470 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1472 char *globs_filename = NULL;
1473 BOOL ret = TRUE;
1474 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1475 if (globs_filename)
1477 FILE *globs_file = fopen(globs_filename, "r");
1478 if (globs_file) /* doesn't have to exist */
1480 char *line = NULL;
1481 int size = 0;
1482 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1484 char *pos;
1485 struct xdg_mime_type *mime_type_entry = NULL;
1486 if (line[0] != '#' && (pos = strchr(line, ':')))
1488 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1489 if (mime_type_entry)
1491 *pos = 0;
1492 mime_type_entry->mimeType = strdupA(line);
1493 mime_type_entry->glob = strdupA(pos + 1);
1494 if (mime_type_entry->mimeType && mime_type_entry->glob)
1495 list_add_tail(mime_types, &mime_type_entry->entry);
1496 else
1498 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1499 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1500 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1501 ret = FALSE;
1504 else
1505 ret = FALSE;
1508 HeapFree(GetProcessHeap(), 0, line);
1509 fclose(globs_file);
1511 HeapFree(GetProcessHeap(), 0, globs_filename);
1513 else
1514 ret = FALSE;
1515 return ret;
1518 static void free_native_mime_types(struct list *native_mime_types)
1520 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1522 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1524 list_remove(&mime_type_entry->entry);
1525 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1526 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1527 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1529 HeapFree(GetProcessHeap(), 0, native_mime_types);
1532 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1534 char *xdg_data_dirs;
1535 BOOL ret;
1537 *mime_types = NULL;
1539 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1540 if (xdg_data_dirs == NULL)
1541 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1542 else
1543 xdg_data_dirs = strdupA(xdg_data_dirs);
1545 if (xdg_data_dirs)
1547 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1548 if (*mime_types)
1550 const char *begin;
1551 char *end;
1553 list_init(*mime_types);
1554 ret = add_mimes(xdg_data_home, *mime_types);
1555 if (ret)
1557 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1559 *end = '\0';
1560 ret = add_mimes(begin, *mime_types);
1561 *end = ':';
1562 if (!ret)
1563 break;
1565 if (ret)
1566 ret = add_mimes(begin, *mime_types);
1569 else
1570 ret = FALSE;
1571 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1573 else
1574 ret = FALSE;
1575 if (!ret && *mime_types)
1577 free_native_mime_types(*mime_types);
1578 *mime_types = NULL;
1580 return ret;
1583 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1584 char **match)
1586 #ifdef HAVE_FNMATCH
1587 struct xdg_mime_type *mime_type_entry;
1588 int matchLength = 0;
1590 *match = NULL;
1592 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1594 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1596 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1598 *match = mime_type_entry->mimeType;
1599 matchLength = strlen(mime_type_entry->glob);
1604 if (*match != NULL)
1606 *match = strdupA(*match);
1607 if (*match == NULL)
1608 return FALSE;
1610 #else
1611 *match = NULL;
1612 #endif
1613 return TRUE;
1616 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1617 const char *extensionA,
1618 LPCWSTR extensionW,
1619 char **mime_type)
1621 WCHAR *lower_extensionW;
1622 INT len;
1623 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1624 if (ret == FALSE || *mime_type != NULL)
1625 return ret;
1626 len = strlenW(extensionW);
1627 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1628 if (lower_extensionW)
1630 char *lower_extensionA;
1631 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1632 strlwrW(lower_extensionW);
1633 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1634 if (lower_extensionA)
1636 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1637 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1639 else
1641 ret = FALSE;
1642 WINE_FIXME("out of memory\n");
1644 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1646 else
1648 ret = FALSE;
1649 WINE_FIXME("out of memory\n");
1651 return ret;
1654 static CHAR* reg_get_valA(HKEY key, LPCSTR subkey, LPCSTR name)
1656 DWORD size;
1657 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1659 CHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1660 if (ret)
1662 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1663 return ret;
1665 HeapFree(GetProcessHeap(), 0, ret);
1667 return NULL;
1670 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1672 DWORD size;
1673 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1675 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1676 if (ret)
1678 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1679 return ret;
1681 HeapFree(GetProcessHeap(), 0, ret);
1683 return NULL;
1686 static HKEY open_associations_reg_key(void)
1688 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1689 'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','F','i','l','e','O','p','e','n','A','s','s','o','c','i','a','t','i','o','n','s',0};
1690 HKEY assocKey;
1691 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1692 return assocKey;
1693 return NULL;
1696 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1698 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1699 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1700 HKEY assocKey;
1701 BOOL ret;
1703 if ((assocKey = open_associations_reg_key()))
1705 CHAR *valueA;
1706 WCHAR *value;
1708 ret = FALSE;
1710 valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1711 if (!valueA || lstrcmpA(valueA, mimeType))
1712 ret = TRUE;
1713 HeapFree(GetProcessHeap(), 0, valueA);
1715 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1716 if (!value || strcmpW(value, progId))
1717 ret = TRUE;
1718 HeapFree(GetProcessHeap(), 0, value);
1720 valueA = reg_get_valA(assocKey, extensionA, "AppName");
1721 if (!valueA || lstrcmpA(valueA, appName))
1722 ret = TRUE;
1723 HeapFree(GetProcessHeap(), 0, valueA);
1725 value = reg_get_valW(assocKey, extensionW, DocNameW);
1726 if (docName && (!value || strcmpW(value, docName)))
1727 ret = TRUE;
1728 HeapFree(GetProcessHeap(), 0, value);
1730 RegCloseKey(assocKey);
1732 else
1734 WINE_ERR("error opening associations registry key\n");
1735 ret = FALSE;
1737 return ret;
1740 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1742 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1743 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1744 HKEY assocKey;
1746 if ((assocKey = open_associations_reg_key()))
1748 HKEY subkey;
1749 if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1751 RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (BYTE*) mimeType, lstrlenA(mimeType) + 1);
1752 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1753 RegSetValueExA(subkey, "AppName", 0, REG_SZ, (BYTE*) appName, lstrlenA(appName) + 1);
1754 if (docName)
1755 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1756 RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1757 RegCloseKey(subkey);
1759 else
1760 WINE_ERR("could not create extension subkey\n");
1761 RegCloseKey(assocKey);
1763 else
1764 WINE_ERR("could not open file associations key\n");
1767 static BOOL cleanup_associations(void)
1769 static const WCHAR openW[] = {'o','p','e','n',0};
1770 HKEY assocKey;
1771 BOOL hasChanged = FALSE;
1772 if ((assocKey = open_associations_reg_key()))
1774 int i;
1775 BOOL done = FALSE;
1776 for (i = 0; !done; i++)
1778 WCHAR *extensionW = NULL;
1779 char *extensionA = NULL;
1780 DWORD size = 1024;
1781 LSTATUS ret;
1785 HeapFree(GetProcessHeap(), 0, extensionW);
1786 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1787 if (extensionW == NULL)
1789 WINE_ERR("out of memory\n");
1790 ret = ERROR_OUTOFMEMORY;
1791 break;
1793 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1794 size *= 2;
1795 } while (ret == ERROR_MORE_DATA);
1797 if (ret == ERROR_SUCCESS)
1799 WCHAR *command;
1800 extensionA = wchars_to_utf8_chars(extensionW);
1801 if (extensionA == NULL)
1803 WINE_ERR("out of memory\n");
1804 done = TRUE;
1805 goto end;
1807 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1808 if (command == NULL)
1810 char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1811 if (desktopFile)
1813 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1814 remove(desktopFile);
1816 RegDeleteKeyW(assocKey, extensionW);
1817 hasChanged = TRUE;
1818 HeapFree(GetProcessHeap(), 0, desktopFile);
1820 HeapFree(GetProcessHeap(), 0, command);
1822 else
1824 if (ret != ERROR_NO_MORE_ITEMS)
1825 WINE_ERR("error %d while reading registry\n", ret);
1826 done = TRUE;
1828 end:
1829 HeapFree(GetProcessHeap(), 0, extensionA);
1830 HeapFree(GetProcessHeap(), 0, extensionW);
1832 RegCloseKey(assocKey);
1834 else
1835 WINE_ERR("could not open file associations key\n");
1836 return hasChanged;
1839 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1840 const char *mime_type, const char *comment)
1842 BOOL ret = FALSE;
1843 char *filename;
1845 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1846 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1848 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1849 if (filename)
1851 FILE *packageFile = fopen(filename, "w");
1852 if (packageFile)
1854 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1855 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1856 fprintf(packageFile, " <mime-type type=\"");
1857 write_xml_text(packageFile, mime_type);
1858 fprintf(packageFile, "\">\n");
1859 fprintf(packageFile, " <glob pattern=\"*");
1860 write_xml_text(packageFile, dot_extension);
1861 fprintf(packageFile, "\"/>\n");
1862 if (comment)
1864 fprintf(packageFile, " <comment>");
1865 write_xml_text(packageFile, comment);
1866 fprintf(packageFile, "</comment>\n");
1868 fprintf(packageFile, " </mime-type>\n");
1869 fprintf(packageFile, "</mime-info>\n");
1870 ret = TRUE;
1871 fclose(packageFile);
1873 else
1874 WINE_ERR("error writing file %s\n", filename);
1875 HeapFree(GetProcessHeap(), 0, filename);
1877 else
1878 WINE_ERR("out of memory\n");
1879 return ret;
1882 static BOOL is_extension_blacklisted(LPCWSTR extension)
1884 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1885 static const WCHAR comW[] = {'.','c','o','m',0};
1886 static const WCHAR exeW[] = {'.','e','x','e',0};
1887 static const WCHAR msiW[] = {'.','m','s','i',0};
1889 if (!strcmpiW(extension, comW) ||
1890 !strcmpiW(extension, exeW) ||
1891 !strcmpiW(extension, msiW))
1892 return TRUE;
1893 return FALSE;
1896 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1897 const char *friendlyAppName, const char *mimeType,
1898 const char *progId)
1900 BOOL ret = FALSE;
1901 FILE *desktop;
1903 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1904 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1905 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1907 desktop = fopen(desktopPath, "w");
1908 if (desktop)
1910 fprintf(desktop, "[Desktop Entry]\n");
1911 fprintf(desktop, "Type=Application\n");
1912 fprintf(desktop, "Name=%s\n", friendlyAppName);
1913 fprintf(desktop, "MimeType=%s\n", mimeType);
1914 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1915 fprintf(desktop, "NoDisplay=true\n");
1916 fprintf(desktop, "StartupNotify=true\n");
1917 ret = TRUE;
1918 fclose(desktop);
1920 else
1921 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1922 return ret;
1925 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1927 static const WCHAR openW[] = {'o','p','e','n',0};
1928 struct list *nativeMimeTypes = NULL;
1929 LSTATUS ret = 0;
1930 int i;
1931 BOOL hasChanged = FALSE;
1933 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1935 WINE_ERR("could not build native MIME types\n");
1936 return FALSE;
1939 for (i = 0; ; i++)
1941 WCHAR *extensionW = NULL;
1942 DWORD size = 1024;
1946 HeapFree(GetProcessHeap(), 0, extensionW);
1947 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1948 if (extensionW == NULL)
1950 WINE_ERR("out of memory\n");
1951 ret = ERROR_OUTOFMEMORY;
1952 break;
1954 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1955 size *= 2;
1956 } while (ret == ERROR_MORE_DATA);
1958 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1960 char *extensionA = NULL;
1961 WCHAR *commandW = NULL;
1962 WCHAR *friendlyDocNameW = NULL;
1963 char *friendlyDocNameA = NULL;
1964 WCHAR *iconW = NULL;
1965 char *iconA = NULL;
1966 WCHAR *contentTypeW = NULL;
1967 char *mimeTypeA = NULL;
1968 WCHAR *friendlyAppNameW = NULL;
1969 char *friendlyAppNameA = NULL;
1970 WCHAR *progIdW = NULL;
1971 char *progIdA = NULL;
1973 extensionA = wchars_to_utf8_chars(extensionW);
1974 if (extensionA == NULL)
1976 WINE_ERR("out of memory\n");
1977 goto end;
1980 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
1981 if (friendlyDocNameW)
1983 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
1984 if (friendlyDocNameA == NULL)
1986 WINE_ERR("out of memory\n");
1987 goto end;
1991 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
1993 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
1995 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
1996 goto end;
1998 if (mimeTypeA == NULL)
2000 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2001 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2002 else
2003 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2005 if (mimeTypeA != NULL)
2007 /* Gnome seems to ignore the <icon> tag in MIME packages,
2008 * and the default name is more intuitive anyway.
2010 if (iconW)
2012 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2013 if (flattened_mime)
2015 int index = 0;
2016 WCHAR *comma = strrchrW(iconW, ',');
2017 if (comma)
2019 *comma = 0;
2020 index = atoiW(comma + 1);
2022 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2023 HeapFree(GetProcessHeap(), 0, flattened_mime);
2027 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2028 hasChanged = TRUE;
2030 else
2032 WINE_FIXME("out of memory\n");
2033 goto end;
2037 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2038 if (commandW == NULL)
2039 /* no command => no application is associated */
2040 goto end;
2042 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2043 if (friendlyAppNameW)
2045 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2046 if (friendlyAppNameA == NULL)
2048 WINE_ERR("out of memory\n");
2049 goto end;
2052 else
2054 friendlyAppNameA = heap_printf("A Wine application");
2055 if (friendlyAppNameA == NULL)
2057 WINE_ERR("out of memory\n");
2058 goto end;
2062 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2063 if (progIdW)
2065 progIdA = wchars_to_utf8_chars(progIdW);
2066 if (progIdA == NULL)
2068 WINE_ERR("out of memory\n");
2069 goto end;
2072 else
2073 goto end; /* no progID => not a file type association */
2075 if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2077 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2078 if (desktopPath)
2080 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2082 hasChanged = TRUE;
2083 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2085 HeapFree(GetProcessHeap(), 0, desktopPath);
2089 end:
2090 HeapFree(GetProcessHeap(), 0, extensionA);
2091 HeapFree(GetProcessHeap(), 0, commandW);
2092 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2093 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2094 HeapFree(GetProcessHeap(), 0, iconW);
2095 HeapFree(GetProcessHeap(), 0, iconA);
2096 HeapFree(GetProcessHeap(), 0, contentTypeW);
2097 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2098 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2099 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2100 HeapFree(GetProcessHeap(), 0, progIdW);
2101 HeapFree(GetProcessHeap(), 0, progIdA);
2103 HeapFree(GetProcessHeap(), 0, extensionW);
2104 if (ret != ERROR_SUCCESS)
2105 break;
2108 free_native_mime_types(nativeMimeTypes);
2109 return hasChanged;
2112 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2114 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2115 '\\','s','t','a','r','t','.','e','x','e',0};
2116 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2117 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
2118 WCHAR szTmp[INFOTIPSIZE];
2119 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2120 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2121 int iIconId = 0, r = -1;
2122 DWORD csidl = -1;
2123 HANDLE hsem = NULL;
2124 char *unix_link = NULL;
2126 if ( !link )
2128 WINE_ERR("Link name is null\n");
2129 return FALSE;
2132 if( !GetLinkLocation( link, &csidl, &link_name ) )
2134 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2135 return TRUE;
2137 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2139 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2140 return TRUE;
2142 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2144 szTmp[0] = 0;
2145 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2146 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2147 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2149 szTmp[0] = 0;
2150 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2151 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2152 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2154 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
2155 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2156 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2158 szTmp[0] = 0;
2159 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2160 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2161 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2163 if( !szPath[0] )
2165 LPITEMIDLIST pidl = NULL;
2166 IShellLinkW_GetIDList( sl, &pidl );
2167 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2168 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2171 /* extract the icon */
2172 if( szIconPath[0] )
2173 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2174 else
2175 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2177 /* fail - try once again after parent process exit */
2178 if( !icon_name )
2180 if (bWait)
2182 WINE_WARN("Unable to extract icon, deferring.\n");
2183 goto cleanup;
2185 WINE_ERR("failed to extract icon from %s\n",
2186 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2189 unix_link = wine_get_unix_file_name(link);
2190 if (unix_link == NULL)
2192 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2193 goto cleanup;
2196 /* check the path */
2197 if( szPath[0] )
2199 static const WCHAR exeW[] = {'.','e','x','e',0};
2200 WCHAR *p;
2202 /* check for .exe extension */
2203 if (!(p = strrchrW( szPath, '.' )) ||
2204 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2205 lstrcmpiW( p, exeW ))
2207 /* Not .exe - use 'start.exe' to launch this file */
2208 p = szArgs + lstrlenW(szPath) + 2;
2209 if (szArgs[0])
2211 p[0] = ' ';
2212 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2213 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2215 else
2216 p[0] = 0;
2218 szArgs[0] = '"';
2219 lstrcpyW(szArgs + 1, szPath);
2220 p[-1] = '"';
2222 GetWindowsDirectoryW(szPath, MAX_PATH);
2223 lstrcatW(szPath, startW);
2226 /* convert app working dir */
2227 if (szWorkDir[0])
2228 work_dir = wine_get_unix_file_name( szWorkDir );
2230 else
2232 /* if there's no path... try run the link itself */
2233 lstrcpynW(szArgs, link, MAX_PATH);
2234 GetWindowsDirectoryW(szPath, MAX_PATH);
2235 lstrcatW(szPath, startW);
2238 /* escape the path and parameters */
2239 escaped_path = escape(szPath);
2240 escaped_args = escape(szArgs);
2241 escaped_description = escape(szDescription);
2243 /* building multiple menus concurrently has race conditions */
2244 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2245 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2247 WINE_ERR("failed wait for semaphore\n");
2248 goto cleanup;
2251 if (in_desktop_dir(csidl))
2253 char *location;
2254 const char *lastEntry;
2255 lastEntry = strrchr(link_name, '/');
2256 if (lastEntry == NULL)
2257 lastEntry = link_name;
2258 else
2259 ++lastEntry;
2260 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2261 if (location)
2263 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2264 HeapFree(GetProcessHeap(), 0, location);
2267 else
2268 r = !write_menu_entry(unix_link, link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2270 ReleaseSemaphore( hsem, 1, NULL );
2272 cleanup:
2273 if (hsem) CloseHandle( hsem );
2274 HeapFree( GetProcessHeap(), 0, icon_name );
2275 HeapFree( GetProcessHeap(), 0, work_dir );
2276 HeapFree( GetProcessHeap(), 0, link_name );
2277 HeapFree( GetProcessHeap(), 0, escaped_args );
2278 HeapFree( GetProcessHeap(), 0, escaped_path );
2279 HeapFree( GetProcessHeap(), 0, escaped_description );
2280 HeapFree( GetProcessHeap(), 0, unix_link);
2282 if (r && !bWait)
2283 WINE_ERR("failed to build the menu\n" );
2285 return ( r == 0 );
2288 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2290 char *link_name = NULL;
2291 DWORD csidl = -1;
2292 LPWSTR urlPath;
2293 char *escaped_urlPath = NULL;
2294 HRESULT hr;
2295 HANDLE hSem = NULL;
2296 BOOL ret = TRUE;
2297 int r = -1;
2298 char *unix_link = NULL;
2300 if ( !link )
2302 WINE_ERR("Link name is null\n");
2303 return TRUE;
2306 if( !GetLinkLocation( link, &csidl, &link_name ) )
2308 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2309 return TRUE;
2311 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2313 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2314 ret = TRUE;
2315 goto cleanup;
2317 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2319 hr = url->lpVtbl->GetURL(url, &urlPath);
2320 if (FAILED(hr))
2322 ret = TRUE;
2323 goto cleanup;
2325 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2327 unix_link = wine_get_unix_file_name(link);
2328 if (unix_link == NULL)
2330 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2331 goto cleanup;
2334 escaped_urlPath = escape(urlPath);
2336 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2337 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2339 WINE_ERR("failed wait for semaphore\n");
2340 goto cleanup;
2342 if (in_desktop_dir(csidl))
2344 char *location;
2345 const char *lastEntry;
2346 lastEntry = strrchr(link_name, '/');
2347 if (lastEntry == NULL)
2348 lastEntry = link_name;
2349 else
2350 ++lastEntry;
2351 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2352 if (location)
2354 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2355 HeapFree(GetProcessHeap(), 0, location);
2358 else
2359 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2360 ret = (r != 0);
2361 ReleaseSemaphore(hSem, 1, NULL);
2363 cleanup:
2364 if (hSem)
2365 CloseHandle(hSem);
2366 HeapFree(GetProcessHeap(), 0, link_name);
2367 CoTaskMemFree( urlPath );
2368 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2369 HeapFree(GetProcessHeap(), 0, unix_link);
2370 return ret;
2373 static BOOL WaitForParentProcess( void )
2375 PROCESSENTRY32 procentry;
2376 HANDLE hsnapshot = NULL, hprocess = NULL;
2377 DWORD ourpid = GetCurrentProcessId();
2378 BOOL ret = FALSE, rc;
2380 WINE_TRACE("Waiting for parent process\n");
2381 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2382 INVALID_HANDLE_VALUE)
2384 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2385 goto done;
2388 procentry.dwSize = sizeof(PROCESSENTRY32);
2389 rc = Process32First( hsnapshot, &procentry );
2390 while (rc)
2392 if (procentry.th32ProcessID == ourpid) break;
2393 rc = Process32Next( hsnapshot, &procentry );
2395 if (!rc)
2397 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2398 goto done;
2401 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2402 NULL)
2404 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2405 GetLastError());
2406 goto done;
2409 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2410 ret = TRUE;
2411 else
2412 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2414 done:
2415 if (hprocess) CloseHandle( hprocess );
2416 if (hsnapshot) CloseHandle( hsnapshot );
2417 return ret;
2420 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2422 IShellLinkW *sl;
2423 IPersistFile *pf;
2424 HRESULT r;
2425 WCHAR fullname[MAX_PATH];
2426 DWORD len;
2428 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2430 if( !linkname[0] )
2432 WINE_ERR("link name missing\n");
2433 return 1;
2436 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2437 if (len==0 || len>MAX_PATH)
2439 WINE_ERR("couldn't get full path of link file\n");
2440 return 1;
2443 r = CoInitialize( NULL );
2444 if( FAILED( r ) )
2446 WINE_ERR("CoInitialize failed\n");
2447 return 1;
2450 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2451 &IID_IShellLinkW, (LPVOID *) &sl );
2452 if( FAILED( r ) )
2454 WINE_ERR("No IID_IShellLink\n");
2455 return 1;
2458 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2459 if( FAILED( r ) )
2461 WINE_ERR("No IID_IPersistFile\n");
2462 return 1;
2465 r = IPersistFile_Load( pf, fullname, STGM_READ );
2466 if( SUCCEEDED( r ) )
2468 /* If something fails (eg. Couldn't extract icon)
2469 * wait for parent process and try again
2471 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2473 WaitForParentProcess();
2474 InvokeShellLinker( sl, fullname, FALSE );
2477 else
2479 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2482 IPersistFile_Release( pf );
2483 IShellLinkW_Release( sl );
2485 CoUninitialize();
2487 return !r;
2490 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2492 IUniformResourceLocatorW *url;
2493 IPersistFile *pf;
2494 HRESULT r;
2495 WCHAR fullname[MAX_PATH];
2496 DWORD len;
2498 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2500 if( !urlname[0] )
2502 WINE_ERR("URL name missing\n");
2503 return 1;
2506 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2507 if (len==0 || len>MAX_PATH)
2509 WINE_ERR("couldn't get full path of URL file\n");
2510 return 1;
2513 r = CoInitialize( NULL );
2514 if( FAILED( r ) )
2516 WINE_ERR("CoInitialize failed\n");
2517 return 1;
2520 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2521 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2522 if( FAILED( r ) )
2524 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2525 return 1;
2528 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2529 if( FAILED( r ) )
2531 WINE_ERR("No IID_IPersistFile\n");
2532 return 1;
2534 r = IPersistFile_Load( pf, fullname, STGM_READ );
2535 if( SUCCEEDED( r ) )
2537 /* If something fails (eg. Couldn't extract icon)
2538 * wait for parent process and try again
2540 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2542 WaitForParentProcess();
2543 InvokeShellLinkerForURL( url, fullname, FALSE );
2547 IPersistFile_Release( pf );
2548 url->lpVtbl->Release( url );
2550 CoUninitialize();
2552 return !r;
2555 static void RefreshFileTypeAssociations(void)
2557 HANDLE hSem = NULL;
2558 char *mime_dir = NULL;
2559 char *packages_dir = NULL;
2560 char *applications_dir = NULL;
2561 BOOL hasChanged;
2563 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2564 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2566 WINE_ERR("failed wait for semaphore\n");
2567 CloseHandle(hSem);
2568 hSem = NULL;
2569 goto end;
2572 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2573 if (mime_dir == NULL)
2575 WINE_ERR("out of memory\n");
2576 goto end;
2578 create_directories(mime_dir);
2580 packages_dir = heap_printf("%s/packages", mime_dir);
2581 if (packages_dir == NULL)
2583 WINE_ERR("out of memory\n");
2584 goto end;
2586 create_directories(packages_dir);
2588 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2589 if (applications_dir == NULL)
2591 WINE_ERR("out of memory\n");
2592 goto end;
2594 create_directories(applications_dir);
2596 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2597 hasChanged |= cleanup_associations();
2598 if (hasChanged)
2600 const char *argv[3];
2602 argv[0] = "update-mime-database";
2603 argv[1] = mime_dir;
2604 argv[2] = NULL;
2605 spawnvp( _P_NOWAIT, argv[0], argv );
2607 argv[0] = "update-desktop-database";
2608 argv[1] = applications_dir;
2609 spawnvp( _P_NOWAIT, argv[0], argv );
2612 end:
2613 if (hSem)
2615 ReleaseSemaphore(hSem, 1, NULL);
2616 CloseHandle(hSem);
2618 HeapFree(GetProcessHeap(), 0, mime_dir);
2619 HeapFree(GetProcessHeap(), 0, packages_dir);
2620 HeapFree(GetProcessHeap(), 0, applications_dir);
2623 static void cleanup_menus(void)
2625 HKEY hkey;
2627 hkey = open_menus_reg_key();
2628 if (hkey)
2630 int i;
2631 LSTATUS lret = ERROR_SUCCESS;
2632 for (i = 0; lret == ERROR_SUCCESS; )
2634 char *value = NULL;
2635 char *data = NULL;
2636 DWORD valueSize = 4096;
2637 DWORD dataSize = 4096;
2638 while (1)
2640 lret = ERROR_OUTOFMEMORY;
2641 value = HeapAlloc(GetProcessHeap(), 0, valueSize);
2642 if (value == NULL)
2643 break;
2644 data = HeapAlloc(GetProcessHeap(), 0, dataSize);
2645 if (data == NULL)
2646 break;
2647 lret = RegEnumValueA(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2648 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2649 break;
2650 valueSize *= 2;
2651 dataSize *= 2;
2652 HeapFree(GetProcessHeap(), 0, value);
2653 HeapFree(GetProcessHeap(), 0, data);
2654 value = data = NULL;
2656 if (lret == ERROR_SUCCESS)
2658 struct stat filestats;
2659 if (stat(data, &filestats) < 0 && errno == ENOENT)
2661 WINE_TRACE("removing menu related file %s\n", value);
2662 remove(value);
2663 RegDeleteValueA(hkey, value);
2665 else
2666 i++;
2668 else if (lret != ERROR_NO_MORE_ITEMS)
2669 WINE_WARN("error %d reading registry\n", lret);
2670 HeapFree(GetProcessHeap(), 0, value);
2671 HeapFree(GetProcessHeap(), 0, data);
2673 RegCloseKey(hkey);
2675 else
2676 WINE_ERR("error opening registry key, menu cleanup failed\n");
2679 static CHAR *next_token( LPSTR *p )
2681 LPSTR token = NULL, t = *p;
2683 if( !t )
2684 return NULL;
2686 while( t && !token )
2688 switch( *t )
2690 case ' ':
2691 t++;
2692 continue;
2693 case '"':
2694 /* unquote the token */
2695 token = ++t;
2696 t = strchr( token, '"' );
2697 if( t )
2698 *t++ = 0;
2699 break;
2700 case 0:
2701 t = NULL;
2702 break;
2703 default:
2704 token = t;
2705 t = strchr( token, ' ' );
2706 if( t )
2707 *t++ = 0;
2708 break;
2711 *p = t;
2712 return token;
2715 static BOOL init_xdg(void)
2717 WCHAR shellDesktopPath[MAX_PATH];
2718 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2719 if (SUCCEEDED(hr))
2720 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2721 if (xdg_desktop_dir == NULL)
2723 WINE_ERR("error looking up the desktop directory\n");
2724 return FALSE;
2727 if (getenv("XDG_CONFIG_HOME"))
2728 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2729 else
2730 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2731 if (xdg_config_dir)
2733 create_directories(xdg_config_dir);
2734 if (getenv("XDG_DATA_HOME"))
2735 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
2736 else
2737 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2738 if (xdg_data_dir)
2740 char *buffer;
2741 create_directories(xdg_data_dir);
2742 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2743 if (buffer)
2745 mkdir(buffer, 0777);
2746 HeapFree(GetProcessHeap(), 0, buffer);
2748 return TRUE;
2750 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2752 WINE_ERR("out of memory\n");
2753 return FALSE;
2756 /***********************************************************************
2758 * WinMain
2760 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
2762 LPSTR token = NULL, p;
2763 BOOL bWait = FALSE;
2764 BOOL bURL = FALSE;
2765 int ret = 0;
2767 if (!init_xdg())
2768 return 1;
2770 for( p = cmdline; p && *p; )
2772 token = next_token( &p );
2773 if( !token )
2774 break;
2775 if( !lstrcmpA( token, "-a" ) )
2777 RefreshFileTypeAssociations();
2778 continue;
2780 if( !lstrcmpA( token, "-r" ) )
2782 cleanup_menus();
2783 continue;
2785 if( !lstrcmpA( token, "-w" ) )
2786 bWait = TRUE;
2787 else if ( !lstrcmpA( token, "-u" ) )
2788 bURL = TRUE;
2789 else if( token[0] == '-' )
2791 WINE_ERR( "unknown option %s\n",token);
2793 else
2795 WCHAR link[MAX_PATH];
2796 BOOL bRet;
2798 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2799 if (bURL)
2800 bRet = Process_URL( link, bWait );
2801 else
2802 bRet = Process_Link( link, bWait );
2803 if (!bRet)
2805 WINE_ERR( "failed to build menu item for %s\n",token);
2806 ret = 1;
2811 return ret;