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"
78 #include "wine/unicode.h"
79 #include "wine/debug.h"
80 #include "wine/library.h"
81 #include "wine/list.h"
89 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
91 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
92 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
93 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
94 (csidl)==CSIDL_COMMON_STARTMENU)
96 /* link file formats */
117 GRPICONDIRENTRY idEntries[1];
155 static char *xdg_config_dir;
156 static char *xdg_data_dir;
157 static char *xdg_desktop_dir;
159 /* Icon extraction routines
161 * FIXME: should use PrivateExtractIcons and friends
162 * FIXME: should not use stdio
165 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
167 /* PNG-specific code */
170 static void *libpng_handle;
171 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
172 MAKE_FUNCPTR(png_create_info_struct);
173 MAKE_FUNCPTR(png_create_write_struct);
174 MAKE_FUNCPTR(png_destroy_write_struct);
175 MAKE_FUNCPTR(png_init_io);
176 MAKE_FUNCPTR(png_set_bgr);
177 MAKE_FUNCPTR(png_set_text);
178 MAKE_FUNCPTR(png_set_IHDR);
179 MAKE_FUNCPTR(png_write_end);
180 MAKE_FUNCPTR(png_write_info);
181 MAKE_FUNCPTR(png_write_row);
184 static void *load_libpng(void)
186 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
188 #define LOAD_FUNCPTR(f) \
189 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
190 libpng_handle = NULL; \
193 LOAD_FUNCPTR(png_create_info_struct);
194 LOAD_FUNCPTR(png_create_write_struct);
195 LOAD_FUNCPTR(png_destroy_write_struct);
196 LOAD_FUNCPTR(png_init_io);
197 LOAD_FUNCPTR(png_set_bgr);
198 LOAD_FUNCPTR(png_set_IHDR);
199 LOAD_FUNCPTR(png_set_text);
200 LOAD_FUNCPTR(png_write_end);
201 LOAD_FUNCPTR(png_write_info);
202 LOAD_FUNCPTR(png_write_row);
205 return libpng_handle;
208 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
210 static const char comment_key[] = "Created from";
215 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
216 BYTE *row, *copy = NULL;
217 const BYTE *pXOR, *pAND = NULL;
218 int nWidth = pIcon->bmiHeader.biWidth;
219 int nHeight = pIcon->bmiHeader.biHeight;
220 int nBpp = pIcon->bmiHeader.biBitCount;
225 color_type |= PNG_COLOR_MASK_ALPHA;
228 color_type |= PNG_COLOR_MASK_COLOR;
234 if (!libpng_handle && !load_libpng())
236 WINE_WARN("Unable to load libpng\n");
240 if (!(fp = fopen(png_filename, "w")))
242 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
246 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
247 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
248 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
249 if (nHeight > nWidth)
252 pAND = pXOR + nHeight * nXORWidthBytes;
255 /* Apply mask if present */
260 /* copy bytes before modifying them */
261 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
262 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
265 /* image and mask are upside down reversed */
266 row = copy + (nHeight - 1) * nXORWidthBytes;
268 /* top left corner */
269 bgColor.rgbRed = row[0];
270 bgColor.rgbGreen = row[1];
271 bgColor.rgbBlue = row[2];
272 bgColor.rgbReserved = 0;
274 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
275 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
278 RGBQUAD *pixel = (RGBQUAD *)row;
279 pixel->rgbBlue = bgColor.rgbBlue;
280 pixel->rgbGreen = bgColor.rgbGreen;
281 pixel->rgbRed = bgColor.rgbRed;
283 pixel->rgbReserved = bgColor.rgbReserved;
289 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
290 !(info_ptr = ppng_create_info_struct(png_ptr)))
293 if (setjmp(png_jmpbuf(png_ptr)))
295 /* All future errors jump here */
296 WINE_ERR("png error\n");
300 ppng_init_io(png_ptr, fp);
301 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
304 PNG_COMPRESSION_TYPE_DEFAULT,
305 PNG_FILTER_TYPE_DEFAULT);
308 comment.compression = PNG_TEXT_COMPRESSION_NONE;
309 comment.key = (png_charp)comment_key;
310 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
311 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
312 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
313 comment.text_length = i - 1;
314 ppng_set_text(png_ptr, info_ptr, &comment, 1);
317 ppng_write_info(png_ptr, info_ptr);
318 ppng_set_bgr(png_ptr);
319 for (i = nHeight - 1; i >= 0 ; i--)
320 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
321 ppng_write_end(png_ptr, info_ptr);
323 ppng_destroy_write_struct(&png_ptr, &info_ptr);
324 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
326 HeapFree(GetProcessHeap(), 0, copy);
327 HeapFree(GetProcessHeap(), 0, comment.text);
331 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
333 unlink(png_filename);
334 HeapFree(GetProcessHeap(), 0, copy);
335 HeapFree(GetProcessHeap(), 0, comment.text);
338 #endif /* SONAME_LIBPNG */
340 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
350 BOOL aColorUsed[256] = {0};
355 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
357 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
361 if (!(fXPMFile = fopen(szXPMFileName, "w")))
363 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
367 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
368 comment = HeapAlloc(GetProcessHeap(), 0, i);
369 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
371 nHeight = pIcon->bmiHeader.biHeight / 2;
372 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
373 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
374 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
375 + ((pIcon->bmiHeader.biWidth % 32) > 0));
376 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
377 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
378 : 1 << pIcon->bmiHeader.biBitCount;
379 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
380 pAND = pXOR + nHeight * nXORWidthBytes;
382 #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)
384 for (i = 0; i < nHeight; i++) {
385 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
386 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
388 aColorUsed[COLOR(j,i)] = TRUE;
394 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
396 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
397 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
400 for (i = 0; i < nColors; i++) {
402 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
403 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
406 if (fprintf(fXPMFile, "\" c None\"") <= 0)
409 for (i = 0; i < nHeight; i++)
411 if (fprintf(fXPMFile, ",\n\"") <= 0)
413 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
417 if (fprintf(fXPMFile, " ") <= 0)
421 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
424 if (fprintf(fXPMFile, "\"") <= 0)
427 if (fprintf(fXPMFile, "};\n") <= 0)
433 HeapFree(GetProcessHeap(), 0, comment);
438 HeapFree(GetProcessHeap(), 0, comment);
440 unlink( szXPMFileName );
444 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
446 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
448 if (!sEnumRes->nIndex--)
450 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
457 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
461 LPCWSTR lpName = NULL;
463 GRPICONDIR *pIconDir;
465 ENUMRESSTRUCT sEnumRes;
471 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
474 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
475 wine_dbgstr_w(szFileName), GetLastError());
481 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
482 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
483 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
488 sEnumRes.pResInfo = &hResInfo;
489 sEnumRes.nIndex = nIndex;
490 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
491 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
492 sEnumRes.nIndex != -1)
494 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
500 if ((hResData = LoadResource(hModule, hResInfo)))
502 if ((pIconDir = LockResource(hResData)))
504 for (i = 0; i < pIconDir->idCount; i++)
506 if (pIconDir->idEntries[i].wBitCount >= nMaxBits)
508 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
510 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
511 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
512 nMaxBits = pIconDir->idEntries[i].wBitCount;
518 FreeResource(hResData);
523 WINE_WARN("found no icon\n");
524 FreeLibrary(hModule);
528 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
530 if ((hResData = LoadResource(hModule, hResInfo)))
532 if ((pIcon = LockResource(hResData)))
535 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
540 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
541 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
546 FreeResource(hResData);
550 FreeLibrary(hModule);
554 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
556 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
557 !extract_icon16(szFileName, szXPMFileName)*/)
562 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
564 FILE *fICOFile = NULL;
566 ICONDIRENTRY *pIconDirEntry = NULL;
567 int nMax = 0, nMaxBits = 0;
571 char *filename = NULL;
573 filename = wine_get_unix_file_name(szFileName);
574 if (!(fICOFile = fopen(filename, "r")))
576 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
580 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
581 (iconDir.idReserved != 0) || (iconDir.idType != 1))
583 WINE_WARN("Invalid ico file format\n");
587 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
589 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
592 for (i = 0; i < iconDir.idCount; i++)
594 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
595 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
596 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
599 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
600 nMaxBits = pIconDirEntry[i].wBitCount;
603 WINE_TRACE("Selected: %d\n", nIndex);
605 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
607 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
609 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
613 /* Prefer PNG over XPM */
615 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
618 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
619 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
623 HeapFree(GetProcessHeap(), 0, pIcon);
624 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
626 HeapFree(GetProcessHeap(), 0, filename);
630 HeapFree(GetProcessHeap(), 0, pIcon);
631 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
632 if (fICOFile) fclose(fICOFile);
633 HeapFree(GetProcessHeap(), 0, filename);
637 static BOOL create_default_icon( const char *filename, const char* comment )
642 if (!(fXPM = fopen(filename, "w"))) return FALSE;
643 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
645 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
646 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
649 if (fprintf( fXPM, "};\n" ) <=0)
660 static unsigned short crc16(const char* string)
662 unsigned short crc = 0;
665 for (i = 0; string[i] != 0; i++)
668 for (j = 0; j < 8; c >>= 1, j++)
670 xor_poly = (c ^ crc) & 1;
679 static char* heap_printf(const char *format, ...)
686 va_start(args, format);
689 buffer = HeapAlloc(GetProcessHeap(), 0, size);
692 n = vsnprintf(buffer, size, format, args);
699 HeapFree(GetProcessHeap(), 0, buffer);
705 static BOOL create_directories(char *directory)
710 for (i = 0; directory[i]; i++)
712 if (i > 0 && directory[i] == '/')
715 mkdir(directory, 0777);
719 if (mkdir(directory, 0777) && errno != EEXIST)
725 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
726 static char *extract_icon( LPCWSTR path, int index, BOOL bWait )
729 char *iconsdir = NULL, *ico_path = NULL, *ico_name, *xpm_path = NULL;
733 /* Where should we save the icon? */
734 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
735 iconsdir = heap_printf("%s/icons", xdg_data_dir);
738 if (mkdir(iconsdir, 0777) && errno != EEXIST)
740 WINE_WARN("couldn't make icons directory %s\n", wine_dbgstr_a(iconsdir));
746 WINE_TRACE("no icon created\n");
750 /* Determine the icon base name */
751 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
752 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
753 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
756 if (*s=='/' || *s=='\\') {
764 if (*ico_name=='\\') *ico_name++='\0';
765 s=strrchr(ico_name,'.');
768 /* Compute the source-path hash */
771 /* Try to treat the source file as an exe */
772 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
773 sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
774 if (ExtractFromEXEDLL( path, index, xpm_path ))
777 /* Must be something else, ignore the index in that case */
778 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
779 if (ExtractFromICO( path, xpm_path))
783 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
784 if (create_default_icon( xpm_path, ico_path ))
788 HeapFree( GetProcessHeap(), 0, xpm_path );
792 HeapFree(GetProcessHeap(), 0, iconsdir);
793 HeapFree(GetProcessHeap(), 0, ico_path);
797 static BOOL write_desktop_entry(const char *location, const char *linkname, const char *path,
798 const char *args, const char *descr, const char *workdir,
803 WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(location),
804 wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
805 wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon));
807 file = fopen(location, "w");
811 fprintf(file, "[Desktop Entry]\n");
812 fprintf(file, "Name=%s\n", linkname);
813 fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine \"%s\" %s\n",
814 wine_get_config_dir(), path, args);
815 fprintf(file, "Type=Application\n");
816 fprintf(file, "StartupNotify=true\n");
817 if (descr && lstrlenA(descr))
818 fprintf(file, "Comment=%s\n", descr);
819 if (workdir && lstrlenA(workdir))
820 fprintf(file, "Path=%s\n", workdir);
821 if (icon && lstrlenA(icon))
822 fprintf(file, "Icon=%s\n", icon);
828 static BOOL write_directory_entry(const char *directory, const char *location)
832 WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));
834 file = fopen(location, "w");
838 fprintf(file, "[Desktop Entry]\n");
839 fprintf(file, "Type=Directory\n");
840 if (strcmp(directory, "wine") == 0)
842 fprintf(file, "Name=Wine\n");
843 fprintf(file, "Icon=wine\n");
847 fprintf(file, "Name=%s\n", directory);
848 fprintf(file, "Icon=folder\n");
855 static BOOL write_menu_file(const char *filename)
858 FILE *tempfile = NULL;
861 char *menuPath = NULL;
866 WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));
870 tempfilename = tempnam(xdg_config_dir, "_wine");
873 int tempfd = open(tempfilename, O_EXCL | O_CREAT | O_WRONLY, 0666);
876 tempfile = fdopen(tempfd, "w");
882 else if (errno == EEXIST)
892 fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
893 fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
894 fprintf(tempfile, "<Menu>\n");
895 fprintf(tempfile, " <Name>Applications</Name>\n");
897 name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
898 if (name == NULL) goto end;
900 for (i = 0; filename[i]; i++)
902 name[i] = filename[i];
903 if (filename[i] == '/')
908 fprintf(tempfile, " <Menu>\n");
909 fprintf(tempfile, " <Name>%s%s</Name>\n", count ? "" : "wine-", name);
910 fprintf(tempfile, " <Directory>%s%s.directory</Directory>\n", count ? "" : "wine-", name);
911 dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
912 xdg_data_dir, count ? "" : "wine-", name);
915 if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
916 write_directory_entry(lastEntry, dir_file_name);
917 HeapFree(GetProcessHeap(), 0, dir_file_name);
920 lastEntry = &name[i+1];
926 fprintf(tempfile, " <Include>\n");
927 fprintf(tempfile, " <Filename>%s</Filename>\n", name);
928 fprintf(tempfile, " </Include>\n");
929 for (i = 0; i < count; i++)
930 fprintf(tempfile, " </Menu>\n");
931 fprintf(tempfile, "</Menu>\n");
933 menuPath = heap_printf("%s/%s", xdg_config_dir, name);
934 if (menuPath == NULL) goto end;
935 strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
942 ret = (rename(tempfilename, menuPath) == 0);
943 if (!ret && tempfilename)
944 remove(tempfilename);
946 HeapFree(GetProcessHeap(), 0, name);
947 HeapFree(GetProcessHeap(), 0, menuPath);
951 static BOOL write_menu_entry(const char *link, const char *path, const char *args,
952 const char *descr, const char *workdir, const char *icon)
954 const char *linkname;
955 char *desktopPath = NULL;
957 char *filename = NULL;
960 WINE_TRACE("(%s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(link), wine_dbgstr_a(path),
961 wine_dbgstr_a(args), wine_dbgstr_a(descr), wine_dbgstr_a(workdir),
962 wine_dbgstr_a(icon));
964 linkname = strrchr(link, '/');
965 if (linkname == NULL)
970 desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
973 WINE_WARN("out of memory creating menu entry\n");
977 desktopDir = strrchr(desktopPath, '/');
979 if (!create_directories(desktopPath))
981 WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
986 if (!write_desktop_entry(desktopPath, linkname, path, args, descr, workdir, icon))
988 WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
993 filename = heap_printf("wine/%s.desktop", link);
994 if (!filename || !write_menu_file(filename))
996 WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
1001 HeapFree(GetProcessHeap(), 0, desktopPath);
1002 HeapFree(GetProcessHeap(), 0, filename);
1006 /* This escapes \ in filenames */
1007 static LPSTR escape(LPCWSTR arg)
1014 while((esc = strchrW(esc, '\\')))
1020 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
1021 narg = HeapAlloc(GetProcessHeap(), 0, len);
1026 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
1030 *x++='\\'; /* escape \ */
1037 /* Return a heap-allocated copy of the unix format difference between the two
1038 * Windows-format paths.
1039 * locn is the owning location
1040 * link is within locn
1042 static char *relative_path( LPCWSTR link, LPCWSTR locn )
1044 char *unix_locn, *unix_link;
1045 char *relative = NULL;
1047 unix_locn = wine_get_unix_file_name(locn);
1048 unix_link = wine_get_unix_file_name(link);
1049 if (unix_locn && unix_link)
1051 size_t len_unix_locn, len_unix_link;
1052 len_unix_locn = strlen (unix_locn);
1053 len_unix_link = strlen (unix_link);
1054 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
1057 char *p = strrchr (unix_link + len_unix_locn, '/');
1058 p = strrchr (p, '.');
1062 len_unix_link = p - unix_link;
1064 len_rel = len_unix_link - len_unix_locn;
1065 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
1068 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
1073 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
1074 HeapFree(GetProcessHeap(), 0, unix_locn);
1075 HeapFree(GetProcessHeap(), 0, unix_link);
1079 /***********************************************************************
1083 * returns TRUE if successful
1084 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
1085 * *relative will contain the address of a heap-allocated copy of the portion
1086 * of the filename that is within the specified location, in unix form
1088 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1090 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
1091 DWORD len, i, r, filelen;
1092 const DWORD locations[] = {
1093 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
1094 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
1095 CSIDL_COMMON_STARTMENU };
1097 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1098 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
1099 if (filelen==0 || filelen>MAX_PATH)
1102 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
1104 /* the CSLU Toolkit uses a short path name when creating .lnk files;
1105 * expand or our hardcoded list won't match.
1107 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
1108 if (filelen==0 || filelen>MAX_PATH)
1111 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1113 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
1115 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1118 len = lstrlenW(buffer);
1119 if (len >= MAX_PATH)
1120 continue; /* We've just trashed memory! Hopefully we are OK */
1122 if (len > filelen || filename[len]!='\\')
1124 /* do a lstrcmpinW */
1126 r = lstrcmpiW( filename, buffer );
1127 filename[len] = '\\';
1131 /* return the remainder of the string and link type */
1132 *loc = locations[i];
1133 *relative = relative_path (filename, buffer);
1134 return (*relative != NULL);
1140 /* gets the target path directly or through MSI */
1141 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1142 LPWSTR szArgs, DWORD argsSize)
1144 IShellLinkDataList *dl = NULL;
1145 EXP_DARWIN_LINK *dar = NULL;
1151 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1152 if (hr == S_OK && szPath[0])
1154 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1158 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1162 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1169 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1170 if (hr == ERROR_SUCCESS)
1173 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1174 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1175 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1176 if (hr == ERROR_SUCCESS)
1179 int bcount, in_quotes;
1181 /* Extract the application path */
1188 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1190 /* skip the remaining spaces */
1193 } while (*s==0x0009 || *s==0x0020);
1196 else if (*s==0x005c)
1202 else if (*s==0x0022)
1205 if ((bcount & 1)==0)
1207 /* Preceded by an even number of '\', this is
1208 * half that number of '\', plus a quote which
1212 in_quotes=!in_quotes;
1217 /* Preceded by an odd number of '\', this is
1218 * half that number of '\' followed by a '"'
1228 /* a regular character */
1232 if ((d-szPath) == pathSize)
1234 /* Keep processing the path till we get to the
1235 * arguments, but 'stand still'
1240 /* Close the application path */
1243 lstrcpynW(szArgs, s, argsSize);
1245 HeapFree( GetProcessHeap(), 0, szCmdline );
1250 IShellLinkDataList_Release( dl );
1254 static BOOL next_line(FILE *file, char **line, int *size)
1261 *line = HeapAlloc(GetProcessHeap(), 0, *size);
1263 while (*line != NULL)
1265 if (fgets(&(*line)[pos], *size - pos, file) == NULL)
1267 HeapFree(GetProcessHeap(), 0, *line);
1273 pos = strlen(*line);
1274 cr = strchr(*line, '\n');
1279 line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
1284 HeapFree(GetProcessHeap(), 0, *line);
1297 static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
1299 char *globs_filename = NULL;
1301 globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
1304 FILE *globs_file = fopen(globs_filename, "r");
1305 if (globs_file) /* doesn't have to exist */
1309 while (ret && (ret = next_line(globs_file, &line, &size)) && line)
1312 struct xdg_mime_type *mime_type_entry = NULL;
1313 if (line[0] != '#' && (pos = strchr(line, ':')))
1315 mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
1316 if (mime_type_entry)
1319 mime_type_entry->mimeType = line;
1320 mime_type_entry->glob = pos + 1;
1321 list_add_tail(mime_types, &mime_type_entry->entry);
1327 HeapFree(GetProcessHeap(), 0, line);
1330 HeapFree(GetProcessHeap(), 0, globs_filename);
1337 static void free_native_mime_types(struct list *native_mime_types)
1339 struct xdg_mime_type *mime_type_entry, *mime_type_entry2;
1341 LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
1343 list_remove(&mime_type_entry->entry);
1344 HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
1345 HeapFree(GetProcessHeap(), 0, mime_type_entry);
1347 HeapFree(GetProcessHeap(), 0, native_mime_types);
1350 static BOOL build_native_mime_types(const char *xdg_data_home, struct list **mime_types)
1352 char *xdg_data_dirs;
1357 xdg_data_dirs = getenv("XDG_DATA_DIRS");
1358 if (xdg_data_dirs == NULL)
1359 xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
1361 xdg_data_dirs = heap_printf("%s", xdg_data_dirs);
1365 *mime_types = HeapAlloc(GetProcessHeap(), 0, sizeof(struct list));
1371 list_init(*mime_types);
1372 ret = add_mimes(xdg_data_home, *mime_types);
1375 for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
1378 ret = add_mimes(begin, *mime_types);
1384 ret = add_mimes(begin, *mime_types);
1389 HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
1393 if (!ret && *mime_types)
1395 free_native_mime_types(*mime_types);
1401 static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
1403 struct list *nativeMimeTypes = NULL;
1405 if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
1407 WINE_ERR("could not build native MIME types\n");
1413 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1415 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1416 '\\','s','t','a','r','t','.','e','x','e',0};
1417 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1418 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1419 WCHAR szTmp[INFOTIPSIZE];
1420 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1421 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1422 int iIconId = 0, r = -1;
1428 WINE_ERR("Link name is null\n");
1432 if( !GetLinkLocation( link, &csidl, &link_name ) )
1434 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1437 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1439 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1442 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1445 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1446 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1447 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
1450 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1451 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1452 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1454 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1455 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
1456 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
1459 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1460 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1461 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
1465 LPITEMIDLIST pidl = NULL;
1466 IShellLinkW_GetIDList( sl, &pidl );
1467 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1468 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
1471 /* extract the icon */
1473 icon_name = extract_icon( szIconPath , iIconId, bWait );
1475 icon_name = extract_icon( szPath, iIconId, bWait );
1477 /* fail - try once again after parent process exit */
1482 WINE_WARN("Unable to extract icon, deferring.\n");
1485 WINE_ERR("failed to extract icon from %s\n",
1486 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
1489 /* check the path */
1492 static const WCHAR exeW[] = {'.','e','x','e',0};
1495 /* check for .exe extension */
1496 if (!(p = strrchrW( szPath, '.' )) ||
1497 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
1498 lstrcmpiW( p, exeW ))
1500 /* Not .exe - use 'start.exe' to launch this file */
1501 p = szArgs + lstrlenW(szPath) + 2;
1505 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
1506 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
1512 lstrcpyW(szArgs + 1, szPath);
1515 GetWindowsDirectoryW(szPath, MAX_PATH);
1516 lstrcatW(szPath, startW);
1519 /* convert app working dir */
1521 work_dir = wine_get_unix_file_name( szWorkDir );
1525 /* if there's no path... try run the link itself */
1526 lstrcpynW(szArgs, link, MAX_PATH);
1527 GetWindowsDirectoryW(szPath, MAX_PATH);
1528 lstrcatW(szPath, startW);
1531 /* escape the path and parameters */
1532 escaped_path = escape(szPath);
1533 escaped_args = escape(szArgs);
1534 escaped_description = escape(szDescription);
1536 /* building multiple menus concurrently has race conditions */
1537 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1538 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
1540 WINE_ERR("failed wait for semaphore\n");
1544 if (in_desktop_dir(csidl))
1547 const char *lastEntry;
1548 lastEntry = strrchr(link_name, '/');
1549 if (lastEntry == NULL)
1550 lastEntry = link_name;
1553 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
1556 r = !write_desktop_entry(location, lastEntry, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
1557 HeapFree(GetProcessHeap(), 0, location);
1561 r = !write_menu_entry(link_name, escaped_path, escaped_args, escaped_description, work_dir, icon_name);
1563 ReleaseSemaphore( hsem, 1, NULL );
1566 if (hsem) CloseHandle( hsem );
1567 HeapFree( GetProcessHeap(), 0, icon_name );
1568 HeapFree( GetProcessHeap(), 0, work_dir );
1569 HeapFree( GetProcessHeap(), 0, link_name );
1570 HeapFree( GetProcessHeap(), 0, escaped_args );
1571 HeapFree( GetProcessHeap(), 0, escaped_path );
1572 HeapFree( GetProcessHeap(), 0, escaped_description );
1575 WINE_ERR("failed to build the menu\n" );
1580 static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
1582 char *link_name = NULL;
1585 char *escaped_urlPath = NULL;
1593 WINE_ERR("Link name is null\n");
1597 if( !GetLinkLocation( link, &csidl, &link_name ) )
1599 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1602 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1604 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1608 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1610 hr = url->lpVtbl->GetURL(url, &urlPath);
1616 WINE_TRACE("path : %s\n", wine_dbgstr_w(urlPath));
1618 escaped_urlPath = escape(urlPath);
1620 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1621 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
1623 WINE_ERR("failed wait for semaphore\n");
1626 if (in_desktop_dir(csidl))
1629 const char *lastEntry;
1630 lastEntry = strrchr(link_name, '/');
1631 if (lastEntry == NULL)
1632 lastEntry = link_name;
1635 location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
1638 r = !write_desktop_entry(location, lastEntry, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
1639 HeapFree(GetProcessHeap(), 0, location);
1643 r = !write_menu_entry(link_name, "winebrowser", escaped_urlPath, NULL, NULL, NULL);
1645 ReleaseSemaphore(hSem, 1, NULL);
1650 HeapFree(GetProcessHeap(), 0, link_name);
1651 CoTaskMemFree( urlPath );
1652 HeapFree(GetProcessHeap(), 0, escaped_urlPath);
1656 static BOOL WaitForParentProcess( void )
1658 PROCESSENTRY32 procentry;
1659 HANDLE hsnapshot = NULL, hprocess = NULL;
1660 DWORD ourpid = GetCurrentProcessId();
1661 BOOL ret = FALSE, rc;
1663 WINE_TRACE("Waiting for parent process\n");
1664 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
1665 INVALID_HANDLE_VALUE)
1667 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
1671 procentry.dwSize = sizeof(PROCESSENTRY32);
1672 rc = Process32First( hsnapshot, &procentry );
1675 if (procentry.th32ProcessID == ourpid) break;
1676 rc = Process32Next( hsnapshot, &procentry );
1680 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
1684 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
1687 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
1692 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
1695 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
1698 if (hprocess) CloseHandle( hprocess );
1699 if (hsnapshot) CloseHandle( hsnapshot );
1703 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
1708 WCHAR fullname[MAX_PATH];
1711 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
1715 WINE_ERR("link name missing\n");
1719 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1720 if (len==0 || len>MAX_PATH)
1722 WINE_ERR("couldn't get full path of link file\n");
1726 r = CoInitialize( NULL );
1729 WINE_ERR("CoInitialize failed\n");
1733 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1734 &IID_IShellLinkW, (LPVOID *) &sl );
1737 WINE_ERR("No IID_IShellLink\n");
1741 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1744 WINE_ERR("No IID_IPersistFile\n");
1748 r = IPersistFile_Load( pf, fullname, STGM_READ );
1749 if( SUCCEEDED( r ) )
1751 /* If something fails (eg. Couldn't extract icon)
1752 * wait for parent process and try again
1754 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
1756 WaitForParentProcess();
1757 InvokeShellLinker( sl, fullname, FALSE );
1762 WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
1765 IPersistFile_Release( pf );
1766 IShellLinkW_Release( sl );
1773 static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
1775 IUniformResourceLocatorW *url;
1778 WCHAR fullname[MAX_PATH];
1781 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);
1785 WINE_ERR("URL name missing\n");
1789 len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
1790 if (len==0 || len>MAX_PATH)
1792 WINE_ERR("couldn't get full path of URL file\n");
1796 r = CoInitialize( NULL );
1799 WINE_ERR("CoInitialize failed\n");
1803 r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
1804 &IID_IUniformResourceLocatorW, (LPVOID *) &url );
1807 WINE_ERR("No IID_IUniformResourceLocatorW\n");
1811 r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
1814 WINE_ERR("No IID_IPersistFile\n");
1817 r = IPersistFile_Load( pf, fullname, STGM_READ );
1818 if( SUCCEEDED( r ) )
1820 /* If something fails (eg. Couldn't extract icon)
1821 * wait for parent process and try again
1823 if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
1825 WaitForParentProcess();
1826 InvokeShellLinkerForURL( url, fullname, FALSE );
1830 IPersistFile_Release( pf );
1831 url->lpVtbl->Release( url );
1838 static void RefreshFileTypeAssociations(void)
1841 char *mime_dir = NULL;
1842 char *packages_dir = NULL;
1843 char *applications_dir = NULL;
1845 hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1846 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
1848 WINE_ERR("failed wait for semaphore\n");
1854 mime_dir = heap_printf("%s/mime", xdg_data_dir);
1855 if (mime_dir == NULL)
1857 WINE_ERR("out of memory\n");
1860 create_directories(mime_dir);
1862 packages_dir = heap_printf("%s/packages", mime_dir);
1863 if (packages_dir == NULL)
1865 WINE_ERR("out of memory\n");
1868 create_directories(packages_dir);
1870 applications_dir = heap_printf("%s/applications", xdg_data_dir);
1871 if (applications_dir == NULL)
1873 WINE_ERR("out of memory\n");
1876 create_directories(applications_dir);
1878 generate_associations(xdg_data_dir, packages_dir, applications_dir);
1883 ReleaseSemaphore(hSem, 1, NULL);
1886 HeapFree(GetProcessHeap(), 0, mime_dir);
1887 HeapFree(GetProcessHeap(), 0, packages_dir);
1888 HeapFree(GetProcessHeap(), 0, applications_dir);
1891 static CHAR *next_token( LPSTR *p )
1893 LPSTR token = NULL, t = *p;
1898 while( t && !token )
1906 /* unquote the token */
1908 t = strchr( token, '"' );
1917 t = strchr( token, ' ' );
1927 static BOOL init_xdg(void)
1929 WCHAR shellDesktopPath[MAX_PATH];
1930 HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
1932 xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
1933 if (xdg_desktop_dir == NULL)
1935 WINE_ERR("error looking up the desktop directory\n");
1939 if (getenv("XDG_CONFIG_HOME"))
1940 xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
1942 xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
1945 create_directories(xdg_config_dir);
1946 if (getenv("XDG_DATA_HOME"))
1947 xdg_data_dir = heap_printf("%s", getenv("XDG_DATA_HOME"));
1949 xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
1953 create_directories(xdg_data_dir);
1954 buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
1957 mkdir(buffer, 0777);
1958 HeapFree(GetProcessHeap(), 0, buffer);
1962 HeapFree(GetProcessHeap(), 0, xdg_config_dir);
1964 WINE_ERR("out of memory\n");
1968 /***********************************************************************
1972 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1974 LPSTR token = NULL, p;
1982 for( p = cmdline; p && *p; )
1984 token = next_token( &p );
1987 if( !lstrcmpA( token, "-a" ) )
1989 RefreshFileTypeAssociations();
1992 if( !lstrcmpA( token, "-w" ) )
1994 else if ( !lstrcmpA( token, "-u" ) )
1996 else if( token[0] == '-' )
1998 WINE_ERR( "unknown option %s\n",token);
2002 WCHAR link[MAX_PATH];
2005 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
2007 bRet = Process_URL( link, bWait );
2009 bRet = Process_Link( link, bWait );
2012 WINE_ERR( "failed to build menu item for %s\n",token);