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
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 * This program is used to replicate the Windows desktop and start menu
26 * into the native desktop's copies. Desktop entries are merged directly
27 * into the native desktop. The Windows Start Menu corresponds to a Wine
28 * entry within the native "start" menu and replicates the whole tree
29 * structure of the Windows Start Menu. Currently it does not differentiate
30 * between the user's desktop/start menu and the "All Users" copies.
32 * This program will read a Windows shortcut file using the IShellLink
33 * interface, then invoke wineshelllink with the appropriate arguments
34 * to 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"
77 #include "wine/unicode.h"
78 #include "wine/debug.h"
79 #include "wine/library.h"
87 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
89 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
90 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
91 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
92 (csidl)==CSIDL_COMMON_STARTMENU)
94 /* link file formats */
115 GRPICONDIRENTRY idEntries[1];
147 /* Icon extraction routines
149 * FIXME: should use PrivateExtractIcons and friends
150 * FIXME: should not use stdio
153 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
155 /* PNG-specific code */
158 static void *libpng_handle;
159 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
160 MAKE_FUNCPTR(png_create_info_struct);
161 MAKE_FUNCPTR(png_create_write_struct);
162 MAKE_FUNCPTR(png_destroy_write_struct);
163 MAKE_FUNCPTR(png_init_io);
164 MAKE_FUNCPTR(png_set_bgr);
165 MAKE_FUNCPTR(png_set_text);
166 MAKE_FUNCPTR(png_set_IHDR);
167 MAKE_FUNCPTR(png_write_end);
168 MAKE_FUNCPTR(png_write_info);
169 MAKE_FUNCPTR(png_write_row);
172 static void *load_libpng(void)
174 if ((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL)
176 #define LOAD_FUNCPTR(f) \
177 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
178 libpng_handle = NULL; \
181 LOAD_FUNCPTR(png_create_info_struct);
182 LOAD_FUNCPTR(png_create_write_struct);
183 LOAD_FUNCPTR(png_destroy_write_struct);
184 LOAD_FUNCPTR(png_init_io);
185 LOAD_FUNCPTR(png_set_bgr);
186 LOAD_FUNCPTR(png_set_IHDR);
187 LOAD_FUNCPTR(png_set_text);
188 LOAD_FUNCPTR(png_write_end);
189 LOAD_FUNCPTR(png_write_info);
190 LOAD_FUNCPTR(png_write_row);
193 return libpng_handle;
196 static BOOL SaveIconResAsPNG(const BITMAPINFO *pIcon, const char *png_filename, LPCWSTR commentW)
198 static const char comment_key[] = "Created from";
203 int nXORWidthBytes, nANDWidthBytes, color_type = 0, i, j;
204 BYTE *row, *copy = NULL;
205 const BYTE *pXOR, *pAND = NULL;
206 int nWidth = pIcon->bmiHeader.biWidth;
207 int nHeight = pIcon->bmiHeader.biHeight;
208 int nBpp = pIcon->bmiHeader.biBitCount;
213 color_type |= PNG_COLOR_MASK_ALPHA;
216 color_type |= PNG_COLOR_MASK_COLOR;
222 if (!libpng_handle && !load_libpng())
224 WINE_WARN("Unable to load libpng\n");
228 if (!(fp = fopen(png_filename, "w")))
230 WINE_ERR("unable to open '%s' for writing: %s\n", png_filename, strerror(errno));
234 nXORWidthBytes = 4 * ((nWidth * nBpp + 31) / 32);
235 nANDWidthBytes = 4 * ((nWidth + 31 ) / 32);
236 pXOR = (const BYTE*) pIcon + sizeof(BITMAPINFOHEADER) + pIcon->bmiHeader.biClrUsed * sizeof(RGBQUAD);
237 if (nHeight > nWidth)
240 pAND = pXOR + nHeight * nXORWidthBytes;
243 /* Apply mask if present */
248 /* copy bytes before modifying them */
249 copy = HeapAlloc( GetProcessHeap(), 0, nHeight * nXORWidthBytes );
250 memcpy( copy, pXOR, nHeight * nXORWidthBytes );
253 /* image and mask are upside down reversed */
254 row = copy + (nHeight - 1) * nXORWidthBytes;
256 /* top left corner */
257 bgColor.rgbRed = row[0];
258 bgColor.rgbGreen = row[1];
259 bgColor.rgbBlue = row[2];
260 bgColor.rgbReserved = 0;
262 for (i = 0; i < nHeight; i++, row -= nXORWidthBytes)
263 for (j = 0; j < nWidth; j++, row += nBpp >> 3)
266 RGBQUAD *pixel = (RGBQUAD *)row;
267 pixel->rgbBlue = bgColor.rgbBlue;
268 pixel->rgbGreen = bgColor.rgbGreen;
269 pixel->rgbRed = bgColor.rgbRed;
271 pixel->rgbReserved = bgColor.rgbReserved;
277 if (!(png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) ||
278 !(info_ptr = ppng_create_info_struct(png_ptr)))
281 if (setjmp(png_jmpbuf(png_ptr)))
283 /* All future errors jump here */
284 WINE_ERR("png error\n");
288 ppng_init_io(png_ptr, fp);
289 ppng_set_IHDR(png_ptr, info_ptr, nWidth, nHeight, 8,
292 PNG_COMPRESSION_TYPE_DEFAULT,
293 PNG_FILTER_TYPE_DEFAULT);
296 comment.compression = PNG_TEXT_COMPRESSION_NONE;
297 comment.key = (png_charp)comment_key;
298 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
299 comment.text = HeapAlloc(GetProcessHeap(), 0, i);
300 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment.text, i, NULL, NULL);
301 comment.text_length = i - 1;
302 ppng_set_text(png_ptr, info_ptr, &comment, 1);
305 ppng_write_info(png_ptr, info_ptr);
306 ppng_set_bgr(png_ptr);
307 for (i = nHeight - 1; i >= 0 ; i--)
308 ppng_write_row(png_ptr, (png_bytep)pXOR + nXORWidthBytes * i);
309 ppng_write_end(png_ptr, info_ptr);
311 ppng_destroy_write_struct(&png_ptr, &info_ptr);
312 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
314 HeapFree(GetProcessHeap(), 0, copy);
315 HeapFree(GetProcessHeap(), 0, comment.text);
319 if (png_ptr) ppng_destroy_write_struct(&png_ptr, NULL);
321 unlink(png_filename);
322 HeapFree(GetProcessHeap(), 0, copy);
323 HeapFree(GetProcessHeap(), 0, comment.text);
326 #endif /* SONAME_LIBPNG */
328 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
338 BOOL aColorUsed[256] = {0};
343 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
345 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
349 if (!(fXPMFile = fopen(szXPMFileName, "w")))
351 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
355 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
356 comment = HeapAlloc(GetProcessHeap(), 0, i);
357 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
359 nHeight = pIcon->bmiHeader.biHeight / 2;
360 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
361 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
362 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
363 + ((pIcon->bmiHeader.biWidth % 32) > 0));
364 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
365 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
366 : 1 << pIcon->bmiHeader.biBitCount;
367 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
368 pAND = pXOR + nHeight * nXORWidthBytes;
370 #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)
372 for (i = 0; i < nHeight; i++) {
373 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
374 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
376 aColorUsed[COLOR(j,i)] = TRUE;
382 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
384 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
385 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
388 for (i = 0; i < nColors; i++) {
390 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
391 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
394 if (fprintf(fXPMFile, "\" c None\"") <= 0)
397 for (i = 0; i < nHeight; i++)
399 if (fprintf(fXPMFile, ",\n\"") <= 0)
401 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
405 if (fprintf(fXPMFile, " ") <= 0)
409 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
412 if (fprintf(fXPMFile, "\"") <= 0)
415 if (fprintf(fXPMFile, "};\n") <= 0)
421 HeapFree(GetProcessHeap(), 0, comment);
426 HeapFree(GetProcessHeap(), 0, comment);
428 unlink( szXPMFileName );
432 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
434 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
436 if (!sEnumRes->nIndex--)
438 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
445 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
449 LPCWSTR lpName = NULL;
451 GRPICONDIR *pIconDir;
453 ENUMRESSTRUCT sEnumRes;
459 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
462 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
463 wine_dbgstr_w(szFileName), GetLastError());
469 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
470 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
471 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
476 sEnumRes.pResInfo = &hResInfo;
477 sEnumRes.nIndex = nIndex;
478 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
479 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
480 sEnumRes.nIndex != 0)
482 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
488 if ((hResData = LoadResource(hModule, hResInfo)))
490 if ((pIconDir = LockResource(hResData)))
492 for (i = 0; i < pIconDir->idCount; i++)
494 if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
496 nMaxBits = pIconDir->idEntries[i].wBitCount;
498 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
500 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
501 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
507 FreeResource(hResData);
512 WINE_WARN("found no icon\n");
513 FreeLibrary(hModule);
517 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
519 if ((hResData = LoadResource(hModule, hResInfo)))
521 if ((pIcon = LockResource(hResData)))
524 if (SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
529 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
530 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
535 FreeResource(hResData);
539 FreeLibrary(hModule);
543 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, char *szXPMFileName)
545 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
546 !extract_icon16(szFileName, szXPMFileName)*/)
551 static int ExtractFromICO(LPCWSTR szFileName, char *szXPMFileName)
553 FILE *fICOFile = NULL;
555 ICONDIRENTRY *pIconDirEntry = NULL;
556 int nMax = 0, nMaxBits = 0;
560 char *filename = NULL;
562 filename = wine_get_unix_file_name(szFileName);
563 if (!(fICOFile = fopen(filename, "r")))
565 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
569 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
570 (iconDir.idReserved != 0) || (iconDir.idType != 1))
572 WINE_WARN("Invalid ico file format\n");
576 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
578 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
581 for (i = 0; i < iconDir.idCount; i++)
583 WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
584 if (pIconDirEntry[i].wBitCount >= nMaxBits &&
585 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
588 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
589 nMaxBits = pIconDirEntry[i].wBitCount;
592 WINE_TRACE("Selected: %d\n", nIndex);
594 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
596 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
598 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
602 /* Prefer PNG over XPM */
604 if (!SaveIconResAsPNG(pIcon, szXPMFileName, szFileName))
607 memcpy(szXPMFileName + strlen(szXPMFileName) - 3, "xpm", 3);
608 if (!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
612 HeapFree(GetProcessHeap(), 0, pIcon);
613 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
615 HeapFree(GetProcessHeap(), 0, filename);
619 HeapFree(GetProcessHeap(), 0, pIcon);
620 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
621 if (fICOFile) fclose(fICOFile);
622 HeapFree(GetProcessHeap(), 0, filename);
626 static BOOL create_default_icon( const char *filename, const char* comment )
631 if (!(fXPM = fopen(filename, "w"))) return FALSE;
632 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
634 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
635 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
638 if (fprintf( fXPM, "};\n" ) <=0)
649 static unsigned short crc16(const char* string)
651 unsigned short crc = 0;
654 for (i = 0; string[i] != 0; i++)
657 for (j = 0; j < 8; c >>= 1, j++)
659 xor_poly = (c ^ crc) & 1;
668 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
669 static char *extract_icon( LPCWSTR path, int index, BOOL bWait )
672 char *iconsdir, *ico_path, *ico_name, *xpm_path;
677 /* Where should we save the icon? */
678 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
679 iconsdir=NULL; /* Default is no icon */
680 /* @@ Wine registry key: HKCU\Software\Wine\WineMenuBuilder */
681 if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\WineMenuBuilder", &hkey ))
683 static const WCHAR IconsDirW[] = {'I','c','o','n','s','D','i','r',0};
687 if (!RegQueryValueExW(hkey, IconsDirW, 0, NULL, NULL, &size))
689 iconsdirW = HeapAlloc(GetProcessHeap(), 0, size);
690 RegQueryValueExW(hkey, IconsDirW, 0, NULL, (LPBYTE)iconsdirW, &size);
692 if (!(iconsdir = wine_get_unix_file_name(iconsdirW)))
694 int n = WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, NULL, 0, NULL, NULL);
695 iconsdir = HeapAlloc(GetProcessHeap(), 0, n);
696 WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, iconsdir, n, NULL, NULL);
698 HeapFree(GetProcessHeap(), 0, iconsdirW);
705 WCHAR path[MAX_PATH];
706 if (GetTempPathW(MAX_PATH, path))
707 iconsdir = wine_get_unix_file_name(path);
710 WINE_TRACE("no IconsDir\n");
711 return NULL; /* No icon created */
717 WINE_TRACE("icon generation disabled\n");
718 HeapFree(GetProcessHeap(), 0, iconsdir);
719 return NULL; /* No icon created */
722 /* Determine the icon base name */
723 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
724 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
725 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
728 if (*s=='/' || *s=='\\') {
736 if (*ico_name=='\\') *ico_name++='\0';
737 s=strrchr(ico_name,'.');
740 /* Compute the source-path hash */
743 /* Try to treat the source file as an exe */
744 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
745 sprintf(xpm_path,"%s/%04x_%s.%d.png",iconsdir,crc,ico_name,index);
746 if (ExtractFromEXEDLL( path, index, xpm_path ))
749 /* Must be something else, ignore the index in that case */
750 sprintf(xpm_path,"%s/%04x_%s.png",iconsdir,crc,ico_name);
751 if (ExtractFromICO( path, xpm_path))
755 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
756 if (create_default_icon( xpm_path, ico_path ))
760 HeapFree( GetProcessHeap(), 0, xpm_path );
764 HeapFree(GetProcessHeap(), 0, iconsdir);
765 HeapFree(GetProcessHeap(), 0, ico_path);
769 /* This escapes \ in filenames */
770 static LPSTR escape(LPCWSTR arg)
777 while((esc = strchrW(esc, '\\')))
783 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
784 narg = HeapAlloc(GetProcessHeap(), 0, len);
789 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
793 *x++='\\'; /* escape \ */
800 static int fork_and_wait( const char *linker, const char *link_name, const char *path,
801 int desktop, const char *args, const char *icon_name,
802 const char *workdir, const char *description )
805 const char *argv[20];
808 WINE_TRACE( "linker app='%s' link='%s' mode=%s "
809 "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
810 linker, link_name, desktop ? "desktop" : "menu",
811 path, args, icon_name, workdir, description );
813 argv[pos++] = linker ;
814 argv[pos++] = "--link";
815 argv[pos++] = link_name;
816 argv[pos++] = "--path";
818 argv[pos++] = desktop ? "--desktop" : "--menu";
819 if (args && strlen(args))
821 argv[pos++] = "--args";
826 argv[pos++] = "--icon";
827 argv[pos++] = icon_name;
829 if (workdir && strlen(workdir))
831 argv[pos++] = "--workdir";
832 argv[pos++] = workdir;
834 if (description && strlen(description))
836 argv[pos++] = "--descr";
837 argv[pos++] = description;
841 retcode=spawnvp( _P_WAIT, linker, argv );
843 WINE_ERR("%s returned %d\n",linker,retcode);
847 /* Return a heap-allocated copy of the unix format difference between the two
848 * Windows-format paths.
849 * locn is the owning location
850 * link is within locn
852 static char *relative_path( LPCWSTR link, LPCWSTR locn )
854 char *unix_locn, *unix_link;
855 char *relative = NULL;
857 unix_locn = wine_get_unix_file_name(locn);
858 unix_link = wine_get_unix_file_name(link);
859 if (unix_locn && unix_link)
861 size_t len_unix_locn, len_unix_link;
862 len_unix_locn = strlen (unix_locn);
863 len_unix_link = strlen (unix_link);
864 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
867 char *p = strrchr (unix_link + len_unix_locn, '/');
868 p = strrchr (p, '.');
872 len_unix_link = p - unix_link;
874 len_rel = len_unix_link - len_unix_locn;
875 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
878 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
883 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
884 HeapFree(GetProcessHeap(), 0, unix_locn);
885 HeapFree(GetProcessHeap(), 0, unix_link);
889 /***********************************************************************
893 * returns TRUE if successful
894 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
895 * *relative will contain the address of a heap-allocated copy of the portion
896 * of the filename that is within the specified location, in unix form
898 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
900 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
901 DWORD len, i, r, filelen;
902 const DWORD locations[] = {
903 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
904 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
905 CSIDL_COMMON_STARTMENU };
907 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
908 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
909 if (filelen==0 || filelen>MAX_PATH)
912 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
914 /* the CSLU Toolkit uses a short path name when creating .lnk files;
915 * expand or our hardcoded list won't match.
917 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
918 if (filelen==0 || filelen>MAX_PATH)
921 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
923 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
925 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
928 len = lstrlenW(buffer);
930 continue; /* We've just trashed memory! Hopefully we are OK */
932 if (len > filelen || filename[len]!='\\')
934 /* do a lstrcmpinW */
936 r = lstrcmpiW( filename, buffer );
937 filename[len] = '\\';
941 /* return the remainder of the string and link type */
943 *relative = relative_path (filename, buffer);
944 return (*relative != NULL);
950 /* gets the target path directly or through MSI */
951 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
952 LPWSTR szArgs, DWORD argsSize)
954 IShellLinkDataList *dl = NULL;
955 EXP_DARWIN_LINK *dar = NULL;
961 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
962 if (hr == S_OK && szPath[0])
964 IShellLinkW_GetArguments( sl, szArgs, argsSize );
968 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
972 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
979 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
980 if (hr == ERROR_SUCCESS)
983 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
984 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
985 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
986 if (hr == ERROR_SUCCESS)
989 int bcount, in_quotes;
991 /* Extract the application path */
998 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1000 /* skip the remaining spaces */
1003 } while (*s==0x0009 || *s==0x0020);
1006 else if (*s==0x005c)
1012 else if (*s==0x0022)
1015 if ((bcount & 1)==0)
1017 /* Preceded by an even number of '\', this is
1018 * half that number of '\', plus a quote which
1022 in_quotes=!in_quotes;
1027 /* Preceded by an odd number of '\', this is
1028 * half that number of '\' followed by a '"'
1038 /* a regular character */
1042 if ((d-szPath) == pathSize)
1044 /* Keep processing the path till we get to the
1045 * arguments, but 'stand still'
1050 /* Close the application path */
1053 lstrcpynW(szArgs, s, argsSize);
1055 HeapFree( GetProcessHeap(), 0, szCmdline );
1060 IShellLinkDataList_Release( dl );
1064 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
1066 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
1067 '\\','s','t','a','r','t','.','e','x','e',0};
1068 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
1069 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1070 WCHAR szTmp[INFOTIPSIZE];
1071 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1072 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1073 int iIconId = 0, r = -1;
1079 WINE_ERR("Link name is null\n");
1083 if( !GetLinkLocation( link, &csidl, &link_name ) )
1085 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1088 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1090 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1093 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
1096 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
1097 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
1098 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
1101 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
1102 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
1103 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1105 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1106 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
1107 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
1110 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
1111 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
1112 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
1116 LPITEMIDLIST pidl = NULL;
1117 IShellLinkW_GetIDList( sl, &pidl );
1118 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1119 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
1122 /* extract the icon */
1124 icon_name = extract_icon( szIconPath , iIconId, bWait );
1126 icon_name = extract_icon( szPath, iIconId, bWait );
1128 /* fail - try once again after parent process exit */
1133 WINE_WARN("Unable to extract icon, deferring.\n");
1136 WINE_ERR("failed to extract icon from %s\n",
1137 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
1140 /* check the path */
1143 static const WCHAR exeW[] = {'.','e','x','e',0};
1146 /* check for .exe extension */
1147 if (!(p = strrchrW( szPath, '.' )) ||
1148 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
1149 lstrcmpiW( p, exeW ))
1151 /* Not .exe - use 'start.exe' to launch this file */
1152 p = szArgs + lstrlenW(szPath) + 2;
1156 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
1157 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
1163 lstrcpyW(szArgs + 1, szPath);
1166 GetWindowsDirectoryW(szPath, MAX_PATH);
1167 lstrcatW(szPath, startW);
1170 /* convert app working dir */
1172 work_dir = wine_get_unix_file_name( szWorkDir );
1176 /* if there's no path... try run the link itself */
1177 lstrcpynW(szArgs, link, MAX_PATH);
1178 GetWindowsDirectoryW(szPath, MAX_PATH);
1179 lstrcatW(szPath, startW);
1182 /* escape the path and parameters */
1183 escaped_path = escape(szPath);
1184 escaped_args = escape(szArgs);
1185 escaped_description = escape(szDescription);
1187 /* running multiple instances of wineshelllink
1188 at the same time may be dangerous */
1189 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1190 if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
1192 WINE_ERR("failed wait for semaphore\n");
1196 r = fork_and_wait("wineshelllink", link_name, escaped_path,
1197 in_desktop_dir(csidl), escaped_args, icon_name,
1198 work_dir ? work_dir : "", escaped_description);
1200 ReleaseSemaphore( hsem, 1, NULL );
1203 if (hsem) CloseHandle( hsem );
1204 HeapFree( GetProcessHeap(), 0, icon_name );
1205 HeapFree( GetProcessHeap(), 0, work_dir );
1206 HeapFree( GetProcessHeap(), 0, link_name );
1207 HeapFree( GetProcessHeap(), 0, escaped_args );
1208 HeapFree( GetProcessHeap(), 0, escaped_path );
1209 HeapFree( GetProcessHeap(), 0, escaped_description );
1212 WINE_ERR("failed to fork and exec wineshelllink\n" );
1217 static BOOL WaitForParentProcess( void )
1219 PROCESSENTRY32 procentry;
1220 HANDLE hsnapshot = NULL, hprocess = NULL;
1221 DWORD ourpid = GetCurrentProcessId();
1222 BOOL ret = FALSE, rc;
1224 WINE_TRACE("Waiting for parent process\n");
1225 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
1226 INVALID_HANDLE_VALUE)
1228 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
1232 procentry.dwSize = sizeof(PROCESSENTRY32);
1233 rc = Process32First( hsnapshot, &procentry );
1236 if (procentry.th32ProcessID == ourpid) break;
1237 rc = Process32Next( hsnapshot, &procentry );
1241 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
1245 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
1248 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
1253 if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
1256 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
1259 if (hprocess) CloseHandle( hprocess );
1260 if (hsnapshot) CloseHandle( hsnapshot );
1264 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
1269 WCHAR fullname[MAX_PATH];
1272 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
1276 WINE_ERR("link name missing\n");
1280 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1281 if (len==0 || len>MAX_PATH)
1283 WINE_ERR("couldn't get full path of link file\n");
1287 r = CoInitialize( NULL );
1290 WINE_ERR("CoInitialize failed\n");
1294 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1295 &IID_IShellLinkW, (LPVOID *) &sl );
1298 WINE_ERR("No IID_IShellLink\n");
1302 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1305 WINE_ERR("No IID_IPersistFile\n");
1309 r = IPersistFile_Load( pf, fullname, STGM_READ );
1310 if( SUCCEEDED( r ) )
1312 /* If something fails (eg. Couldn't extract icon)
1313 * wait for parent process and try again
1315 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
1317 WaitForParentProcess();
1318 InvokeShellLinker( sl, fullname, FALSE );
1322 IPersistFile_Release( pf );
1323 IShellLinkW_Release( sl );
1331 static CHAR *next_token( LPSTR *p )
1333 LPSTR token = NULL, t = *p;
1338 while( t && !token )
1346 /* unquote the token */
1348 t = strchr( token, '"' );
1357 t = strchr( token, ' ' );
1367 /***********************************************************************
1371 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1373 LPSTR token = NULL, p;
1377 for( p = cmdline; p && *p; )
1379 token = next_token( &p );
1382 if( !lstrcmpA( token, "-w" ) )
1384 else if( token[0] == '-' )
1386 WINE_ERR( "unknown option %s\n",token);
1390 WCHAR link[MAX_PATH];
1392 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1393 if( !Process_Link( link, bWait ) )
1395 WINE_ERR( "failed to build menu item for %s\n",token);