msxml3: Implemented IDispatch for IXMLDOMNamedNodeMap.
[wine.git] / programs / winemenubuilder / winemenubuilder.c
blob06ffd451c6fd2bd957a23dcc50f1a98b183df553
1 /*
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.
43 * TODO
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
47 * files).
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
52 * group.
56 #include "config.h"
57 #include "wine/port.h"
59 #include <ctype.h>
60 #include <stdio.h>
61 #include <string.h>
62 #ifdef HAVE_UNISTD_H
63 #include <unistd.h>
64 #endif
65 #include <errno.h>
66 #include <stdarg.h>
68 #define COBJMACROS
70 #include <windows.h>
71 #include <shlobj.h>
72 #include <objidl.h>
73 #include <shlguid.h>
74 #include <appmgmt.h>
75 #include <tlhelp32.h>
77 #include "wine/unicode.h"
78 #include "wine/debug.h"
79 #include "wine.xpm"
81 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
83 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
84 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
85 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
86 (csidl)==CSIDL_COMMON_STARTMENU)
88 /* link file formats */
90 #include "pshpack1.h"
92 typedef struct
94 BYTE bWidth;
95 BYTE bHeight;
96 BYTE bColorCount;
97 BYTE bReserved;
98 WORD wPlanes;
99 WORD wBitCount;
100 DWORD dwBytesInRes;
101 WORD nID;
102 } GRPICONDIRENTRY;
104 typedef struct
106 WORD idReserved;
107 WORD idType;
108 WORD idCount;
109 GRPICONDIRENTRY idEntries[1];
110 } GRPICONDIR;
112 typedef struct
114 BYTE bWidth;
115 BYTE bHeight;
116 BYTE bColorCount;
117 BYTE bReserved;
118 WORD wPlanes;
119 WORD wBitCount;
120 DWORD dwBytesInRes;
121 DWORD dwImageOffset;
122 } ICONDIRENTRY;
124 typedef struct
126 WORD idReserved;
127 WORD idType;
128 WORD idCount;
129 } ICONDIR;
132 #include "poppack.h"
134 typedef struct
136 HRSRC *pResInfo;
137 int nIndex;
138 } ENUMRESSTRUCT;
141 /* Icon extraction routines
143 * FIXME: should use PrivateExtractIcons and friends
144 * FIXME: should not use stdio
147 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
149 FILE *fXPMFile;
150 int nHeight;
151 int nXORWidthBytes;
152 int nANDWidthBytes;
153 BOOL b8BitColors;
154 int nColors;
155 const BYTE *pXOR;
156 const BYTE *pAND;
157 BOOL aColorUsed[256] = {0};
158 int nColorsUsed = 0;
159 int i,j;
160 char *comment;
162 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
164 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
165 return FALSE;
168 if (!(fXPMFile = fopen(szXPMFileName, "w")))
170 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
171 return FALSE;
174 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
175 comment = HeapAlloc(GetProcessHeap(), 0, i);
176 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
178 nHeight = pIcon->bmiHeader.biHeight / 2;
179 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
180 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
181 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
182 + ((pIcon->bmiHeader.biWidth % 32) > 0));
183 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
184 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
185 : 1 << pIcon->bmiHeader.biBitCount;
186 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
187 pAND = pXOR + nHeight * nXORWidthBytes;
189 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
190 #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)
192 for (i = 0; i < nHeight; i++) {
193 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
194 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
196 aColorUsed[COLOR(j,i)] = TRUE;
197 nColorsUsed++;
202 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
203 goto error;
204 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
205 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
206 goto error;
208 for (i = 0; i < nColors; i++) {
209 if (aColorUsed[i])
210 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
211 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
212 goto error;
214 if (fprintf(fXPMFile, "\" c None\"") <= 0)
215 goto error;
217 for (i = 0; i < nHeight; i++)
219 if (fprintf(fXPMFile, ",\n\"") <= 0)
220 goto error;
221 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
223 if MASK(j,i)
225 if (fprintf(fXPMFile, " ") <= 0)
226 goto error;
228 else
229 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
230 goto error;
232 if (fprintf(fXPMFile, "\"") <= 0)
233 goto error;
235 if (fprintf(fXPMFile, "};\n") <= 0)
236 goto error;
238 #undef MASK
239 #undef COLOR
241 HeapFree(GetProcessHeap(), 0, comment);
242 fclose(fXPMFile);
243 return TRUE;
245 error:
246 HeapFree(GetProcessHeap(), 0, comment);
247 fclose(fXPMFile);
248 unlink( szXPMFileName );
249 return FALSE;
252 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
254 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
256 if (!sEnumRes->nIndex--)
258 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
259 return FALSE;
261 else
262 return TRUE;
265 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
267 HMODULE hModule;
268 HRSRC hResInfo;
269 LPCWSTR lpName = NULL;
270 HGLOBAL hResData;
271 GRPICONDIR *pIconDir;
272 BITMAPINFO *pIcon;
273 ENUMRESSTRUCT sEnumRes;
274 int nMax = 0;
275 int nMaxBits = 0;
276 int i;
277 BOOL ret = FALSE;
279 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
280 if (!hModule)
282 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
283 wine_dbgstr_w(szFileName), GetLastError());
284 return FALSE;
287 if (nIndex < 0)
289 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
290 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
291 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
293 else
295 hResInfo=NULL;
296 sEnumRes.pResInfo = &hResInfo;
297 sEnumRes.nIndex = nIndex;
298 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
299 EnumResNameProc, (LONG_PTR)&sEnumRes) &&
300 sEnumRes.nIndex != 0)
302 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
306 if (hResInfo)
308 if ((hResData = LoadResource(hModule, hResInfo)))
310 if ((pIconDir = LockResource(hResData)))
312 for (i = 0; i < pIconDir->idCount; i++)
314 if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
316 nMaxBits = pIconDir->idEntries[i].wBitCount;
318 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
320 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
321 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
327 FreeResource(hResData);
330 else
332 WINE_WARN("found no icon\n");
333 FreeLibrary(hModule);
334 return FALSE;
337 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
339 if ((hResData = LoadResource(hModule, hResInfo)))
341 if ((pIcon = LockResource(hResData)))
343 if(SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
344 ret = TRUE;
347 FreeResource(hResData);
351 FreeLibrary(hModule);
352 return ret;
355 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
357 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
358 !extract_icon16(szFileName, szXPMFileName)*/)
359 return FALSE;
360 return TRUE;
363 static int ExtractFromICO(LPCWSTR szFileName, const char *szXPMFileName)
365 FILE *fICOFile;
366 ICONDIR iconDir;
367 ICONDIRENTRY *pIconDirEntry;
368 int nMax = 0, nMaxBits = 0;
369 int nIndex = 0;
370 void *pIcon;
371 int i;
372 char *filename;
374 filename = wine_get_unix_file_name(szFileName);
375 if (!(fICOFile = fopen(filename, "r")))
377 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
378 goto error1;
381 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
382 (iconDir.idReserved != 0) || (iconDir.idType != 1))
384 WINE_WARN("Invalid ico file format\n");
385 goto error2;
388 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
389 goto error2;
390 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
391 goto error3;
393 for (i = 0; i < iconDir.idCount; i++)
394 if (pIconDirEntry[i].wBitCount <= 8 && pIconDirEntry[i].wBitCount >= nMaxBits &&
395 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
397 nIndex = i;
398 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
399 nMaxBits = pIconDirEntry[i].wBitCount;
401 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
402 goto error3;
403 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
404 goto error4;
405 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
406 goto error4;
408 if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
409 goto error4;
411 HeapFree(GetProcessHeap(), 0, pIcon);
412 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
413 fclose(fICOFile);
414 HeapFree(GetProcessHeap(), 0, filename);
415 return 1;
417 error4:
418 HeapFree(GetProcessHeap(), 0, pIcon);
419 error3:
420 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
421 error2:
422 fclose(fICOFile);
423 error1:
424 HeapFree(GetProcessHeap(), 0, filename);
425 return 0;
428 static BOOL create_default_icon( const char *filename, const char* comment )
430 FILE *fXPM;
431 unsigned int i;
433 if (!(fXPM = fopen(filename, "w"))) return FALSE;
434 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
435 goto error;
436 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
437 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
438 goto error;
440 if (fprintf( fXPM, "};\n" ) <=0)
441 goto error;
442 fclose( fXPM );
443 return TRUE;
444 error:
445 fclose( fXPM );
446 unlink( filename );
447 return FALSE;
451 static unsigned short crc16(const char* string)
453 unsigned short crc = 0;
454 int i, j, xor_poly;
456 for (i = 0; string[i] != 0; i++)
458 char c = string[i];
459 for (j = 0; j < 8; c >>= 1, j++)
461 xor_poly = (c ^ crc) & 1;
462 crc >>= 1;
463 if (xor_poly)
464 crc ^= 0xa001;
467 return crc;
470 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
471 static char *extract_icon( LPCWSTR path, int index, BOOL bWait )
473 unsigned short crc;
474 char *iconsdir, *ico_path, *ico_name, *xpm_path;
475 char* s;
476 HKEY hkey;
477 int n;
479 /* Where should we save the icon? */
480 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
481 iconsdir=NULL; /* Default is no icon */
482 /* @@ Wine registry key: HKCU\Software\Wine\WineMenuBuilder */
483 if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\WineMenuBuilder", &hkey ))
485 static const WCHAR IconsDirW[] = {'I','c','o','n','s','D','i','r',0};
486 LPWSTR iconsdirW;
487 DWORD size = 0;
489 if (!RegQueryValueExW(hkey, IconsDirW, 0, NULL, NULL, &size))
491 iconsdirW = HeapAlloc(GetProcessHeap(), 0, size);
492 RegQueryValueExW(hkey, IconsDirW, 0, NULL, (LPBYTE)iconsdirW, &size);
494 if (!(iconsdir = wine_get_unix_file_name(iconsdirW)))
496 int n = WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, NULL, 0, NULL, NULL);
497 iconsdir = HeapAlloc(GetProcessHeap(), 0, n);
498 WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, iconsdir, n, NULL, NULL);
500 HeapFree(GetProcessHeap(), 0, iconsdirW);
502 RegCloseKey( hkey );
505 if (!iconsdir)
507 WCHAR path[MAX_PATH];
508 if (GetTempPathW(MAX_PATH, path))
509 iconsdir = wine_get_unix_file_name(path);
510 if (!iconsdir)
512 WINE_TRACE("no IconsDir\n");
513 return NULL; /* No icon created */
517 if (!*iconsdir)
519 WINE_TRACE("icon generation disabled\n");
520 HeapFree(GetProcessHeap(), 0, iconsdir);
521 return NULL; /* No icon created */
524 /* Determine the icon base name */
525 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
526 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
527 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
528 s=ico_name=ico_path;
529 while (*s!='\0') {
530 if (*s=='/' || *s=='\\') {
531 *s='\\';
532 ico_name=s;
533 } else {
534 *s=tolower(*s);
536 s++;
538 if (*ico_name=='\\') *ico_name++='\0';
539 s=strrchr(ico_name,'.');
540 if (s) *s='\0';
542 /* Compute the source-path hash */
543 crc=crc16(ico_path);
545 /* Try to treat the source file as an exe */
546 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
547 sprintf(xpm_path,"%s/%04x_%s.%d.xpm",iconsdir,crc,ico_name,index);
548 if (ExtractFromEXEDLL( path, index, xpm_path ))
549 goto end;
551 /* Must be something else, ignore the index in that case */
552 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
553 if (ExtractFromICO( path, xpm_path))
554 goto end;
555 if (!bWait)
556 if (create_default_icon( xpm_path, ico_path ))
557 goto end;
559 HeapFree( GetProcessHeap(), 0, xpm_path );
560 xpm_path=NULL;
562 end:
563 HeapFree(GetProcessHeap(), 0, iconsdir);
564 HeapFree(GetProcessHeap(), 0, ico_path);
565 return xpm_path;
568 /* This escapes \ in filenames */
569 static LPSTR escape(LPCWSTR arg)
571 LPSTR narg, x;
572 LPCWSTR esc;
573 int len = 0, n;
575 esc = arg;
576 while((esc = strchrW(esc, '\\')))
578 esc++;
579 len++;
582 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
583 narg = HeapAlloc(GetProcessHeap(), 0, len);
585 x = narg;
586 while (*arg)
588 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
589 x += n;
590 len -= n;
591 if (*arg == '\\')
592 *x++='\\'; /* escape \ */
593 arg++;
595 *x = 0;
596 return narg;
599 static int fork_and_wait( const char *linker, const char *link_name, const char *path,
600 int desktop, const char *args, const char *icon_name,
601 const char *workdir, const char *description )
603 int pos = 0;
604 const char *argv[20];
605 int retcode;
607 WINE_TRACE( "linker app='%s' link='%s' mode=%s "
608 "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
609 linker, link_name, desktop ? "desktop" : "menu",
610 path, args, icon_name, workdir, description );
612 argv[pos++] = linker ;
613 argv[pos++] = "--link";
614 argv[pos++] = link_name;
615 argv[pos++] = "--path";
616 argv[pos++] = path;
617 argv[pos++] = desktop ? "--desktop" : "--menu";
618 if (args && strlen(args))
620 argv[pos++] = "--args";
621 argv[pos++] = args;
623 if (icon_name)
625 argv[pos++] = "--icon";
626 argv[pos++] = icon_name;
628 if (workdir && strlen(workdir))
630 argv[pos++] = "--workdir";
631 argv[pos++] = workdir;
633 if (description && strlen(description))
635 argv[pos++] = "--descr";
636 argv[pos++] = description;
638 argv[pos] = NULL;
640 retcode=spawnvp( _P_WAIT, linker, argv );
641 if (retcode!=0)
642 WINE_ERR("%s returned %d\n",linker,retcode);
643 return retcode;
646 /* Return a heap-allocated copy of the unix format difference between the two
647 * Windows-format paths.
648 * locn is the owning location
649 * link is within locn
651 static char *relative_path( LPCWSTR link, LPCWSTR locn )
653 char *unix_locn, *unix_link;
654 char *relative = NULL;
656 unix_locn = wine_get_unix_file_name(locn);
657 unix_link = wine_get_unix_file_name(link);
658 if (unix_locn && unix_link)
660 size_t len_unix_locn, len_unix_link;
661 len_unix_locn = strlen (unix_locn);
662 len_unix_link = strlen (unix_link);
663 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
665 size_t len_rel;
666 char *p = strrchr (unix_link + len_unix_locn, '/');
667 p = strrchr (p, '.');
668 if (p)
670 *p = '\0';
671 len_unix_link = p - unix_link;
673 len_rel = len_unix_link - len_unix_locn;
674 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
675 if (relative)
677 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
681 if (!relative)
682 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
683 HeapFree(GetProcessHeap(), 0, unix_locn);
684 HeapFree(GetProcessHeap(), 0, unix_link);
685 return relative;
688 /***********************************************************************
690 * GetLinkLocation
692 * returns TRUE if successful
693 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
694 * *relative will contain the address of a heap-allocated copy of the portion
695 * of the filename that is within the specified location, in unix form
697 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
699 WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
700 DWORD len, i, r, filelen;
701 const DWORD locations[] = {
702 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
703 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
704 CSIDL_COMMON_STARTMENU };
706 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
707 filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
708 if (filelen==0 || filelen>MAX_PATH)
709 return FALSE;
711 WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));
713 /* the CSLU Toolkit uses a short path name when creating .lnk files;
714 * expand or our hardcoded list won't match.
716 filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
717 if (filelen==0 || filelen>MAX_PATH)
718 return FALSE;
720 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
722 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
724 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
725 continue;
727 len = lstrlenW(buffer);
728 if (len >= MAX_PATH)
729 continue; /* We've just trashed memory! Hopefully we are OK */
731 if (len > filelen || filename[len]!='\\')
732 continue;
733 /* do a lstrcmpinW */
734 filename[len] = 0;
735 r = lstrcmpiW( filename, buffer );
736 filename[len] = '\\';
737 if ( r )
738 continue;
740 /* return the remainder of the string and link type */
741 *loc = locations[i];
742 *relative = relative_path (filename, buffer);
743 return (*relative != NULL);
746 return FALSE;
749 /* gets the target path directly or through MSI */
750 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
751 LPWSTR szArgs, DWORD argsSize)
753 IShellLinkDataList *dl = NULL;
754 EXP_DARWIN_LINK *dar = NULL;
755 HRESULT hr;
757 szPath[0] = 0;
758 szArgs[0] = 0;
760 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
761 if (hr == S_OK && szPath[0])
763 IShellLinkW_GetArguments( sl, szArgs, argsSize );
764 return hr;
767 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
768 if (FAILED(hr))
769 return hr;
771 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
772 if (SUCCEEDED(hr))
774 WCHAR* szCmdline;
775 DWORD cmdSize;
777 cmdSize=0;
778 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
779 if (hr == ERROR_SUCCESS)
781 cmdSize++;
782 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
783 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
784 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
785 if (hr == ERROR_SUCCESS)
787 WCHAR *s, *d;
788 int bcount, in_quotes;
790 /* Extract the application path */
791 bcount=0;
792 in_quotes=0;
793 s=szCmdline;
794 d=szPath;
795 while (*s)
797 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
799 /* skip the remaining spaces */
800 do {
801 s++;
802 } while (*s==0x0009 || *s==0x0020);
803 break;
805 else if (*s==0x005c)
807 /* '\\' */
808 *d++=*s++;
809 bcount++;
811 else if (*s==0x0022)
813 /* '"' */
814 if ((bcount & 1)==0)
816 /* Preceded by an even number of '\', this is
817 * half that number of '\', plus a quote which
818 * we erase.
820 d-=bcount/2;
821 in_quotes=!in_quotes;
822 s++;
824 else
826 /* Preceded by an odd number of '\', this is
827 * half that number of '\' followed by a '"'
829 d=d-bcount/2-1;
830 *d++='"';
831 s++;
833 bcount=0;
835 else
837 /* a regular character */
838 *d++=*s++;
839 bcount=0;
841 if ((d-szPath) == pathSize)
843 /* Keep processing the path till we get to the
844 * arguments, but 'stand still'
846 d--;
849 /* Close the application path */
850 *d=0;
852 lstrcpynW(szArgs, s, argsSize);
854 HeapFree( GetProcessHeap(), 0, szCmdline );
856 LocalFree( dar );
859 IShellLinkDataList_Release( dl );
860 return hr;
863 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
865 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
866 '\\','s','t','a','r','t','.','e','x','e',0};
867 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
868 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
869 WCHAR szTmp[INFOTIPSIZE];
870 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
871 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
872 int iIconId = 0, r = -1;
873 DWORD csidl = -1;
874 HANDLE hsem = NULL;
876 if ( !link )
878 WINE_ERR("Link name is null\n");
879 return FALSE;
882 if( !GetLinkLocation( link, &csidl, &link_name ) )
884 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
885 return TRUE;
887 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
889 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
890 return TRUE;
892 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
894 szTmp[0] = 0;
895 IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
896 ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
897 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
899 szTmp[0] = 0;
900 IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
901 ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
902 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
904 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
905 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
906 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
908 szTmp[0] = 0;
909 IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
910 ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
911 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
913 if( !szPath[0] )
915 LPITEMIDLIST pidl = NULL;
916 IShellLinkW_GetIDList( sl, &pidl );
917 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
918 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
921 /* extract the icon */
922 if( szIconPath[0] )
923 icon_name = extract_icon( szIconPath , iIconId, bWait );
924 else
925 icon_name = extract_icon( szPath, iIconId, bWait );
927 /* fail - try once again after parent process exit */
928 if( !icon_name )
930 if (bWait)
932 WINE_WARN("Unable to extract icon, deferring.\n");
933 goto cleanup;
935 WINE_ERR("failed to extract icon from %s\n",
936 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
939 /* check the path */
940 if( szPath[0] )
942 static const WCHAR exeW[] = {'.','e','x','e',0};
943 WCHAR *p;
945 /* check for .exe extension */
946 if (!(p = strrchrW( szPath, '.' )) ||
947 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
948 lstrcmpiW( p, exeW ))
950 /* Not .exe - use 'start.exe' to launch this file */
951 p = szArgs + lstrlenW(szPath) + 2;
952 if (szArgs[0])
954 p[0] = ' ';
955 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
956 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
958 else
959 p[0] = 0;
961 szArgs[0] = '"';
962 lstrcpyW(szArgs + 1, szPath);
963 p[-1] = '"';
965 GetWindowsDirectoryW(szPath, MAX_PATH);
966 lstrcatW(szPath, startW);
969 /* convert app working dir */
970 if (szWorkDir[0])
971 work_dir = wine_get_unix_file_name( szWorkDir );
973 else
975 /* if there's no path... try run the link itself */
976 lstrcpynW(szArgs, link, MAX_PATH);
977 GetWindowsDirectoryW(szPath, MAX_PATH);
978 lstrcatW(szPath, startW);
981 /* escape the path and parameters */
982 escaped_path = escape(szPath);
983 escaped_args = escape(szArgs);
984 escaped_description = escape(szDescription);
986 /* running multiple instances of wineshelllink
987 at the same time may be dangerous */
988 hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
989 if( WAIT_OBJECT_0 != WaitForSingleObject( hsem, INFINITE ) )
991 WINE_ERR("failed wait for semaphore\n");
992 goto cleanup;
995 r = fork_and_wait("wineshelllink", link_name, escaped_path,
996 in_desktop_dir(csidl), escaped_args, icon_name,
997 work_dir ? work_dir : "", escaped_description);
999 ReleaseSemaphore( hsem, 1, NULL );
1001 cleanup:
1002 if (hsem) CloseHandle( hsem );
1003 HeapFree( GetProcessHeap(), 0, icon_name );
1004 HeapFree( GetProcessHeap(), 0, work_dir );
1005 HeapFree( GetProcessHeap(), 0, link_name );
1006 HeapFree( GetProcessHeap(), 0, escaped_args );
1007 HeapFree( GetProcessHeap(), 0, escaped_path );
1008 HeapFree( GetProcessHeap(), 0, escaped_description );
1010 if (r && !bWait)
1011 WINE_ERR("failed to fork and exec wineshelllink\n" );
1013 return ( r == 0 );
1016 static BOOL WaitForParentProcess( void )
1018 PROCESSENTRY32 procentry;
1019 HANDLE hsnapshot = NULL, hprocess = NULL;
1020 DWORD ourpid = GetCurrentProcessId();
1021 BOOL ret = FALSE, rc;
1023 WINE_TRACE("Waiting for parent process\n");
1024 if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
1025 INVALID_HANDLE_VALUE)
1027 WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
1028 goto done;
1031 procentry.dwSize = sizeof(PROCESSENTRY32);
1032 rc = Process32First( hsnapshot, &procentry );
1033 while (rc)
1035 if (procentry.th32ProcessID == ourpid) break;
1036 rc = Process32Next( hsnapshot, &procentry );
1038 if (!rc)
1040 WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
1041 goto done;
1044 if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
1045 NULL)
1047 WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
1048 GetLastError());
1049 goto done;
1052 if (WaitForSingleObject( hprocess, INFINITE ) == WAIT_OBJECT_0)
1053 ret = TRUE;
1054 else
1055 WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());
1057 done:
1058 if (hprocess) CloseHandle( hprocess );
1059 if (hsnapshot) CloseHandle( hsnapshot );
1060 return ret;
1063 static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
1065 IShellLinkW *sl;
1066 IPersistFile *pf;
1067 HRESULT r;
1068 WCHAR fullname[MAX_PATH];
1069 DWORD len;
1071 WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
1073 if( !linkname[0] )
1075 WINE_ERR("link name missing\n");
1076 return 1;
1079 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1080 if (len==0 || len>MAX_PATH)
1082 WINE_ERR("couldn't get full path of link file\n");
1083 return 1;
1086 r = CoInitialize( NULL );
1087 if( FAILED( r ) )
1089 WINE_ERR("CoInitialize failed\n");
1090 return 1;
1093 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1094 &IID_IShellLinkW, (LPVOID *) &sl );
1095 if( FAILED( r ) )
1097 WINE_ERR("No IID_IShellLink\n");
1098 return 1;
1101 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1102 if( FAILED( r ) )
1104 WINE_ERR("No IID_IPersistFile\n");
1105 return 1;
1108 r = IPersistFile_Load( pf, fullname, STGM_READ );
1109 if( SUCCEEDED( r ) )
1111 /* If something fails (eg. Couldn't extract icon)
1112 * wait for parent process and try again
1114 if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
1116 WaitForParentProcess();
1117 InvokeShellLinker( sl, fullname, FALSE );
1121 IPersistFile_Release( pf );
1122 IShellLinkW_Release( sl );
1124 CoUninitialize();
1126 return !r;
1130 static CHAR *next_token( LPSTR *p )
1132 LPSTR token = NULL, t = *p;
1134 if( !t )
1135 return NULL;
1137 while( t && !token )
1139 switch( *t )
1141 case ' ':
1142 t++;
1143 continue;
1144 case '"':
1145 /* unquote the token */
1146 token = ++t;
1147 t = strchr( token, '"' );
1148 if( t )
1149 *t++ = 0;
1150 break;
1151 case 0:
1152 t = NULL;
1153 break;
1154 default:
1155 token = t;
1156 t = strchr( token, ' ' );
1157 if( t )
1158 *t++ = 0;
1159 break;
1162 *p = t;
1163 return token;
1166 /***********************************************************************
1168 * WinMain
1170 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1172 LPSTR token = NULL, p;
1173 BOOL bWait = FALSE;
1174 int ret = 0;
1176 for( p = cmdline; p && *p; )
1178 token = next_token( &p );
1179 if( !token )
1180 break;
1181 if( !lstrcmpA( token, "-w" ) )
1182 bWait = TRUE;
1183 else if( token[0] == '-' )
1185 WINE_ERR( "unknown option %s\n",token);
1187 else
1189 WCHAR link[MAX_PATH];
1191 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1192 if( !Process_Link( link, bWait ) )
1194 WINE_ERR( "failed to build menu item for %s\n",token);
1195 ret = 1;
1200 return ret;