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.
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
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
53 * Clean up fd.o menu icons and .directory files when the menu is deleted
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
64 * Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
65 * that write associations there won't associate (#17019).
69 #include "wine/port.h"
94 #include "wine/unicode.h"
95 #include "wine/debug.h"
96 #include "wine/library.h"
97 #include "wine/list.h"
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"
133 GRPICONDIRENTRY idEntries[1];
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 */
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);
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; \
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);
225 return libpng_handle;
228 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
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";
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;
263 color_type |= PNG_COLOR_MASK_ALPHA;
266 color_type |= PNG_COLOR_MASK_COLOR;
272 if (!libpng_handle && !load_libpng())
274 WINE_WARN("Unable to load libpng\n");
278 if (!(fp = fopen(png_filename, "w")))
280 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
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)
290 pAND = pXOR + nHeight * nXORWidthBytes;
293 /* Apply mask if present */
298 /* copy bytes before modifying them */
299 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
300 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
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)
316 RGBQUAD *pixel = (RGBQUAD *)row;
317 pixel->rgbBlue = bgColor.rgbBlue;
318 pixel->rgbGreen = bgColor.rgbGreen;
319 pixel->rgbRed = bgColor.rgbRed;
321 pixel->rgbReserved = bgColor.rgbReserved;
327 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
328 !(info_ptr = ppng_create_info_struct(png_ptr)))
333 /* All future errors jump here */
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,
342 PNG_COMPRESSION_TYPE_DEFAULT,
343 PNG_FILTER_TYPE_DEFAULT);
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);
364 HeapFree(GetProcessHeap(), 0, copy);
365 HeapFree(GetProcessHeap(), 0, comment.text);
369 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
371 unlink(png_filename);
372 HeapFree(GetProcessHeap(), 0, copy);
373 HeapFree(GetProcessHeap(), 0, comment.text);
376 #endif /* SONAME_LIBPNG */
378 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
388 BOOL aColorUsed[256] = {0};
393 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
395 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
399 if (!(fXPMFile = fopen(szXPMFileName, "w")))
401 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
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;
432 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
434 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
435 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
438 for (i = 0; i < nColors; 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)
444 if (fprintf(fXPMFile, "\" c None\"") <= 0)
447 for (i = 0; i < nHeight; i++)
449 if (fprintf(fXPMFile, ",\n\"") <= 0)
451 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
455 if (fprintf(fXPMFile, " ") <= 0)
459 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
462 if (fprintf(fXPMFile, "\"") <= 0)
465 if (fprintf(fXPMFile, "};\n") <= 0)
471 HeapFree(GetProcessHeap(), 0, comment);
476 HeapFree(GetProcessHeap(), 0, comment);
478 unlink( szXPMFileName );
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);
495 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
499 LPCWSTR lpName = NULL;
501 GRPICONDIR *pIconDir;
503 ENUMRESSTRUCT sEnumRes;
509 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
512 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
513 wine_dbgstr_w(szFileName), GetLastError());
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());
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());
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);
561 WINE_WARN("found no icon\n");
562 FreeLibrary(hModule);
566 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
568 if ((hResData = LoadResource(hModule, hResInfo)))
570 if ((pIcon = LockResource(hResData)))
573 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
578 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
579 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
584 FreeResource(hResData);
588 FreeLibrary(hModule);
592 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
594 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
595 !extract_icon16(szFileName, szXPMFileName)*/)
600 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
602 FILE *fICOFile = NULL;
604 ICONDIRENTRY *pIconDirEntry = NULL;
605 int nMax = 0, nMaxBits = 0;
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));
618 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
619 (iconDir.idReserved != 0) || (iconDir.idType != 1))
621 WINE_WARN("Invalid ico file format\n");
625 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
627 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
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)
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)
645 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
647 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
651 /* Prefer PNG over XPM */
653 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
656 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
657 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
661 HeapFree(GetProcessHeap(), 0, pIcon);
662 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
664 HeapFree(GetProcessHeap(), 0, filename);
668 HeapFree(GetProcessHeap(), 0, pIcon);
669 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
670 if (fICOFile) fclose(fICOFile);
671 HeapFree(GetProcessHeap(), 0, filename);
675 static BOOL create_default_icon( const char *filename, const char* comment )
680 if (!(fXPM = fopen(filename, "w"))) return FALSE;
681 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
683 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
684 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
687 if (fprintf( fXPM, "};\n" ) <=0)
698 static unsigned short crc16(const char* string)
700 unsigned short crc = 0;
703 for (i = 0; string[i] != 0; i++)
706 for (j = 0; j < 8; c >>= 1, j++)
708 xor_poly = (c ^ crc) & 1;
717 static char *strdupA( const char *str )
721 if (!str) return NULL;
722 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
726 static char* heap_printf(const char *format, ...)
733 va_start(args, format);
736 buffer = HeapAlloc(GetProcessHeap(), 0, size);
739 n = vsnprintf(buffer, size, format, args);
746 HeapFree(GetProcessHeap(), 0, buffer);
749 if (!buffer) return NULL;
750 ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
751 if (!ret) ret = buffer;
755 static void write_xml_text(FILE *file, const char *text)
758 for (i = 0; text[i]; i++)
761 fputs("&", file);
762 else if (text[i] == '<')
764 else if (text[i] == '>')
766 else if (text[i] == '\'')
767 fputs("'", file);
768 else if (text[i] == '"')
769 fputs(""", file);
771 fputc(text[i], file);
775 static BOOL create_directories(char *directory)
780 for (i = 0; directory[i]; i++)
782 if (i > 0 && directory[i] == '/')
785 mkdir(directory, 0777);
789 if (mkdir(directory, 0777) && errno != EEXIST)
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 )
799 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
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);
808 if (mkdir(iconsdir, 0777) && errno != EEXIST)
810 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
816 WINE_TRACE("no icon created\n");
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);
826 if (*s=='/' || *s=='\\') {
834 if (*ico_name=='\\') *ico_name++='\0';
835 s=strrchr(ico_name,'.');
838 /* Compute the source-path hash */
841 /* Try to treat the source file as an exe */
843 xpm_path=heap_printf("%s/%s.png",iconsdir,destFilename);
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));
852 if (ExtractFromEXEDLL( path, index, xpm_path ))
855 /* Must be something else, ignore the index in that case */
857 sprintf(xpm_path,"%s/%s.png",iconsdir,destFilename);
859 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
860 if (ExtractFromICO( path, xpm_path))
865 sprintf(xpm_path,"%s/%s.xpm",iconsdir,destFilename);
867 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
868 if (create_default_icon( xpm_path, ico_path ))
872 HeapFree( GetProcessHeap(), 0, xpm_path );
876 HeapFree(GetProcessHeap(), 0, iconsdir);
877 HeapFree(GetProcessHeap(), 0, ico_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};
887 ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey);
888 if (ret == ERROR_SUCCESS)
894 static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
897 WCHAR *windows_fileW;
901 size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
902 unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
905 MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
906 size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
907 windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
911 MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
912 hkey = open_menus_reg_key();
915 ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
916 (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
920 ret = GetLastError();
921 HeapFree(GetProcessHeap(), 0, windows_fileW);
924 ret = ERROR_NOT_ENOUGH_MEMORY;
925 HeapFree(GetProcessHeap(), 0, unix_fileW);
928 ret = ERROR_NOT_ENOUGH_MEMORY;
932 static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
933 const char *path, const char *args, const char *descr,
934 const char *workdir, const char *icon)
938 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
939 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
940 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
942 file = fopen(location, "w");
946 fprintf(file, "[Desktop Entry]\n");
947 fprintf(file, "Name=%s\n", linkname);
948 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
949 wine_get_config_dir(), path, args);
950 fprintf(file, "Type=Application\n");
951 fprintf(file, "StartupNotify=true\n");
952 if (descr && lstrlenA(descr))
953 fprintf(file, "Comment=%s\n", descr);
954 if (workdir && lstrlenA(workdir))
955 fprintf(file, "Path=%s\n", workdir);
956 if (icon && lstrlenA(icon))
957 fprintf(file, "Icon=%s\n", icon);
963 DWORD ret = register_menus_entry(location, unix_link);
964 if (ret != ERROR_SUCCESS)
971 static BOOL write_directory_entry(const char *directory, const char *location)
975 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
977 file = fopen(location, "w");
981 fprintf(file, "[Desktop Entry]\n");
982 fprintf(file, "Type=Directory\n");
983 if (strcmp(directory, "wine") == 0)
985 fprintf(file, "Name=Wine\n");
986 fprintf(file, "Icon=wine\n");
990 fprintf(file, "Name=%s\n", directory);
991 fprintf(file, "Icon=folder\n");
998 static BOOL write_menu_file(const char *unix_link, const char *filename)
1001 FILE *tempfile = NULL;
1004 char *menuPath = NULL;
1009 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
1013 tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1016 int tempfd = mkstemps(tempfilename, 0);
1019 tempfile = fdopen(tempfd, "w");
1025 else if (errno == EEXIST)
1027 HeapFree(GetProcessHeap(), 0, tempfilename);
1030 HeapFree(GetProcessHeap(), 0, tempfilename);
1035 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
1036 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
1037 fprintf(tempfile, "<Menu>\n");
1038 fprintf(tempfile, " <Name>Applications</Name>\n");
1040 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
1041 if (name == NULL) goto end;
1043 for (i = 0; filename[i]; i++)
1045 name[i] = filename[i];
1046 if (filename[i] == '/')
1048 char *dir_file_name;
1051 fprintf(tempfile, " <Menu>\n");
1052 fprintf(tempfile, " <Name>%s", count ? "" : "wine-");
1053 write_xml_text(tempfile, name);
1054 fprintf(tempfile, "</Name>\n");
1055 fprintf(tempfile, " <Directory>%s", count ? "" : "wine-");
1056 write_xml_text(tempfile, name);
1057 fprintf(tempfile, ".directory</Directory>\n");
1058 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
1059 xdg_data_dir, count ? "" : "wine-", name);
1062 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
1063 write_directory_entry(lastEntry, dir_file_name);
1064 HeapFree(GetProcessHeap(), 0, dir_file_name);
1067 lastEntry = &name[i+1];
1073 fprintf(tempfile, " <Include>\n");
1074 fprintf(tempfile, " <Filename>");
1075 write_xml_text(tempfile, name);
1076 fprintf(tempfile, "</Filename>\n");
1077 fprintf(tempfile, " </Include>\n");
1078 for (i = 0; i < count; i++)
1079 fprintf(tempfile, " </Menu>\n");
1080 fprintf(tempfile, "</Menu>\n");
1082 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
1083 if (menuPath == NULL) goto end;
1084 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
1091 ret = (rename(tempfilename, menuPath) == 0);
1092 if (!ret && tempfilename)
1093 remove(tempfilename);
1094 HeapFree(GetProcessHeap(), 0, tempfilename);
1096 register_menus_entry(menuPath, unix_link);
1097 HeapFree(GetProcessHeap(), 0, name);
1098 HeapFree(GetProcessHeap(), 0, menuPath);
1102 static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1103 const char *descr, const char *workdir, const char *icon)
1105 const char *linkname;
1106 char *desktopPath = NULL;
1108 char *filename = NULL;
1111 WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1112 wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1113 wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
1115 linkname = strrchr(link, '/');
1116 if (linkname == NULL)
1121 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
1124 WINE_WARN("out of memory creating menu entry\n");
1128 desktopDir = strrchr(desktopPath, '/');
1130 if (!create_directories(desktopPath))
1132 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
1137 if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon))
1139 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
1144 filename = heap_printf("wine/%s.desktop", link);
1145 if (!filename || !write_menu_file(unix_link, filename))
1147 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1152 HeapFree(GetProcessHeap(), 0, desktopPath);
1153 HeapFree(GetProcessHeap(), 0, filename);
1157 /* This escapes \ in filenames */
1158 static LPSTR escape(LPCWSTR arg)
1165 while((esc = strchrW(esc, '\\')))
1171 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1172 narg = HeapAlloc(GetProcessHeap(), 0, len);
1177 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1181 *x++='\\'; /* escape \ */
1188 /* Return a heap-allocated copy of the unix format difference between the two
1189 * Windows-format paths.
1190 * locn is the owning location
1191 * link is within locn
1193 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1195 char *unix_locn, *unix_link;
1196 char *relative = NULL;
1198 unix_locn = wine_get_unix_file_name(locn);
1199 unix_link = wine_get_unix_file_name(link);
1200 if (unix_locn && unix_link)
1202 size_t len_unix_locn, len_unix_link;
1203 len_unix_locn = strlen (unix_locn);
1204 len_unix_link = strlen (unix_link);
1205 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1208 char *p = strrchr (unix_link + len_unix_locn, '/');
1209 p = strrchr (p, '.');
1213 len_unix_link = p - unix_link;
1215 len_rel = len_unix_link - len_unix_locn;
1216 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1219 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1224 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1225 HeapFree(GetProcessHeap(), 0, unix_locn);
1226 HeapFree(GetProcessHeap(), 0, unix_link);
1230 /***********************************************************************
1234 * returns TRUE if successful
1235 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1236 * *relative will contain the address of a heap-allocated copy of the portion
1237 * of the filename that is within the specified location, in unix form
1239 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1241 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1242 DWORD len, i, r, filelen;
1243 const DWORD locations[] = {
1244 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1245 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1246 CSIDL_COMMON_STARTMENU };
1248 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1249 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1250 if (filelen==0 || filelen>MAX_PATH)
1253 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1255 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1256 * expand or our hardcoded list won't match.
1258 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1259 if (filelen==0 || filelen>MAX_PATH)
1262 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1264 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1266 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1269 len = lstrlenW(buffer);
1270 if (len >= MAX_PATH)
1271 continue; /* We've just trashed memory! Hopefully we are OK */
1273 if (len > filelen || filename[len]!='\\')
1275 /* do a lstrcmpinW */
1277 r = lstrcmpiW( filename, buffer );
1278 filename[len] = '\\';
1282 /* return the remainder of the string and link type */
1283 *loc = locations[i];
1284 *relative = relative_path (filename, buffer);
1285 return (*relative != NULL);
1291 /* gets the target path directly or through MSI */
1292 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1293 LPWSTR szArgs, DWORD argsSize)
1295 IShellLinkDataList *dl = NULL;
1296 EXP_DARWIN_LINK *dar = NULL;
1302 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1303 if (hr == S_OK && szPath[0])
1305 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1309 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1313 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1320 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1321 if (hr == ERROR_SUCCESS)
1324 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1325 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1326 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1327 if (hr == ERROR_SUCCESS)
1330 int bcount, in_quotes;
1332 /* Extract the application path */
1339 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1341 /* skip the remaining spaces */
1344 } while (*s==0x0009 || *s==0x0020);
1347 else if (*s==0x005c)
1353 else if (*s==0x0022)
1356 if ((bcount & 1)==0)
1358 /* Preceded by an even number of '\', this is
1359 * half that number of '\', plus a quote which
1363 in_quotes=!in_quotes;
1368 /* Preceded by an odd number of '\', this is
1369 * half that number of '\' followed by a '"'
1379 /* a regular character */
1383 if ((d-szPath) == pathSize)
1385 /* Keep processing the path till we get to the
1386 * arguments, but 'stand still'
1391 /* Close the application path */
1394 lstrcpynW(szArgs, s, argsSize);
1396 HeapFree( GetProcessHeap(), 0, szCmdline );
1401 IShellLinkDataList_Release( dl );
1405 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1408 WCHAR *value = NULL;
1410 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1413 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1416 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1419 HeapFree(GetProcessHeap(), 0, value);
1427 static char* wchars_to_utf8_chars(LPCWSTR string)
1430 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
1431 ret = HeapAlloc(GetProcessHeap(), 0, size);
1433 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
1437 static char* wchars_to_unix_chars(LPCWSTR string)
1440 INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
1441 ret = HeapAlloc(GetProcessHeap(), 0, size);
1443 WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
1447 static char *slashes_to_minuses(const char *string)
1450 char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
1453 for (i = 0; string[i]; i++)
1455 if (string[i] == '/')
1466 static BOOL next_line(FILE *file, char **line, int *size)
1473 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1475 while (*line != NULL)
1477 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1479 HeapFree(GetProcessHeap(), 0, *line);
1485 pos = strlen(*line);
1486 cr = strchr(*line, '\n');
1491 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1496 HeapFree(GetProcessHeap(), 0, *line);
1509 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1511 char *globs_filename = NULL;
1513 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1516 FILE *globs_file = fopen(globs_filename, "r");
1517 if (globs_file) /* doesn't have to exist */
1521 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1524 struct xdg_mime_type *mime_type_entry = NULL;
1525 if (line[0] != '#' && (pos = strchr(line, ':')))
1527 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1528 if (mime_type_entry)
1531 mime_type_entry->mimeType = strdupA(line);
1532 mime_type_entry->glob = strdupA(pos + 1);
1533 if (mime_type_entry->mimeType && mime_type_entry->glob)
1534 list_add_tail(mime_types, &mime_type_entry->entry);
1537 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1538 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1539 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1547 HeapFree(GetProcessHeap(), 0, line);
1550 HeapFree(GetProcessHeap(), 0, globs_filename);
1557 static void free_native_mime_types(struct list *native_mime_types)
1559 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1561 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1563 list_remove(&mime_type_entry->entry);
1564 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1565 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1566 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1568 HeapFree(GetProcessHeap(), 0, native_mime_types);
1571 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1573 char *xdg_data_dirs;
1578 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1579 if (xdg_data_dirs == NULL)
1580 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1582 xdg_data_dirs = strdupA(xdg_data_dirs);
1586 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1592 list_init(*mime_types);
1593 ret = add_mimes(xdg_data_home, *mime_types);
1596 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1599 ret = add_mimes(begin, *mime_types);
1605 ret = add_mimes(begin, *mime_types);
1610 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1614 if (!ret && *mime_types)
1616 free_native_mime_types(*mime_types);
1622 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1626 struct xdg_mime_type *mime_type_entry;
1627 int matchLength = 0;
1631 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1633 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1635 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1637 *match = mime_type_entry->mimeType;
1638 matchLength = strlen(mime_type_entry->glob);
1645 *match = strdupA(*match);
1655 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1656 const char *extensionA,
1660 WCHAR *lower_extensionW;
1662 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1663 if (ret == FALSE || *mime_type != NULL)
1665 len = strlenW(extensionW);
1666 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1667 if (lower_extensionW)
1669 char *lower_extensionA;
1670 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1671 strlwrW(lower_extensionW);
1672 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1673 if (lower_extensionA)
1675 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1676 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1681 WINE_FIXME("out of memory\n");
1683 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1688 WINE_FIXME("out of memory\n");
1693 static CHAR* reg_get_valA(HKEY key, LPCSTR subkey, LPCSTR name)
1696 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1698 CHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1701 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1704 HeapFree(GetProcessHeap(), 0, ret);
1709 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1712 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1714 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1717 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1720 HeapFree(GetProcessHeap(), 0, ret);
1725 static HKEY open_associations_reg_key(void)
1727 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1728 '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};
1730 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1735 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1737 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1738 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1742 if ((assocKey = open_associations_reg_key()))
1749 valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1750 if (!valueA || lstrcmpA(valueA, mimeType))
1752 HeapFree(GetProcessHeap(), 0, valueA);
1754 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1755 if (!value || strcmpW(value, progId))
1757 HeapFree(GetProcessHeap(), 0, value);
1759 valueA = reg_get_valA(assocKey, extensionA, "AppName");
1760 if (!valueA || lstrcmpA(valueA, appName))
1762 HeapFree(GetProcessHeap(), 0, valueA);
1764 value = reg_get_valW(assocKey, extensionW, DocNameW);
1765 if (docName && (!value || strcmpW(value, docName)))
1767 HeapFree(GetProcessHeap(), 0, value);
1769 RegCloseKey(assocKey);
1773 WINE_ERR("error opening associations registry key\n");
1779 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1781 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1782 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1785 if ((assocKey = open_associations_reg_key()))
1788 if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1790 RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (const BYTE*) mimeType, lstrlenA(mimeType) + 1);
1791 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1792 RegSetValueExA(subkey, "AppName", 0, REG_SZ, (const BYTE*) appName, lstrlenA(appName) + 1);
1794 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (const BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1795 RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (const BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1796 RegCloseKey(subkey);
1799 WINE_ERR("could not create extension subkey\n");
1800 RegCloseKey(assocKey);
1803 WINE_ERR("could not open file associations key\n");
1806 static BOOL cleanup_associations(void)
1808 static const WCHAR openW[] = {'o','p','e','n',0};
1810 BOOL hasChanged = FALSE;
1811 if ((assocKey = open_associations_reg_key()))
1815 for (i = 0; !done; i++)
1817 WCHAR *extensionW = NULL;
1818 char *extensionA = NULL;
1824 HeapFree(GetProcessHeap(), 0, extensionW);
1825 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1826 if (extensionW == NULL)
1828 WINE_ERR("out of memory\n");
1829 ret = ERROR_OUTOFMEMORY;
1832 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1834 } while (ret == ERROR_MORE_DATA);
1836 if (ret == ERROR_SUCCESS)
1839 extensionA = wchars_to_utf8_chars(extensionW);
1840 if (extensionA == NULL)
1842 WINE_ERR("out of memory\n");
1846 command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
1847 if (command == NULL)
1849 char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1852 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1853 remove(desktopFile);
1855 RegDeleteKeyW(assocKey, extensionW);
1857 HeapFree(GetProcessHeap(), 0, desktopFile);
1859 HeapFree(GetProcessHeap(), 0, command);
1863 if (ret != ERROR_NO_MORE_ITEMS)
1864 WINE_ERR("error %d while reading registry\n", ret);
1868 HeapFree(GetProcessHeap(), 0, extensionA);
1869 HeapFree(GetProcessHeap(), 0, extensionW);
1871 RegCloseKey(assocKey);
1874 WINE_ERR("could not open file associations key\n");
1878 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1879 const char *mime_type, const char *comment)
1884 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1885 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1887 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1890 FILE *packageFile = fopen(filename, "w");
1893 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1894 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1895 fprintf(packageFile, " <mime-type type=\"");
1896 write_xml_text(packageFile, mime_type);
1897 fprintf(packageFile, "\">\n");
1898 fprintf(packageFile, " <glob pattern=\"*");
1899 write_xml_text(packageFile, dot_extension);
1900 fprintf(packageFile, "\"/>\n");
1903 fprintf(packageFile, " <comment>");
1904 write_xml_text(packageFile, comment);
1905 fprintf(packageFile, "</comment>\n");
1907 fprintf(packageFile, " </mime-type>\n");
1908 fprintf(packageFile, "</mime-info>\n");
1910 fclose(packageFile);
1913 WINE_ERR("error writing file %s\n", filename);
1914 HeapFree(GetProcessHeap(), 0, filename);
1917 WINE_ERR("out of memory\n");
1921 static BOOL is_extension_blacklisted(LPCWSTR extension)
1923 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1924 static const WCHAR comW[] = {'.','c','o','m',0};
1925 static const WCHAR exeW[] = {'.','e','x','e',0};
1926 static const WCHAR msiW[] = {'.','m','s','i',0};
1928 if (!strcmpiW(extension, comW) ||
1929 !strcmpiW(extension, exeW) ||
1930 !strcmpiW(extension, msiW))
1935 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1936 const char *friendlyAppName, const char *mimeType,
1942 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1943 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1944 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1946 desktop = fopen(desktopPath, "w");
1949 fprintf(desktop, "[Desktop Entry]\n");
1950 fprintf(desktop, "Type=Application\n");
1951 fprintf(desktop, "Name=%s\n", friendlyAppName);
1952 fprintf(desktop, "MimeType=%s\n", mimeType);
1953 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1954 fprintf(desktop, "NoDisplay=true\n");
1955 fprintf(desktop, "StartupNotify=true\n");
1960 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1964 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1966 static const WCHAR openW[] = {'o','p','e','n',0};
1967 struct list *nativeMimeTypes = NULL;
1970 BOOL hasChanged = FALSE;
1972 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1974 WINE_ERR("could not build native MIME types\n");
1980 WCHAR *extensionW = NULL;
1985 HeapFree(GetProcessHeap(), 0, extensionW);
1986 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1987 if (extensionW == NULL)
1989 WINE_ERR("out of memory\n");
1990 ret = ERROR_OUTOFMEMORY;
1993 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1995 } while (ret == ERROR_MORE_DATA);
1997 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1999 char *extensionA = NULL;
2000 WCHAR *commandW = NULL;
2001 WCHAR *friendlyDocNameW = NULL;
2002 char *friendlyDocNameA = NULL;
2003 WCHAR *iconW = NULL;
2005 WCHAR *contentTypeW = NULL;
2006 char *mimeTypeA = NULL;
2007 WCHAR *friendlyAppNameW = NULL;
2008 char *friendlyAppNameA = NULL;
2009 WCHAR *progIdW = NULL;
2010 char *progIdA = NULL;
2012 extensionA = wchars_to_utf8_chars(extensionW);
2013 if (extensionA == NULL)
2015 WINE_ERR("out of memory\n");
2019 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
2020 if (friendlyDocNameW)
2022 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
2023 if (friendlyDocNameA == NULL)
2025 WINE_ERR("out of memory\n");
2030 iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);
2032 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2034 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2037 if (mimeTypeA == NULL)
2039 if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2040 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2042 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2044 if (mimeTypeA != NULL)
2046 /* Gnome seems to ignore the <icon> tag in MIME packages,
2047 * and the default name is more intuitive anyway.
2051 char *flattened_mime = slashes_to_minuses(mimeTypeA);
2055 WCHAR *comma = strrchrW(iconW, ',');
2059 index = atoiW(comma + 1);
2061 iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2062 HeapFree(GetProcessHeap(), 0, flattened_mime);
2066 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
2071 WINE_FIXME("out of memory\n");
2076 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2077 if (commandW == NULL)
2078 /* no command => no application is associated */
2081 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
2082 if (friendlyAppNameW)
2084 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
2085 if (friendlyAppNameA == NULL)
2087 WINE_ERR("out of memory\n");
2093 friendlyAppNameA = heap_printf("A Wine application");
2094 if (friendlyAppNameA == NULL)
2096 WINE_ERR("out of memory\n");
2101 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
2104 progIdA = wchars_to_utf8_chars(progIdW);
2105 if (progIdA == NULL)
2107 WINE_ERR("out of memory\n");
2112 goto end; /* no progID => not a file type association */
2114 if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
2116 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
2119 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
2122 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
2124 HeapFree(GetProcessHeap(), 0, desktopPath);
2129 HeapFree(GetProcessHeap(), 0, extensionA);
2130 HeapFree(GetProcessHeap(), 0, commandW);
2131 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
2132 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2133 HeapFree(GetProcessHeap(), 0, iconW);
2134 HeapFree(GetProcessHeap(), 0, iconA);
2135 HeapFree(GetProcessHeap(), 0, contentTypeW);
2136 HeapFree(GetProcessHeap(), 0, mimeTypeA);
2137 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
2138 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
2139 HeapFree(GetProcessHeap(), 0, progIdW);
2140 HeapFree(GetProcessHeap(), 0, progIdA);
2142 HeapFree(GetProcessHeap(), 0, extensionW);
2143 if (ret != ERROR_SUCCESS)
2147 free_native_mime_types(nativeMimeTypes);
2151 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2153 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
2154 '\\','s','t','a','r','t','.','e','x','e',0};
2155 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2156 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
2157 WCHAR szTmp[INFOTIPSIZE];
2158 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2159 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
2160 int iIconId = 0, r = -1;
2163 char *unix_link = NULL;
2167 WINE_ERR("Link name is null\n");
2171 if( !GetLinkLocation( link, &csidl, &link_name ) )
2173 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2176 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2178 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2181 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2184 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
2185 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2186 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
2189 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
2190 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2191 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2193 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
2194 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
2195 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
2198 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
2199 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2200 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
2204 LPITEMIDLIST pidl = NULL;
2205 IShellLinkW_GetIDList( sl, &pidl );
2206 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2207 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
2210 /* extract the icon */
2212 icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2214 icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2216 /* fail - try once again after parent process exit */
2221 WINE_WARN("Unable to extract icon, deferring.\n");
2224 WINE_ERR("failed to extract icon from %s\n",
2225 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2228 unix_link = wine_get_unix_file_name(link);
2229 if (unix_link == NULL)
2231 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2235 /* check the path */
2238 static const WCHAR exeW[] = {'.','e','x','e',0};
2241 /* check for .exe extension */
2242 if (!(p = strrchrW( szPath, '.' )) ||
2243 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2244 lstrcmpiW( p, exeW ))
2246 /* Not .exe - use 'start.exe' to launch this file */
2247 p = szArgs + lstrlenW(szPath) + 2;
2251 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2252 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2258 lstrcpyW(szArgs + 1, szPath);
2261 GetWindowsDirectoryW(szPath, MAX_PATH);
2262 lstrcatW(szPath, startW);
2265 /* convert app working dir */
2267 work_dir = wine_get_unix_file_name( szWorkDir );
2271 /* if there's no path... try run the link itself */
2272 lstrcpynW(szArgs, link, MAX_PATH);
2273 GetWindowsDirectoryW(szPath, MAX_PATH);
2274 lstrcatW(szPath, startW);
2277 /* escape the path and parameters */
2278 escaped_path = escape(szPath);
2279 escaped_args = escape(szArgs);
2280 escaped_description = escape(szDescription);
2282 /* building multiple menus concurrently has race conditions */
2283 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2284 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2286 WINE_ERR("failed wait for semaphore\n");
2290 if (in_desktop_dir(csidl))
2293 const char *lastEntry;
2294 lastEntry = strrchr(link_name, '/');
2295 if (lastEntry == NULL)
2296 lastEntry = link_name;
2299 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2302 r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2303 HeapFree(GetProcessHeap(), 0, location);
2307 r = !write_menu_entry(unix_link, link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2309 ReleaseSemaphore( hsem, 1, NULL );
2312 if (hsem) CloseHandle( hsem );
2313 HeapFree( GetProcessHeap(), 0, icon_name );
2314 HeapFree( GetProcessHeap(), 0, work_dir );
2315 HeapFree( GetProcessHeap(), 0, link_name );
2316 HeapFree( GetProcessHeap(), 0, escaped_args );
2317 HeapFree( GetProcessHeap(), 0, escaped_path );
2318 HeapFree( GetProcessHeap(), 0, escaped_description );
2319 HeapFree( GetProcessHeap(), 0, unix_link);
2322 WINE_ERR("failed to build the menu\n" );
2327 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2329 char *link_name = NULL;
2332 char *escaped_urlPath = NULL;
2337 char *unix_link = NULL;
2341 WINE_ERR("Link name is null\n");
2345 if( !GetLinkLocation( link, &csidl, &link_name ) )
2347 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2350 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2352 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2356 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2358 hr = url->lpVtbl->GetURL(url, &urlPath);
2364 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2366 unix_link = wine_get_unix_file_name(link);
2367 if (unix_link == NULL)
2369 WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
2373 escaped_urlPath = escape(urlPath);
2375 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2376 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2378 WINE_ERR("failed wait for semaphore\n");
2381 if (in_desktop_dir(csidl))
2384 const char *lastEntry;
2385 lastEntry = strrchr(link_name, '/');
2386 if (lastEntry == NULL)
2387 lastEntry = link_name;
2390 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2393 r = !write_desktop_entry(NULL, location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2394 HeapFree(GetProcessHeap(), 0, location);
2398 r = !write_menu_entry(unix_link, link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2400 ReleaseSemaphore(hSem, 1, NULL);
2405 HeapFree(GetProcessHeap(), 0, link_name);
2406 CoTaskMemFree( urlPath );
2407 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2408 HeapFree(GetProcessHeap(), 0, unix_link);
2412 static BOOL WaitForParentProcess( void )
2414 PROCESSENTRY32 procentry;
2415 HANDLE hsnapshot = NULL, hprocess = NULL;
2416 DWORD ourpid = GetCurrentProcessId();
2417 BOOL ret = FALSE, rc;
2419 WINE_TRACE("Waiting for parent process\n");
2420 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2421 INVALID_HANDLE_VALUE)
2423 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2427 procentry.dwSize = sizeof(PROCESSENTRY32);
2428 rc = Process32First( hsnapshot, &procentry );
2431 if (procentry.th32ProcessID == ourpid) break;
2432 rc = Process32Next( hsnapshot, &procentry );
2436 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2440 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2443 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2448 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2451 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2454 if (hprocess) CloseHandle( hprocess );
2455 if (hsnapshot) CloseHandle( hsnapshot );
2459 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2464 WCHAR fullname[MAX_PATH];
2467 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2471 WINE_ERR("link name missing\n");
2475 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2476 if (len==0 || len>MAX_PATH)
2478 WINE_ERR("couldn't get full path of link file\n");
2482 r = CoInitialize( NULL );
2485 WINE_ERR("CoInitialize failed\n");
2489 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2490 &IID_IShellLinkW, (LPVOID *) &sl );
2493 WINE_ERR("No IID_IShellLink\n");
2497 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2500 WINE_ERR("No IID_IPersistFile\n");
2504 r = IPersistFile_Load( pf, fullname, STGM_READ );
2505 if( SUCCEEDED( r ) )
2507 /* If something fails (eg. Couldn't extract icon)
2508 * wait for parent process and try again
2510 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2512 WaitForParentProcess();
2513 InvokeShellLinker( sl, fullname, FALSE );
2518 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2521 IPersistFile_Release( pf );
2522 IShellLinkW_Release( sl );
2529 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2531 IUniformResourceLocatorW *url;
2534 WCHAR fullname[MAX_PATH];
2537 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2541 WINE_ERR("URL name missing\n");
2545 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2546 if (len==0 || len>MAX_PATH)
2548 WINE_ERR("couldn't get full path of URL file\n");
2552 r = CoInitialize( NULL );
2555 WINE_ERR("CoInitialize failed\n");
2559 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2560 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2563 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2567 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2570 WINE_ERR("No IID_IPersistFile\n");
2573 r = IPersistFile_Load( pf, fullname, STGM_READ );
2574 if( SUCCEEDED( r ) )
2576 /* If something fails (eg. Couldn't extract icon)
2577 * wait for parent process and try again
2579 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2581 WaitForParentProcess();
2582 InvokeShellLinkerForURL( url, fullname, FALSE );
2586 IPersistFile_Release( pf );
2587 url->lpVtbl->Release( url );
2594 static void RefreshFileTypeAssociations(void)
2597 char *mime_dir = NULL;
2598 char *packages_dir = NULL;
2599 char *applications_dir = NULL;
2602 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2603 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2605 WINE_ERR("failed wait for semaphore\n");
2611 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2612 if (mime_dir == NULL)
2614 WINE_ERR("out of memory\n");
2617 create_directories(mime_dir);
2619 packages_dir = heap_printf("%s/packages", mime_dir);
2620 if (packages_dir == NULL)
2622 WINE_ERR("out of memory\n");
2625 create_directories(packages_dir);
2627 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2628 if (applications_dir == NULL)
2630 WINE_ERR("out of memory\n");
2633 create_directories(applications_dir);
2635 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2636 hasChanged |= cleanup_associations();
2639 const char *argv[3];
2641 argv[0] = "update-mime-database";
2644 spawnvp( _P_NOWAIT, argv[0], argv );
2646 argv[0] = "update-desktop-database";
2647 argv[1] = applications_dir;
2648 spawnvp( _P_NOWAIT, argv[0], argv );
2654 ReleaseSemaphore(hSem, 1, NULL);
2657 HeapFree(GetProcessHeap(), 0, mime_dir);
2658 HeapFree(GetProcessHeap(), 0, packages_dir);
2659 HeapFree(GetProcessHeap(), 0, applications_dir);
2662 static void cleanup_menus(void)
2666 hkey = open_menus_reg_key();
2670 LSTATUS lret = ERROR_SUCCESS;
2671 for (i = 0; lret == ERROR_SUCCESS; )
2673 WCHAR *value = NULL;
2675 DWORD valueSize = 4096;
2676 DWORD dataSize = 4096;
2679 lret = ERROR_OUTOFMEMORY;
2680 value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
2683 data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
2686 lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
2687 if (lret == ERROR_SUCCESS || lret != ERROR_MORE_DATA)
2691 HeapFree(GetProcessHeap(), 0, value);
2692 HeapFree(GetProcessHeap(), 0, data);
2693 value = data = NULL;
2695 if (lret == ERROR_SUCCESS)
2699 unix_file = wchars_to_unix_chars(value);
2700 windows_file = wchars_to_unix_chars(data);
2701 if (unix_file != NULL && windows_file != NULL)
2703 struct stat filestats;
2704 if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
2706 WINE_TRACE("removing menu related file %s\n", unix_file);
2708 RegDeleteValueW(hkey, value);
2715 WINE_ERR("out of memory enumerating menus\n");
2716 lret = ERROR_OUTOFMEMORY;
2718 HeapFree(GetProcessHeap(), 0, unix_file);
2719 HeapFree(GetProcessHeap(), 0, windows_file);
2721 else if (lret != ERROR_NO_MORE_ITEMS)
2722 WINE_ERR("error %d reading registry\n", lret);
2723 HeapFree(GetProcessHeap(), 0, value);
2724 HeapFree(GetProcessHeap(), 0, data);
2729 WINE_ERR("error opening registry key, menu cleanup failed\n");
2732 static WCHAR *next_token( LPWSTR *p )
2734 LPWSTR token = NULL, t = *p;
2739 while( t && !token )
2747 /* unquote the token */
2749 t = strchrW( token, '"' );
2758 t = strchrW( token, ' ' );
2768 static BOOL init_xdg(void)
2770 WCHAR shellDesktopPath[MAX_PATH];
2771 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2773 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2774 if (xdg_desktop_dir == NULL)
2776 WINE_ERR("error looking up the desktop directory\n");
2780 if (getenv("XDG_CONFIG_HOME"))
2781 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2783 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2786 create_directories(xdg_config_dir);
2787 if (getenv("XDG_DATA_HOME"))
2788 xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
2790 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2794 create_directories(xdg_data_dir);
2795 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2798 mkdir(buffer, 0777);
2799 HeapFree(GetProcessHeap(), 0, buffer);
2803 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2805 WINE_ERR("out of memory\n");
2809 /***********************************************************************
2813 int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
2815 static const WCHAR dash_aW[] = {'-','a',0};
2816 static const WCHAR dash_rW[] = {'-','r',0};
2817 static const WCHAR dash_uW[] = {'-','u',0};
2818 static const WCHAR dash_wW[] = {'-','w',0};
2820 LPWSTR token = NULL, p;
2828 for( p = cmdline; p && *p; )
2830 token = next_token( &p );
2833 if( !strcmpW( token, dash_aW ) )
2835 RefreshFileTypeAssociations();
2838 if( !strcmpW( token, dash_rW ) )
2843 if( !strcmpW( token, dash_wW ) )
2845 else if ( !strcmpW( token, dash_uW ) )
2847 else if( token[0] == '-' )
2849 WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
2856 bRet = Process_URL( token, bWait );
2858 bRet = Process_Link( token, bWait );
2861 WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );