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
57 #include "wine/port.h"
82 #include "wine/unicode.h"
83 #include "wine/debug.h"
84 #include "wine/library.h"
85 #include "wine/list.h"
93 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
95 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
96 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
97 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
98 (csidl)==CSIDL_COMMON_STARTMENU)
100 /* link file formats */
102 #include "pshpack1.h"
121 GRPICONDIRENTRY idEntries[1];
159 static char *xdg_config_dir;
160 static char *xdg_data_dir;
161 static char *xdg_desktop_dir;
163 /* Icon extraction routines
165 * FIXME: should use PrivateExtractIcons and friends
166 * FIXME: should not use stdio
169 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
171 /* PNG-specific code */
174 static void *libpng_handle;
175 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
176 MAKE_FUNCPTR(png_create_info_struct);
177 MAKE_FUNCPTR(png_create_write_struct);
178 MAKE_FUNCPTR(png_destroy_write_struct);
179 MAKE_FUNCPTR(png_init_io);
180 MAKE_FUNCPTR(png_set_bgr);
181 MAKE_FUNCPTR(png_set_text);
182 MAKE_FUNCPTR(png_set_IHDR);
183 MAKE_FUNCPTR(png_write_end);
184 MAKE_FUNCPTR(png_write_info);
185 MAKE_FUNCPTR(png_write_row);
188 static void *load_libpng(void)
190 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
192 #define LOAD_FUNCPTR(f) \
193 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
194 libpng_handle = NULL; \
197 LOAD_FUNCPTR(png_create_info_struct);
198 LOAD_FUNCPTR(png_create_write_struct);
199 LOAD_FUNCPTR(png_destroy_write_struct);
200 LOAD_FUNCPTR(png_init_io);
201 LOAD_FUNCPTR(png_set_bgr);
202 LOAD_FUNCPTR(png_set_IHDR);
203 LOAD_FUNCPTR(png_set_text);
204 LOAD_FUNCPTR(png_write_end);
205 LOAD_FUNCPTR(png_write_info);
206 LOAD_FUNCPTR(png_write_row);
209 return libpng_handle;
212 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
214 static const char comment_key[] = "Created from";
219 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
220 BYTE *row, *copy = NULL;
221 const BYTE *pXOR, *pAND = NULL;
222 int nWidth = pIcon->bmiHeader.biWidth;
223 int nHeight = pIcon->bmiHeader.biHeight;
224 int nBpp = pIcon->bmiHeader.biBitCount;
229 color_type |= PNG_COLOR_MASK_ALPHA;
232 color_type |= PNG_COLOR_MASK_COLOR;
238 if (!libpng_handle && !load_libpng())
240 WINE_WARN("Unable to load libpng\n");
244 if (!(fp = fopen(png_filename, "w")))
246 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
250 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
251 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
252 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
253 if (nHeight > nWidth)
256 pAND = pXOR + nHeight * nXORWidthBytes;
259 /* Apply mask if present */
264 /* copy bytes before modifying them */
265 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
266 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
269 /* image and mask are upside down reversed */
270 row = copy + (nHeight - 1) * nXORWidthBytes;
272 /* top left corner */
273 bgColor.rgbRed = row[0];
274 bgColor.rgbGreen = row[1];
275 bgColor.rgbBlue = row[2];
276 bgColor.rgbReserved = 0;
278 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
279 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
282 RGBQUAD *pixel = (RGBQUAD *)row;
283 pixel->rgbBlue = bgColor.rgbBlue;
284 pixel->rgbGreen = bgColor.rgbGreen;
285 pixel->rgbRed = bgColor.rgbRed;
287 pixel->rgbReserved = bgColor.rgbReserved;
293 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
294 !(info_ptr = ppng_create_info_struct(png_ptr)))
297 if (setjmp(png_jmpbuf(png_ptr)))
299 /* All future errors jump here */
300 WINE_ERR("png error\n");
304 ppng_init_io(png_ptr, fp);
305 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
308 PNG_COMPRESSION_TYPE_DEFAULT,
309 PNG_FILTER_TYPE_DEFAULT);
312 comment.compression = PNG_TEXT_COMPRESSION_NONE;
313 comment.key = (png_charp)comment_key;
314 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
315 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
316 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
317 comment.text_length = i - 1;
318 ppng_set_text(png_ptr, info_ptr, &comment, 1);
321 ppng_write_info(png_ptr, info_ptr);
322 ppng_set_bgr(png_ptr);
323 for (i = nHeight - 1; i >= 0 ; i--)
324 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
325 ppng_write_end(png_ptr, info_ptr);
327 ppng_destroy_write_struct(&png_ptr, &info_ptr);
328 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
330 HeapFree(GetProcessHeap(), 0, copy);
331 HeapFree(GetProcessHeap(), 0, comment.text);
335 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
337 unlink(png_filename);
338 HeapFree(GetProcessHeap(), 0, copy);
339 HeapFree(GetProcessHeap(), 0, comment.text);
342 #endif /* SONAME_LIBPNG */
344 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
354 BOOL aColorUsed[256] = {0};
359 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
361 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
365 if (!(fXPMFile = fopen(szXPMFileName, "w")))
367 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
371 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
372 comment = HeapAlloc(GetProcessHeap(), 0, i);
373 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
375 nHeight = pIcon->bmiHeader.biHeight / 2;
376 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
377 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
378 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
379 + ((pIcon->bmiHeader.biWidth % 32) > 0));
380 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
381 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
382 : 1 << pIcon->bmiHeader.biBitCount;
383 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
384 pAND = pXOR + nHeight * nXORWidthBytes;
386 #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)
388 for (i = 0; i < nHeight; i++) {
389 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
390 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
392 aColorUsed[COLOR(j,i)] = TRUE;
398 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
400 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
401 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
404 for (i = 0; i < nColors; i++) {
406 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
407 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
410 if (fprintf(fXPMFile, "\" c None\"") <= 0)
413 for (i = 0; i < nHeight; i++)
415 if (fprintf(fXPMFile, ",\n\"") <= 0)
417 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
421 if (fprintf(fXPMFile, " ") <= 0)
425 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
428 if (fprintf(fXPMFile, "\"") <= 0)
431 if (fprintf(fXPMFile, "};\n") <= 0)
437 HeapFree(GetProcessHeap(), 0, comment);
442 HeapFree(GetProcessHeap(), 0, comment);
444 unlink( szXPMFileName );
448 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
450 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
452 if (!sEnumRes->nIndex--)
454 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
461 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
465 LPCWSTR lpName = NULL;
467 GRPICONDIR *pIconDir;
469 ENUMRESSTRUCT sEnumRes;
475 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
478 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
479 wine_dbgstr_w(szFileName), GetLastError());
485 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
486 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
487 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
492 sEnumRes.pResInfo = &hResInfo;
493 sEnumRes.nIndex = nIndex;
494 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
495 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
496 sEnumRes.nIndex != -1)
498 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
504 if ((hResData = LoadResource(hModule, hResInfo)))
506 if ((pIconDir = LockResource(hResData)))
508 for (i = 0; i < pIconDir->idCount; i++)
510 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
512 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
514 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
515 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
516 nMaxBits = pIconDir->idEntries[i].wBitCount;
522 FreeResource(hResData);
527 WINE_WARN("found no icon\n");
528 FreeLibrary(hModule);
532 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
534 if ((hResData = LoadResource(hModule, hResInfo)))
536 if ((pIcon = LockResource(hResData)))
539 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
544 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
545 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
550 FreeResource(hResData);
554 FreeLibrary(hModule);
558 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
560 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
561 !extract_icon16(szFileName, szXPMFileName)*/)
566 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
568 FILE *fICOFile = NULL;
570 ICONDIRENTRY *pIconDirEntry = NULL;
571 int nMax = 0, nMaxBits = 0;
575 char *filename = NULL;
577 filename = wine_get_unix_file_name(szFileName);
578 if (!(fICOFile = fopen(filename, "r")))
580 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
584 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
585 (iconDir.idReserved != 0) || (iconDir.idType != 1))
587 WINE_WARN("Invalid ico file format\n");
591 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
593 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
596 for (i = 0; i < iconDir.idCount; i++)
598 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
599 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
600 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
603 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
604 nMaxBits = pIconDirEntry[i].wBitCount;
607 WINE_TRACE("Selected: %d\n", nIndex);
609 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
611 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
613 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
617 /* Prefer PNG over XPM */
619 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
622 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
623 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
627 HeapFree(GetProcessHeap(), 0, pIcon);
628 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
630 HeapFree(GetProcessHeap(), 0, filename);
634 HeapFree(GetProcessHeap(), 0, pIcon);
635 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
636 if (fICOFile) fclose(fICOFile);
637 HeapFree(GetProcessHeap(), 0, filename);
641 static BOOL create_default_icon( const char *filename, const char* comment )
646 if (!(fXPM = fopen(filename, "w"))) return FALSE;
647 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
649 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
650 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
653 if (fprintf( fXPM, "};\n" ) <=0)
664 static unsigned short crc16(const char* string)
666 unsigned short crc = 0;
669 for (i = 0; string[i] != 0; i++)
672 for (j = 0; j < 8; c >>= 1, j++)
674 xor_poly = (c ^ crc) & 1;
683 static char* heap_printf(const char *format, ...)
690 va_start(args, format);
693 buffer = HeapAlloc(GetProcessHeap(), 0, size);
696 n = vsnprintf(buffer, size, format, args);
703 HeapFree(GetProcessHeap(), 0, buffer);
709 static BOOL create_directories(char *directory)
714 for (i = 0; directory[i]; i++)
716 if (i > 0 && directory[i] == '/')
719 mkdir(directory, 0777);
723 if (mkdir(directory, 0777) && errno != EEXIST)
729 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
730 static char *extract_icon( LPCWSTR path, int index, BOOL bWait )
733 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
737 /* Where should we save the icon? */
738 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
739 iconsdir = heap_printf("%s/icons", xdg_data_dir);
742 if (mkdir(iconsdir, 0777) && errno != EEXIST)
744 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
750 WINE_TRACE("no icon created\n");
754 /* Determine the icon base name */
755 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
756 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
757 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
760 if (*s=='/' || *s=='\\') {
768 if (*ico_name=='\\') *ico_name++='\0';
769 s=strrchr(ico_name,'.');
772 /* Compute the source-path hash */
775 /* Try to treat the source file as an exe */
776 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
777 sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
778 if (ExtractFromEXEDLL( path, index, xpm_path ))
781 /* Must be something else, ignore the index in that case */
782 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
783 if (ExtractFromICO( path, xpm_path))
787 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
788 if (create_default_icon( xpm_path, ico_path ))
792 HeapFree( GetProcessHeap(), 0, xpm_path );
796 HeapFree(GetProcessHeap(), 0, iconsdir);
797 HeapFree(GetProcessHeap(), 0, ico_path);
801 static BOOL write_desktop_entry(const char *location, const char *linkname, const char *path,
802 const char *args, const char *descr, const char *workdir,
807 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(location),
808 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
809 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
811 file = fopen(location, "w");
815 fprintf(file, "[Desktop Entry]\n");
816 fprintf(file, "Name=%s\n", linkname);
817 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
818 wine_get_config_dir(), path, args);
819 fprintf(file, "Type=Application\n");
820 fprintf(file, "StartupNotify=true\n");
821 if (descr && lstrlenA(descr))
822 fprintf(file, "Comment=%s\n", descr);
823 if (workdir && lstrlenA(workdir))
824 fprintf(file, "Path=%s\n", workdir);
825 if (icon && lstrlenA(icon))
826 fprintf(file, "Icon=%s\n", icon);
832 static BOOL write_directory_entry(const char *directory, const char *location)
836 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
838 file = fopen(location, "w");
842 fprintf(file, "[Desktop Entry]\n");
843 fprintf(file, "Type=Directory\n");
844 if (strcmp(directory, "wine") == 0)
846 fprintf(file, "Name=Wine\n");
847 fprintf(file, "Icon=wine\n");
851 fprintf(file, "Name=%s\n", directory);
852 fprintf(file, "Icon=folder\n");
859 static BOOL write_menu_file(const char *filename)
862 FILE *tempfile = NULL;
865 char *menuPath = NULL;
870 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
874 tempfilename = tempnam(xdg_config_dir, "_wine");
877 int tempfd = open(tempfilename, O_EXCL | O_CREAT | O_WRONLY, 0666);
880 tempfile = fdopen(tempfd, "w");
886 else if (errno == EEXIST)
896 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
897 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
898 fprintf(tempfile, "<Menu>\n");
899 fprintf(tempfile, " <Name>Applications</Name>\n");
901 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
902 if (name == NULL) goto end;
904 for (i = 0; filename[i]; i++)
906 name[i] = filename[i];
907 if (filename[i] == '/')
912 fprintf(tempfile, " <Menu>\n");
913 fprintf(tempfile, " <Name>%s%s</Name>\n", count ? "" : "wine-", name);
914 fprintf(tempfile, " <Directory>%s%s.directory</Directory>\n", count ? "" : "wine-", name);
915 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
916 xdg_data_dir, count ? "" : "wine-", name);
919 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
920 write_directory_entry(lastEntry, dir_file_name);
921 HeapFree(GetProcessHeap(), 0, dir_file_name);
924 lastEntry = &name[i+1];
930 fprintf(tempfile, " <Include>\n");
931 fprintf(tempfile, " <Filename>%s</Filename>\n", name);
932 fprintf(tempfile, " </Include>\n");
933 for (i = 0; i < count; i++)
934 fprintf(tempfile, " </Menu>\n");
935 fprintf(tempfile, "</Menu>\n");
937 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
938 if (menuPath == NULL) goto end;
939 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
946 ret = (rename(tempfilename, menuPath) == 0);
947 if (!ret && tempfilename)
948 remove(tempfilename);
950 HeapFree(GetProcessHeap(), 0, name);
951 HeapFree(GetProcessHeap(), 0, menuPath);
955 static BOOL write_menu_entry(const char *link, const char *path, const char *args,
956 const char *descr, const char *workdir, const char *icon)
958 const char *linkname;
959 char *desktopPath = NULL;
961 char *filename = NULL;
964 WINE_TRACE("(%s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(link), wine_dbgstr_a(path),
965 wine_dbgstr_a(args), wine_dbgstr_a(descr), wine_dbgstr_a(workdir),
966 wine_dbgstr_a(icon));
968 linkname = strrchr(link, '/');
969 if (linkname == NULL)
974 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
977 WINE_WARN("out of memory creating menu entry\n");
981 desktopDir = strrchr(desktopPath, '/');
983 if (!create_directories(desktopPath))
985 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
990 if (!write_desktop_entry(desktopPath, linkname, path, args, descr, workdir, icon))
992 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
997 filename = heap_printf("wine/%s.desktop", link);
998 if (!filename || !write_menu_file(filename))
1000 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1005 HeapFree(GetProcessHeap(), 0, desktopPath);
1006 HeapFree(GetProcessHeap(), 0, filename);
1010 /* This escapes \ in filenames */
1011 static LPSTR escape(LPCWSTR arg)
1018 while((esc = strchrW(esc, '\\')))
1024 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1025 narg = HeapAlloc(GetProcessHeap(), 0, len);
1030 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1034 *x++='\\'; /* escape \ */
1041 /* Return a heap-allocated copy of the unix format difference between the two
1042 * Windows-format paths.
1043 * locn is the owning location
1044 * link is within locn
1046 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1048 char *unix_locn, *unix_link;
1049 char *relative = NULL;
1051 unix_locn = wine_get_unix_file_name(locn);
1052 unix_link = wine_get_unix_file_name(link);
1053 if (unix_locn && unix_link)
1055 size_t len_unix_locn, len_unix_link;
1056 len_unix_locn = strlen (unix_locn);
1057 len_unix_link = strlen (unix_link);
1058 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1061 char *p = strrchr (unix_link + len_unix_locn, '/');
1062 p = strrchr (p, '.');
1066 len_unix_link = p - unix_link;
1068 len_rel = len_unix_link - len_unix_locn;
1069 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1072 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1077 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1078 HeapFree(GetProcessHeap(), 0, unix_locn);
1079 HeapFree(GetProcessHeap(), 0, unix_link);
1083 /***********************************************************************
1087 * returns TRUE if successful
1088 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1089 * *relative will contain the address of a heap-allocated copy of the portion
1090 * of the filename that is within the specified location, in unix form
1092 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1094 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1095 DWORD len, i, r, filelen;
1096 const DWORD locations[] = {
1097 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1098 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1099 CSIDL_COMMON_STARTMENU };
1101 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1102 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1103 if (filelen==0 || filelen>MAX_PATH)
1106 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1108 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1109 * expand or our hardcoded list won't match.
1111 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1112 if (filelen==0 || filelen>MAX_PATH)
1115 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1117 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1119 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1122 len = lstrlenW(buffer);
1123 if (len >= MAX_PATH)
1124 continue; /* We've just trashed memory! Hopefully we are OK */
1126 if (len > filelen || filename[len]!='\\')
1128 /* do a lstrcmpinW */
1130 r = lstrcmpiW( filename, buffer );
1131 filename[len] = '\\';
1135 /* return the remainder of the string and link type */
1136 *loc = locations[i];
1137 *relative = relative_path (filename, buffer);
1138 return (*relative != NULL);
1144 /* gets the target path directly or through MSI */
1145 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1146 LPWSTR szArgs, DWORD argsSize)
1148 IShellLinkDataList *dl = NULL;
1149 EXP_DARWIN_LINK *dar = NULL;
1155 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1156 if (hr == S_OK && szPath[0])
1158 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1162 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1166 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1173 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1174 if (hr == ERROR_SUCCESS)
1177 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1178 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1179 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1180 if (hr == ERROR_SUCCESS)
1183 int bcount, in_quotes;
1185 /* Extract the application path */
1192 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1194 /* skip the remaining spaces */
1197 } while (*s==0x0009 || *s==0x0020);
1200 else if (*s==0x005c)
1206 else if (*s==0x0022)
1209 if ((bcount & 1)==0)
1211 /* Preceded by an even number of '\', this is
1212 * half that number of '\', plus a quote which
1216 in_quotes=!in_quotes;
1221 /* Preceded by an odd number of '\', this is
1222 * half that number of '\' followed by a '"'
1232 /* a regular character */
1236 if ((d-szPath) == pathSize)
1238 /* Keep processing the path till we get to the
1239 * arguments, but 'stand still'
1244 /* Close the application path */
1247 lstrcpynW(szArgs, s, argsSize);
1249 HeapFree( GetProcessHeap(), 0, szCmdline );
1254 IShellLinkDataList_Release( dl );
1258 static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
1261 WCHAR *value = NULL;
1263 hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
1266 value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1269 hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
1272 HeapFree(GetProcessHeap(), 0, value);
1280 static char* wchars_to_utf8_chars(LPCWSTR string)
1283 INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
1284 ret = HeapAlloc(GetProcessHeap(), 0, size);
1286 WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
1290 static BOOL next_line(FILE *file, char **line, int *size)
1297 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1299 while (*line != NULL)
1301 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1303 HeapFree(GetProcessHeap(), 0, *line);
1309 pos = strlen(*line);
1310 cr = strchr(*line, '\n');
1315 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1320 HeapFree(GetProcessHeap(), 0, *line);
1333 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1335 char *globs_filename = NULL;
1337 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1340 FILE *globs_file = fopen(globs_filename, "r");
1341 if (globs_file) /* doesn't have to exist */
1345 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1348 struct xdg_mime_type *mime_type_entry = NULL;
1349 if (line[0] != '#' && (pos = strchr(line, ':')))
1351 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1352 if (mime_type_entry)
1355 mime_type_entry->mimeType = heap_printf("%s", line);
1356 mime_type_entry->glob = heap_printf("%s", pos + 1);
1357 if (mime_type_entry->mimeType && mime_type_entry->glob)
1358 list_add_tail(mime_types, &mime_type_entry->entry);
1361 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1362 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1363 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1371 HeapFree(GetProcessHeap(), 0, line);
1374 HeapFree(GetProcessHeap(), 0, globs_filename);
1381 static void free_native_mime_types(struct list *native_mime_types)
1383 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1385 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1387 list_remove(&mime_type_entry->entry);
1388 HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
1389 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1390 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1392 HeapFree(GetProcessHeap(), 0, native_mime_types);
1395 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1397 char *xdg_data_dirs;
1402 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1403 if (xdg_data_dirs == NULL)
1404 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1406 xdg_data_dirs = heap_printf("%s", xdg_data_dirs);
1410 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1416 list_init(*mime_types);
1417 ret = add_mimes(xdg_data_home, *mime_types);
1420 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1423 ret = add_mimes(begin, *mime_types);
1429 ret = add_mimes(begin, *mime_types);
1434 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1438 if (!ret && *mime_types)
1440 free_native_mime_types(*mime_types);
1446 static BOOL match_glob(struct list *native_mime_types, const char *extension,
1450 struct xdg_mime_type *mime_type_entry;
1451 int matchLength = 0;
1455 LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
1457 if (fnmatch(mime_type_entry->glob, extension, 0) == 0)
1459 if (*match == NULL || matchLength < strlen(mime_type_entry->glob))
1461 *match = mime_type_entry->mimeType;
1462 matchLength = strlen(mime_type_entry->glob);
1469 *match = heap_printf("%s", *match);
1479 static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
1480 const char *extensionA,
1484 WCHAR *lower_extensionW;
1486 BOOL ret = match_glob(native_mime_types, extensionA, mime_type);
1487 if (ret == FALSE || *mime_type != NULL)
1489 len = strlenW(extensionW);
1490 lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
1491 if (lower_extensionW)
1493 char *lower_extensionA;
1494 memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
1495 strlwrW(lower_extensionW);
1496 lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
1497 if (lower_extensionA)
1499 ret = match_glob(native_mime_types, lower_extensionA, mime_type);
1500 HeapFree(GetProcessHeap(), 0, lower_extensionA);
1505 WINE_FIXME("out of memory\n");
1507 HeapFree(GetProcessHeap(), 0, lower_extensionW);
1512 WINE_FIXME("out of memory\n");
1517 static CHAR* reg_get_valA(HKEY key, LPCSTR subkey, LPCSTR name)
1520 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1522 CHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1525 if (RegGetValueA(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1528 HeapFree(GetProcessHeap(), 0, ret);
1533 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1536 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1538 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1541 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1544 HeapFree(GetProcessHeap(), 0, ret);
1549 static HKEY open_associations_reg_key(void)
1551 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1552 '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};
1554 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1559 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1561 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1562 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1566 if ((assocKey = open_associations_reg_key()))
1573 valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1574 if (!valueA || lstrcmpA(valueA, mimeType))
1576 HeapFree(GetProcessHeap(), 0, valueA);
1578 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1579 if (!value || strcmpW(value, progId))
1581 HeapFree(GetProcessHeap(), 0, value);
1583 valueA = reg_get_valA(assocKey, extensionA, "AppName");
1584 if (!valueA || lstrcmpA(valueA, appName))
1586 HeapFree(GetProcessHeap(), 0, valueA);
1588 value = reg_get_valW(assocKey, extensionW, DocNameW);
1589 if (docName && (!value || strcmpW(value, docName)))
1591 HeapFree(GetProcessHeap(), 0, value);
1593 RegCloseKey(assocKey);
1597 WINE_ERR("error opening associations registry key\n");
1603 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1605 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1606 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1609 if ((assocKey = open_associations_reg_key()))
1612 if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1614 RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (BYTE*) mimeType, lstrlenA(mimeType) + 1);
1615 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1616 RegSetValueExA(subkey, "AppName", 0, REG_SZ, (BYTE*) appName, lstrlenA(appName) + 1);
1618 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1619 RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1620 RegCloseKey(subkey);
1623 WINE_ERR("could not create extension subkey\n");
1624 RegCloseKey(assocKey);
1627 WINE_ERR("could not open file associations key\n");
1630 static BOOL cleanup_associations(void)
1633 BOOL hasChanged = FALSE;
1634 if ((assocKey = open_associations_reg_key()))
1638 for (i = 0; !done; i++)
1640 WCHAR *extensionW = NULL;
1641 char *extensionA = NULL;
1647 HeapFree(GetProcessHeap(), 0, extensionW);
1648 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1649 if (extensionW == NULL)
1651 WINE_ERR("out of memory\n");
1652 ret = ERROR_OUTOFMEMORY;
1655 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1657 } while (ret == ERROR_MORE_DATA);
1659 if (ret == ERROR_SUCCESS)
1662 extensionA = wchars_to_utf8_chars(extensionW);
1663 if (extensionA == NULL)
1665 WINE_ERR("out of memory\n");
1669 command = assoc_query(ASSOCSTR_COMMAND, extensionW, NULL);
1670 if (command == NULL)
1672 char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1675 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1676 remove(desktopFile);
1678 RegDeleteKeyW(assocKey, extensionW);
1680 HeapFree(GetProcessHeap(), 0, desktopFile);
1682 HeapFree(GetProcessHeap(), 0, command);
1686 if (ret != ERROR_NO_MORE_ITEMS)
1687 WINE_ERR("error %d while reading registry\n", ret);
1691 HeapFree(GetProcessHeap(), 0, extensionA);
1692 HeapFree(GetProcessHeap(), 0, extensionW);
1694 RegCloseKey(assocKey);
1697 WINE_ERR("could not open file associations key\n");
1701 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1702 const char *mime_type, const char *comment)
1707 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1708 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1710 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1713 FILE *packageFile = fopen(filename, "w");
1716 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1717 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1718 fprintf(packageFile, " <mime-type type=\"%s\">\n", mime_type);
1719 fprintf(packageFile, " <glob pattern=\"*%s\"/>\n", dot_extension);
1721 fprintf(packageFile, " <comment>%s</comment>\n", comment);
1722 fprintf(packageFile, " </mime-type>\n");
1723 fprintf(packageFile, "</mime-info>\n");
1725 fclose(packageFile);
1728 WINE_ERR("error writing file %s\n", filename);
1729 HeapFree(GetProcessHeap(), 0, filename);
1732 WINE_ERR("out of memory\n");
1736 static BOOL is_extension_blacklisted(LPCWSTR extension)
1738 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1739 static const WCHAR comW[] = {'.','c','o','m',0};
1740 static const WCHAR exeW[] = {'.','e','x','e',0};
1741 static const WCHAR msiW[] = {'.','m','s','i',0};
1743 if (!strcmpiW(extension, comW) ||
1744 !strcmpiW(extension, exeW) ||
1745 !strcmpiW(extension, msiW))
1750 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1751 const char *friendlyAppName, const char *mimeType,
1757 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1758 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1759 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1761 desktop = fopen(desktopPath, "w");
1764 fprintf(desktop, "[Desktop Entry]\n");
1765 fprintf(desktop, "Type=Application\n");
1766 fprintf(desktop, "Name=%s\n", friendlyAppName);
1767 fprintf(desktop, "MimeType=%s\n", mimeType);
1768 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1769 fprintf(desktop, "NoDisplay=true\n");
1770 fprintf(desktop, "StartupNotify=true\n");
1775 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1779 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1781 struct list *nativeMimeTypes = NULL;
1784 BOOL hasChanged = FALSE;
1786 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1788 WINE_ERR("could not build native MIME types\n");
1794 WCHAR *extensionW = NULL;
1799 HeapFree(GetProcessHeap(), 0, extensionW);
1800 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1801 if (extensionW == NULL)
1803 WINE_ERR("out of memory\n");
1804 ret = ERROR_OUTOFMEMORY;
1807 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1809 } while (ret == ERROR_MORE_DATA);
1811 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1813 char *extensionA = NULL;
1814 WCHAR *commandW = NULL;
1815 WCHAR *friendlyDocNameW = NULL;
1816 char *friendlyDocNameA = NULL;
1817 WCHAR *contentTypeW = NULL;
1818 char *mimeTypeA = NULL;
1819 WCHAR *friendlyAppNameW = NULL;
1820 char *friendlyAppNameA = NULL;
1821 WCHAR *progIdW = NULL;
1822 char *progIdA = NULL;
1824 extensionA = wchars_to_utf8_chars(extensionW);
1825 if (extensionA == NULL)
1827 WINE_ERR("out of memory\n");
1831 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
1832 if (friendlyDocNameW)
1834 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
1835 if (friendlyDocNameA == NULL)
1837 WINE_ERR("out of memory\n");
1842 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
1844 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
1847 if (mimeTypeA == NULL)
1849 if (contentTypeW != NULL)
1850 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
1852 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
1854 if (mimeTypeA != NULL)
1856 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
1861 WINE_FIXME("out of memory\n");
1866 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, NULL);
1867 if (commandW == NULL)
1868 /* no command => no application is associated */
1871 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
1872 if (friendlyAppNameW)
1874 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
1875 if (friendlyAppNameA == NULL)
1877 WINE_ERR("out of memory\n");
1883 friendlyAppNameA = heap_printf("A Wine application");
1884 if (friendlyAppNameA == NULL)
1886 WINE_ERR("out of memory\n");
1891 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
1894 progIdA = wchars_to_utf8_chars(progIdW);
1895 if (progIdA == NULL)
1897 WINE_ERR("out of memory\n");
1902 goto end; /* no progID => not a file type association */
1904 if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
1906 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
1909 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
1912 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
1914 HeapFree(GetProcessHeap(), 0, desktopPath);
1919 HeapFree(GetProcessHeap(), 0, extensionA);
1920 HeapFree(GetProcessHeap(), 0, commandW);
1921 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
1922 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
1923 HeapFree(GetProcessHeap(), 0, contentTypeW);
1924 HeapFree(GetProcessHeap(), 0, mimeTypeA);
1925 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
1926 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
1927 HeapFree(GetProcessHeap(), 0, progIdW);
1928 HeapFree(GetProcessHeap(), 0, progIdA);
1930 HeapFree(GetProcessHeap(), 0, extensionW);
1931 if (ret != ERROR_SUCCESS)
1935 free_native_mime_types(nativeMimeTypes);
1939 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1941 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1942 '\\','s','t','a','r','t','.','e','x','e',0};
1943 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1944 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1945 WCHAR szTmp[INFOTIPSIZE];
1946 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1947 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1948 int iIconId = 0, r = -1;
1954 WINE_ERR("Link name is null\n");
1958 if( !GetLinkLocation( link, &csidl, &link_name ) )
1960 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1963 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1965 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1968 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1971 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1972 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1973 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
1976 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1977 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1978 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1980 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1981 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
1982 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
1985 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1986 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1987 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
1991 LPITEMIDLIST pidl = NULL;
1992 IShellLinkW_GetIDList( sl, &pidl );
1993 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1994 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
1997 /* extract the icon */
1999 icon_name = extract_icon( szIconPath , iIconId, bWait );
2001 icon_name = extract_icon( szPath, iIconId, bWait );
2003 /* fail - try once again after parent process exit */
2008 WINE_WARN("Unable to extract icon, deferring.\n");
2011 WINE_ERR("failed to extract icon from %s\n",
2012 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2015 /* check the path */
2018 static const WCHAR exeW[] = {'.','e','x','e',0};
2021 /* check for .exe extension */
2022 if (!(p = strrchrW( szPath, '.' )) ||
2023 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2024 lstrcmpiW( p, exeW ))
2026 /* Not .exe - use 'start.exe' to launch this file */
2027 p = szArgs + lstrlenW(szPath) + 2;
2031 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2032 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2038 lstrcpyW(szArgs + 1, szPath);
2041 GetWindowsDirectoryW(szPath, MAX_PATH);
2042 lstrcatW(szPath, startW);
2045 /* convert app working dir */
2047 work_dir = wine_get_unix_file_name( szWorkDir );
2051 /* if there's no path... try run the link itself */
2052 lstrcpynW(szArgs, link, MAX_PATH);
2053 GetWindowsDirectoryW(szPath, MAX_PATH);
2054 lstrcatW(szPath, startW);
2057 /* escape the path and parameters */
2058 escaped_path = escape(szPath);
2059 escaped_args = escape(szArgs);
2060 escaped_description = escape(szDescription);
2062 /* building multiple menus concurrently has race conditions */
2063 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2064 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2066 WINE_ERR("failed wait for semaphore\n");
2070 if (in_desktop_dir(csidl))
2073 const char *lastEntry;
2074 lastEntry = strrchr(link_name, '/');
2075 if (lastEntry == NULL)
2076 lastEntry = link_name;
2079 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2082 r = !write_desktop_entry(location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2083 HeapFree(GetProcessHeap(), 0, location);
2087 r = !write_menu_entry(link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2089 ReleaseSemaphore( hsem, 1, NULL );
2092 if (hsem) CloseHandle( hsem );
2093 HeapFree( GetProcessHeap(), 0, icon_name );
2094 HeapFree( GetProcessHeap(), 0, work_dir );
2095 HeapFree( GetProcessHeap(), 0, link_name );
2096 HeapFree( GetProcessHeap(), 0, escaped_args );
2097 HeapFree( GetProcessHeap(), 0, escaped_path );
2098 HeapFree( GetProcessHeap(), 0, escaped_description );
2101 WINE_ERR("failed to build the menu\n" );
2106 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2108 char *link_name = NULL;
2111 char *escaped_urlPath = NULL;
2119 WINE_ERR("Link name is null\n");
2123 if( !GetLinkLocation( link, &csidl, &link_name ) )
2125 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2128 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2130 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2134 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2136 hr = url->lpVtbl->GetURL(url, &urlPath);
2142 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2144 escaped_urlPath = escape(urlPath);
2146 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2147 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2149 WINE_ERR("failed wait for semaphore\n");
2152 if (in_desktop_dir(csidl))
2155 const char *lastEntry;
2156 lastEntry = strrchr(link_name, '/');
2157 if (lastEntry == NULL)
2158 lastEntry = link_name;
2161 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2164 r = !write_desktop_entry(location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2165 HeapFree(GetProcessHeap(), 0, location);
2169 r = !write_menu_entry(link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2171 ReleaseSemaphore(hSem, 1, NULL);
2176 HeapFree(GetProcessHeap(), 0, link_name);
2177 CoTaskMemFree( urlPath );
2178 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2182 static BOOL WaitForParentProcess( void )
2184 PROCESSENTRY32 procentry;
2185 HANDLE hsnapshot = NULL, hprocess = NULL;
2186 DWORD ourpid = GetCurrentProcessId();
2187 BOOL ret = FALSE, rc;
2189 WINE_TRACE("Waiting for parent process\n");
2190 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2191 INVALID_HANDLE_VALUE)
2193 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2197 procentry.dwSize = sizeof(PROCESSENTRY32);
2198 rc = Process32First( hsnapshot, &procentry );
2201 if (procentry.th32ProcessID == ourpid) break;
2202 rc = Process32Next( hsnapshot, &procentry );
2206 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2210 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2213 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2218 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2221 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2224 if (hprocess) CloseHandle( hprocess );
2225 if (hsnapshot) CloseHandle( hsnapshot );
2229 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2234 WCHAR fullname[MAX_PATH];
2237 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2241 WINE_ERR("link name missing\n");
2245 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2246 if (len==0 || len>MAX_PATH)
2248 WINE_ERR("couldn't get full path of link file\n");
2252 r = CoInitialize( NULL );
2255 WINE_ERR("CoInitialize failed\n");
2259 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2260 &IID_IShellLinkW, (LPVOID *) &sl );
2263 WINE_ERR("No IID_IShellLink\n");
2267 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2270 WINE_ERR("No IID_IPersistFile\n");
2274 r = IPersistFile_Load( pf, fullname, STGM_READ );
2275 if( SUCCEEDED( r ) )
2277 /* If something fails (eg. Couldn't extract icon)
2278 * wait for parent process and try again
2280 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2282 WaitForParentProcess();
2283 InvokeShellLinker( sl, fullname, FALSE );
2288 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2291 IPersistFile_Release( pf );
2292 IShellLinkW_Release( sl );
2299 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2301 IUniformResourceLocatorW *url;
2304 WCHAR fullname[MAX_PATH];
2307 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2311 WINE_ERR("URL name missing\n");
2315 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2316 if (len==0 || len>MAX_PATH)
2318 WINE_ERR("couldn't get full path of URL file\n");
2322 r = CoInitialize( NULL );
2325 WINE_ERR("CoInitialize failed\n");
2329 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2330 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2333 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2337 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2340 WINE_ERR("No IID_IPersistFile\n");
2343 r = IPersistFile_Load( pf, fullname, STGM_READ );
2344 if( SUCCEEDED( r ) )
2346 /* If something fails (eg. Couldn't extract icon)
2347 * wait for parent process and try again
2349 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2351 WaitForParentProcess();
2352 InvokeShellLinkerForURL( url, fullname, FALSE );
2356 IPersistFile_Release( pf );
2357 url->lpVtbl->Release( url );
2364 static void RefreshFileTypeAssociations(void)
2367 char *mime_dir = NULL;
2368 char *packages_dir = NULL;
2369 char *applications_dir = NULL;
2372 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2373 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2375 WINE_ERR("failed wait for semaphore\n");
2381 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2382 if (mime_dir == NULL)
2384 WINE_ERR("out of memory\n");
2387 create_directories(mime_dir);
2389 packages_dir = heap_printf("%s/packages", mime_dir);
2390 if (packages_dir == NULL)
2392 WINE_ERR("out of memory\n");
2395 create_directories(packages_dir);
2397 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2398 if (applications_dir == NULL)
2400 WINE_ERR("out of memory\n");
2403 create_directories(applications_dir);
2405 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2406 hasChanged |= cleanup_associations();
2409 char *command = heap_printf("update-mime-database %s", mime_dir);
2413 HeapFree(GetProcessHeap(), 0, command);
2417 WINE_ERR("out of memory\n");
2421 command = heap_printf("update-desktop-database %s/applications", xdg_data_dir);
2425 HeapFree(GetProcessHeap(), 0, command);
2429 WINE_ERR("out of memory\n");
2437 ReleaseSemaphore(hSem, 1, NULL);
2440 HeapFree(GetProcessHeap(), 0, mime_dir);
2441 HeapFree(GetProcessHeap(), 0, packages_dir);
2442 HeapFree(GetProcessHeap(), 0, applications_dir);
2445 static CHAR *next_token( LPSTR *p )
2447 LPSTR token = NULL, t = *p;
2452 while( t && !token )
2460 /* unquote the token */
2462 t = strchr( token, '"' );
2471 t = strchr( token, ' ' );
2481 static BOOL init_xdg(void)
2483 WCHAR shellDesktopPath[MAX_PATH];
2484 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2486 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2487 if (xdg_desktop_dir == NULL)
2489 WINE_ERR("error looking up the desktop directory\n");
2493 if (getenv("XDG_CONFIG_HOME"))
2494 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2496 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2499 create_directories(xdg_config_dir);
2500 if (getenv("XDG_DATA_HOME"))
2501 xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
2503 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2507 create_directories(xdg_data_dir);
2508 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2511 mkdir(buffer, 0777);
2512 HeapFree(GetProcessHeap(), 0, buffer);
2516 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2518 WINE_ERR("out of memory\n");
2522 /***********************************************************************
2526 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
2528 LPSTR token = NULL, p;
2536 for( p = cmdline; p && *p; )
2538 token = next_token( &p );
2541 if( !lstrcmpA( token, "-a" ) )
2543 RefreshFileTypeAssociations();
2546 if( !lstrcmpA( token, "-w" ) )
2548 else if ( !lstrcmpA( token, "-u" ) )
2550 else if( token[0] == '-' )
2552 WINE_ERR( "unknown option %s\n",token);
2556 WCHAR link[MAX_PATH];
2559 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2561 bRet = Process_URL( link, bWait );
2563 bRet = Process_Link( link, bWait );
2566 WINE_ERR( "failed to build menu item for %s\n",token);