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)
1532 static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
1535 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
1537 WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
1540 if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
1547 static HKEY open_associations_reg_key(void)
1549 static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
1550 '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};
1552 if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
1557 static BOOL has_association_changed(LPCSTR extensionA, LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName)
1559 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1560 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1564 if ((assocKey = open_associations_reg_key()))
1571 valueA = reg_get_valA(assocKey, extensionA, "MimeType");
1572 if (!valueA || lstrcmpA(valueA, mimeType))
1574 HeapFree(GetProcessHeap(), 0, valueA);
1576 value = reg_get_valW(assocKey, extensionW, ProgIDW);
1577 if (!value || strcmpW(value, progId))
1579 HeapFree(GetProcessHeap(), 0, value);
1581 valueA = reg_get_valA(assocKey, extensionA, "AppName");
1582 if (!valueA || lstrcmpA(valueA, appName))
1584 HeapFree(GetProcessHeap(), 0, valueA);
1586 value = reg_get_valW(assocKey, extensionW, DocNameW);
1587 if (docName && (!value || strcmpW(value, docName)))
1589 HeapFree(GetProcessHeap(), 0, value);
1591 RegCloseKey(assocKey);
1595 WINE_ERR("error opening associations registry key\n");
1601 static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId, LPCSTR appName, LPCWSTR docName, LPCSTR desktopFile)
1603 static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
1604 static const WCHAR DocNameW[] = {'D','o','c','N','a','m','e',0};
1607 if ((assocKey = open_associations_reg_key()))
1610 if (RegCreateKeyW(assocKey, extension, &subkey) == ERROR_SUCCESS)
1612 RegSetValueExA(subkey, "MimeType", 0, REG_SZ, (BYTE*) mimeType, lstrlenA(mimeType) + 1);
1613 RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
1614 RegSetValueExA(subkey, "AppName", 0, REG_SZ, (BYTE*) appName, lstrlenA(appName) + 1);
1616 RegSetValueExW(subkey, DocNameW, 0, REG_SZ, (BYTE*) docName, (lstrlenW(docName) + 1) * sizeof(WCHAR));
1617 RegSetValueExA(subkey, "DesktopFile", 0, REG_SZ, (BYTE*) desktopFile, (lstrlenA(desktopFile) + 1));
1618 RegCloseKey(subkey);
1621 WINE_ERR("could not create extension subkey\n");
1622 RegCloseKey(assocKey);
1625 WINE_ERR("could not open file associations key\n");
1628 static BOOL cleanup_associations(void)
1631 BOOL hasChanged = FALSE;
1632 if ((assocKey = open_associations_reg_key()))
1636 for (i = 0; !done; i++)
1638 WCHAR *extensionW = NULL;
1639 char *extensionA = NULL;
1645 HeapFree(GetProcessHeap(), 0, extensionW);
1646 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1647 if (extensionW == NULL)
1649 WINE_ERR("out of memory\n");
1650 ret = ERROR_OUTOFMEMORY;
1653 ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
1655 } while (ret == ERROR_MORE_DATA);
1657 if (ret == ERROR_SUCCESS)
1660 extensionA = wchars_to_utf8_chars(extensionW);
1661 if (extensionA == NULL)
1663 WINE_ERR("out of memory\n");
1667 command = assoc_query(ASSOCSTR_COMMAND, extensionW, NULL);
1668 if (command == NULL)
1670 char *desktopFile = reg_get_valA(assocKey, extensionA, "DesktopFile");
1673 WINE_TRACE("removing file type association for %s\n", wine_dbgstr_a(extensionA));
1674 remove(desktopFile);
1676 RegDeleteKeyW(assocKey, extensionW);
1678 HeapFree(GetProcessHeap(), 0, desktopFile);
1680 HeapFree(GetProcessHeap(), 0, command);
1684 if (ret != ERROR_NO_MORE_ITEMS)
1685 WINE_ERR("error %d while reading registry\n", ret);
1689 HeapFree(GetProcessHeap(), 0, extensionA);
1690 HeapFree(GetProcessHeap(), 0, extensionW);
1692 RegCloseKey(assocKey);
1695 WINE_ERR("could not open file associations key\n");
1699 static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
1700 const char *mime_type, const char *comment)
1705 WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
1706 wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));
1708 filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
1711 FILE *packageFile = fopen(filename, "w");
1714 fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1715 fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
1716 fprintf(packageFile, " <mime-type type=\"%s\">\n", mime_type);
1717 fprintf(packageFile, " <glob pattern=\"*%s\"/>\n", dot_extension);
1719 fprintf(packageFile, " <comment>%s</comment>\n", comment);
1720 fprintf(packageFile, " </mime-type>\n");
1721 fprintf(packageFile, "</mime-info>\n");
1723 fclose(packageFile);
1726 WINE_ERR("error writing file %s\n", filename);
1727 HeapFree(GetProcessHeap(), 0, filename);
1730 WINE_ERR("out of memory\n");
1734 static BOOL is_extension_blacklisted(LPCWSTR extension)
1736 /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
1737 static const WCHAR comW[] = {'.','c','o','m',0};
1738 static const WCHAR exeW[] = {'.','e','x','e',0};
1739 static const WCHAR msiW[] = {'.','m','s','i',0};
1741 if (!strcmpiW(extension, comW) ||
1742 !strcmpiW(extension, exeW) ||
1743 !strcmpiW(extension, msiW))
1748 static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
1749 const char *friendlyAppName, const char *mimeType,
1755 WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, to file %s\n",
1756 wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
1757 wine_dbgstr_a(progId), wine_dbgstr_a(desktopPath));
1759 desktop = fopen(desktopPath, "w");
1762 fprintf(desktop, "[Desktop Entry]\n");
1763 fprintf(desktop, "Type=Application\n");
1764 fprintf(desktop, "Name=%s\n", friendlyAppName);
1765 fprintf(desktop, "MimeType=%s\n", mimeType);
1766 fprintf(desktop, "Exec=wine start /ProgIDOpen %s %%f\n", progId);
1767 fprintf(desktop, "NoDisplay=true\n");
1768 fprintf(desktop, "StartupNotify=true\n");
1773 WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
1777 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1779 struct list *nativeMimeTypes = NULL;
1782 BOOL hasChanged = FALSE;
1784 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1786 WINE_ERR("could not build native MIME types\n");
1792 WCHAR *extensionW = NULL;
1797 HeapFree(GetProcessHeap(), 0, extensionW);
1798 extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
1799 if (extensionW == NULL)
1801 WINE_ERR("out of memory\n");
1802 ret = ERROR_OUTOFMEMORY;
1805 ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
1807 } while (ret == ERROR_MORE_DATA);
1809 if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
1811 char *extensionA = NULL;
1812 WCHAR *commandW = NULL;
1813 WCHAR *friendlyDocNameW = NULL;
1814 char *friendlyDocNameA = NULL;
1815 WCHAR *contentTypeW = NULL;
1816 char *mimeTypeA = NULL;
1817 WCHAR *friendlyAppNameW = NULL;
1818 char *friendlyAppNameA = NULL;
1819 WCHAR *progIdW = NULL;
1820 char *progIdA = NULL;
1822 extensionA = wchars_to_utf8_chars(extensionW);
1823 if (extensionA == NULL)
1825 WINE_ERR("out of memory\n");
1829 friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
1830 if (friendlyDocNameW)
1832 friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
1833 if (friendlyDocNameA == NULL)
1835 WINE_ERR("out of memory\n");
1840 contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
1842 if (!freedesktop_mime_type_for_extension(nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
1845 if (mimeTypeA == NULL)
1847 if (contentTypeW != NULL)
1848 mimeTypeA = wchars_to_utf8_chars(contentTypeW);
1850 mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
1852 if (mimeTypeA != NULL)
1854 write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
1859 WINE_FIXME("out of memory\n");
1864 commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, NULL);
1865 if (commandW == NULL)
1866 /* no command => no application is associated */
1869 friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, NULL);
1870 if (friendlyAppNameW)
1872 friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
1873 if (friendlyAppNameA == NULL)
1875 WINE_ERR("out of memory\n");
1881 friendlyAppNameA = heap_printf("A Wine application");
1882 if (friendlyAppNameA == NULL)
1884 WINE_ERR("out of memory\n");
1889 progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
1892 progIdA = wchars_to_utf8_chars(progIdW);
1893 if (progIdA == NULL)
1895 WINE_ERR("out of memory\n");
1900 goto end; /* no progID => not a file type association */
1902 if (has_association_changed(extensionA, extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW))
1904 char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
1907 if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA))
1910 update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, friendlyDocNameW, desktopPath);
1912 HeapFree(GetProcessHeap(), 0, desktopPath);
1917 HeapFree(GetProcessHeap(), 0, extensionA);
1918 HeapFree(GetProcessHeap(), 0, commandW);
1919 HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
1920 HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
1921 HeapFree(GetProcessHeap(), 0, contentTypeW);
1922 HeapFree(GetProcessHeap(), 0, mimeTypeA);
1923 HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
1924 HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
1925 HeapFree(GetProcessHeap(), 0, progIdW);
1926 HeapFree(GetProcessHeap(), 0, progIdA);
1928 HeapFree(GetProcessHeap(), 0, extensionW);
1929 if (ret != ERROR_SUCCESS)
1933 free_native_mime_types(nativeMimeTypes);
1937 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1939 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1940 '\\','s','t','a','r','t','.','e','x','e',0};
1941 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1942 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1943 WCHAR szTmp[INFOTIPSIZE];
1944 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1945 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1946 int iIconId = 0, r = -1;
1952 WINE_ERR("Link name is null\n");
1956 if( !GetLinkLocation( link, &csidl, &link_name ) )
1958 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1961 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1963 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1966 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1969 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1970 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1971 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
1974 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1975 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1976 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1978 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1979 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
1980 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
1983 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1984 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1985 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
1989 LPITEMIDLIST pidl = NULL;
1990 IShellLinkW_GetIDList( sl, &pidl );
1991 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1992 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
1995 /* extract the icon */
1997 icon_name = extract_icon( szIconPath , iIconId, bWait );
1999 icon_name = extract_icon( szPath, iIconId, bWait );
2001 /* fail - try once again after parent process exit */
2006 WINE_WARN("Unable to extract icon, deferring.\n");
2009 WINE_ERR("failed to extract icon from %s\n",
2010 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2013 /* check the path */
2016 static const WCHAR exeW[] = {'.','e','x','e',0};
2019 /* check for .exe extension */
2020 if (!(p = strrchrW( szPath, '.' )) ||
2021 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
2022 lstrcmpiW( p, exeW ))
2024 /* Not .exe - use 'start.exe' to launch this file */
2025 p = szArgs + lstrlenW(szPath) + 2;
2029 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
2030 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
2036 lstrcpyW(szArgs + 1, szPath);
2039 GetWindowsDirectoryW(szPath, MAX_PATH);
2040 lstrcatW(szPath, startW);
2043 /* convert app working dir */
2045 work_dir = wine_get_unix_file_name( szWorkDir );
2049 /* if there's no path... try run the link itself */
2050 lstrcpynW(szArgs, link, MAX_PATH);
2051 GetWindowsDirectoryW(szPath, MAX_PATH);
2052 lstrcatW(szPath, startW);
2055 /* escape the path and parameters */
2056 escaped_path = escape(szPath);
2057 escaped_args = escape(szArgs);
2058 escaped_description = escape(szDescription);
2060 /* building multiple menus concurrently has race conditions */
2061 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2062 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2064 WINE_ERR("failed wait for semaphore\n");
2068 if (in_desktop_dir(csidl))
2071 const char *lastEntry;
2072 lastEntry = strrchr(link_name, '/');
2073 if (lastEntry == NULL)
2074 lastEntry = link_name;
2077 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2080 r = !write_desktop_entry(location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2081 HeapFree(GetProcessHeap(), 0, location);
2085 r = !write_menu_entry(link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
2087 ReleaseSemaphore( hsem, 1, NULL );
2090 if (hsem) CloseHandle( hsem );
2091 HeapFree( GetProcessHeap(), 0, icon_name );
2092 HeapFree( GetProcessHeap(), 0, work_dir );
2093 HeapFree( GetProcessHeap(), 0, link_name );
2094 HeapFree( GetProcessHeap(), 0, escaped_args );
2095 HeapFree( GetProcessHeap(), 0, escaped_path );
2096 HeapFree( GetProcessHeap(), 0, escaped_description );
2099 WINE_ERR("failed to build the menu\n" );
2104 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
2106 char *link_name = NULL;
2109 char *escaped_urlPath = NULL;
2117 WINE_ERR("Link name is null\n");
2121 if( !GetLinkLocation( link, &csidl, &link_name ) )
2123 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2126 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2128 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
2132 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
2134 hr = url->lpVtbl->GetURL(url, &urlPath);
2140 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
2142 escaped_urlPath = escape(urlPath);
2144 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2145 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2147 WINE_ERR("failed wait for semaphore\n");
2150 if (in_desktop_dir(csidl))
2153 const char *lastEntry;
2154 lastEntry = strrchr(link_name, '/');
2155 if (lastEntry == NULL)
2156 lastEntry = link_name;
2159 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2162 r = !write_desktop_entry(location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2163 HeapFree(GetProcessHeap(), 0, location);
2167 r = !write_menu_entry(link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
2169 ReleaseSemaphore(hSem, 1, NULL);
2174 HeapFree(GetProcessHeap(), 0, link_name);
2175 CoTaskMemFree( urlPath );
2176 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
2180 static BOOL WaitForParentProcess( void )
2182 PROCESSENTRY32 procentry;
2183 HANDLE hsnapshot = NULL, hprocess = NULL;
2184 DWORD ourpid = GetCurrentProcessId();
2185 BOOL ret = FALSE, rc;
2187 WINE_TRACE("Waiting for parent process\n");
2188 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
2189 INVALID_HANDLE_VALUE)
2191 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
2195 procentry.dwSize = sizeof(PROCESSENTRY32);
2196 rc = Process32First( hsnapshot, &procentry );
2199 if (procentry.th32ProcessID == ourpid) break;
2200 rc = Process32Next( hsnapshot, &procentry );
2204 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
2208 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
2211 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
2216 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
2219 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
2222 if (hprocess) CloseHandle( hprocess );
2223 if (hsnapshot) CloseHandle( hsnapshot );
2227 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
2232 WCHAR fullname[MAX_PATH];
2235 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
2239 WINE_ERR("link name missing\n");
2243 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
2244 if (len==0 || len>MAX_PATH)
2246 WINE_ERR("couldn't get full path of link file\n");
2250 r = CoInitialize( NULL );
2253 WINE_ERR("CoInitialize failed\n");
2257 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2258 &IID_IShellLinkW, (LPVOID *) &sl );
2261 WINE_ERR("No IID_IShellLink\n");
2265 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
2268 WINE_ERR("No IID_IPersistFile\n");
2272 r = IPersistFile_Load( pf, fullname, STGM_READ );
2273 if( SUCCEEDED( r ) )
2275 /* If something fails (eg. Couldn't extract icon)
2276 * wait for parent process and try again
2278 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
2280 WaitForParentProcess();
2281 InvokeShellLinker( sl, fullname, FALSE );
2286 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
2289 IPersistFile_Release( pf );
2290 IShellLinkW_Release( sl );
2297 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
2299 IUniformResourceLocatorW *url;
2302 WCHAR fullname[MAX_PATH];
2305 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
2309 WINE_ERR("URL name missing\n");
2313 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
2314 if (len==0 || len>MAX_PATH)
2316 WINE_ERR("couldn't get full path of URL file\n");
2320 r = CoInitialize( NULL );
2323 WINE_ERR("CoInitialize failed\n");
2327 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
2328 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
2331 WINE_ERR("No IID_IUniformResourceLocatorW\n");
2335 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
2338 WINE_ERR("No IID_IPersistFile\n");
2341 r = IPersistFile_Load( pf, fullname, STGM_READ );
2342 if( SUCCEEDED( r ) )
2344 /* If something fails (eg. Couldn't extract icon)
2345 * wait for parent process and try again
2347 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
2349 WaitForParentProcess();
2350 InvokeShellLinkerForURL( url, fullname, FALSE );
2354 IPersistFile_Release( pf );
2355 url->lpVtbl->Release( url );
2362 static void RefreshFileTypeAssociations(void)
2365 char *mime_dir = NULL;
2366 char *packages_dir = NULL;
2367 char *applications_dir = NULL;
2370 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2371 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
2373 WINE_ERR("failed wait for semaphore\n");
2379 mime_dir = heap_printf("%s/mime", xdg_data_dir);
2380 if (mime_dir == NULL)
2382 WINE_ERR("out of memory\n");
2385 create_directories(mime_dir);
2387 packages_dir = heap_printf("%s/packages", mime_dir);
2388 if (packages_dir == NULL)
2390 WINE_ERR("out of memory\n");
2393 create_directories(packages_dir);
2395 applications_dir = heap_printf("%s/applications", xdg_data_dir);
2396 if (applications_dir == NULL)
2398 WINE_ERR("out of memory\n");
2401 create_directories(applications_dir);
2403 hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
2404 hasChanged |= cleanup_associations();
2407 char *command = heap_printf("update-mime-database %s", mime_dir);
2411 HeapFree(GetProcessHeap(), 0, command);
2415 WINE_ERR("out of memory\n");
2419 command = heap_printf("update-desktop-database %s/applications", xdg_data_dir);
2423 HeapFree(GetProcessHeap(), 0, command);
2427 WINE_ERR("out of memory\n");
2435 ReleaseSemaphore(hSem, 1, NULL);
2438 HeapFree(GetProcessHeap(), 0, mime_dir);
2439 HeapFree(GetProcessHeap(), 0, packages_dir);
2440 HeapFree(GetProcessHeap(), 0, applications_dir);
2443 static CHAR *next_token( LPSTR *p )
2445 LPSTR token = NULL, t = *p;
2450 while( t && !token )
2458 /* unquote the token */
2460 t = strchr( token, '"' );
2469 t = strchr( token, ' ' );
2479 static BOOL init_xdg(void)
2481 WCHAR shellDesktopPath[MAX_PATH];
2482 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
2484 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
2485 if (xdg_desktop_dir == NULL)
2487 WINE_ERR("error looking up the desktop directory\n");
2491 if (getenv("XDG_CONFIG_HOME"))
2492 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
2494 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
2497 create_directories(xdg_config_dir);
2498 if (getenv("XDG_DATA_HOME"))
2499 xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
2501 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
2505 create_directories(xdg_data_dir);
2506 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
2509 mkdir(buffer, 0777);
2510 HeapFree(GetProcessHeap(), 0, buffer);
2514 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
2516 WINE_ERR("out of memory\n");
2520 /***********************************************************************
2524 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
2526 LPSTR token = NULL, p;
2534 for( p = cmdline; p && *p; )
2536 token = next_token( &p );
2539 if( !lstrcmpA( token, "-a" ) )
2541 RefreshFileTypeAssociations();
2544 if( !lstrcmpA( token, "-w" ) )
2546 else if ( !lstrcmpA( token, "-u" ) )
2548 else if( token[0] == '-' )
2550 WINE_ERR( "unknown option %s\n",token);
2554 WCHAR link[MAX_PATH];
2557 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2559 bRet = Process_URL( link, bWait );
2561 bRet = Process_Link( link, bWait );
2564 WINE_ERR( "failed to build menu item for %s\n",token);