shell32/tests: Fixed a test failing on WinXP.
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blob38231426360f6ea1f50b66b151968a1b1e8d380c
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 [ -r ] <shortcut.lnk>
38 * If the -r parameter is passed, and the shortcut cannot be created,
39 * this program will add a RunOnce entry to invoke itself at the next
40 * reboot. 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>
76 #include "wine/unicode.h"
77 #include "wine/debug.h"
78 #include "wine.xpm"
80 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
82 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
83 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
84 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
85 (csidl)==CSIDL_COMMON_STARTMENU)
87 /* link file formats */
89 #include "pshpack1.h"
91 typedef struct
93 BYTE bWidth;
94 BYTE bHeight;
95 BYTE bColorCount;
96 BYTE bReserved;
97 WORD wPlanes;
98 WORD wBitCount;
99 DWORD dwBytesInRes;
100 WORD nID;
101 } GRPICONDIRENTRY;
103 typedef struct
105 WORD idReserved;
106 WORD idType;
107 WORD idCount;
108 GRPICONDIRENTRY idEntries[1];
109 } GRPICONDIR;
111 typedef struct
113 BYTE bWidth;
114 BYTE bHeight;
115 BYTE bColorCount;
116 BYTE bReserved;
117 WORD wPlanes;
118 WORD wBitCount;
119 DWORD dwBytesInRes;
120 DWORD dwImageOffset;
121 } ICONDIRENTRY;
123 typedef struct
125 WORD idReserved;
126 WORD idType;
127 WORD idCount;
128 } ICONDIR;
131 #include "poppack.h"
133 typedef struct
135 HRSRC *pResInfo;
136 int nIndex;
137 } ENUMRESSTRUCT;
140 /* Icon extraction routines
142 * FIXME: should use PrivateExtractIcons and friends
143 * FIXME: should not use stdio
146 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
148 FILE *fXPMFile;
149 int nHeight;
150 int nXORWidthBytes;
151 int nANDWidthBytes;
152 BOOL b8BitColors;
153 int nColors;
154 const BYTE *pXOR;
155 const BYTE *pAND;
156 BOOL aColorUsed[256] = {0};
157 int nColorsUsed = 0;
158 int i,j;
159 char *comment;
161 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
162 return FALSE;
164 if (!(fXPMFile = fopen(szXPMFileName, "w")))
165 return FALSE;
167 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
168 comment = malloc(i);
169 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
171 nHeight = pIcon->bmiHeader.biHeight / 2;
172 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
173 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
174 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
175 + ((pIcon->bmiHeader.biWidth % 32) > 0));
176 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
177 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
178 : 1 << pIcon->bmiHeader.biBitCount;
179 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
180 pAND = pXOR + nHeight * nXORWidthBytes;
182 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
183 #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)
185 for (i = 0; i < nHeight; i++) {
186 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
187 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
189 aColorUsed[COLOR(j,i)] = TRUE;
190 nColorsUsed++;
195 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
196 goto error;
197 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
198 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
199 goto error;
201 for (i = 0; i < nColors; i++) {
202 if (aColorUsed[i])
203 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
204 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
205 goto error;
207 if (fprintf(fXPMFile, "\" c None\"") <= 0)
208 goto error;
210 for (i = 0; i < nHeight; i++)
212 if (fprintf(fXPMFile, ",\n\"") <= 0)
213 goto error;
214 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
216 if MASK(j,i)
218 if (fprintf(fXPMFile, " ") <= 0)
219 goto error;
221 else
222 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
223 goto error;
225 if (fprintf(fXPMFile, "\"") <= 0)
226 goto error;
228 if (fprintf(fXPMFile, "};\n") <= 0)
229 goto error;
231 #undef MASK
232 #undef COLOR
234 free(comment);
235 fclose(fXPMFile);
236 return TRUE;
238 error:
239 free(comment);
240 fclose(fXPMFile);
241 unlink( szXPMFileName );
242 return FALSE;
245 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
247 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
249 if (!sEnumRes->nIndex--)
251 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
252 return FALSE;
254 else
255 return TRUE;
258 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
260 HMODULE hModule;
261 HRSRC hResInfo;
262 LPCWSTR lpName = NULL;
263 HGLOBAL hResData;
264 GRPICONDIR *pIconDir;
265 BITMAPINFO *pIcon;
266 ENUMRESSTRUCT sEnumRes;
267 int nMax = 0;
268 int nMaxBits = 0;
269 int i;
270 BOOL ret = FALSE;
272 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
273 if (!hModule)
275 WINE_ERR("LoadLibraryExW (%s) failed, error %ld\n",
276 wine_dbgstr_w(szFileName), GetLastError());
277 return FALSE;
280 if (nIndex < 0)
282 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
283 WINE_TRACE("FindResourceW (%s) called, return %p, error %ld\n",
284 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
286 else
288 hResInfo=NULL;
289 sEnumRes.pResInfo = &hResInfo;
290 sEnumRes.nIndex = nIndex;
291 EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON, EnumResNameProc, (LONG_PTR)&sEnumRes);
294 if (hResInfo)
296 if ((hResData = LoadResource(hModule, hResInfo)))
298 if ((pIconDir = LockResource(hResData)))
300 for (i = 0; i < pIconDir->idCount; i++)
302 if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
304 nMaxBits = pIconDir->idEntries[i].wBitCount;
306 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
308 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
309 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
315 FreeResource(hResData);
318 else
320 WINE_ERR("ExtractFromEXEDLL failed, error %ld\n", GetLastError());
321 FreeLibrary(hModule);
322 return FALSE;
325 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
327 if ((hResData = LoadResource(hModule, hResInfo)))
329 if ((pIcon = LockResource(hResData)))
331 if(SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
332 ret = TRUE;
335 FreeResource(hResData);
339 FreeLibrary(hModule);
340 return ret;
343 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
345 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
346 !extract_icon16(szFileName, szXPMFileName)*/)
347 return FALSE;
348 return TRUE;
351 static int ExtractFromICO(LPCWSTR szFileName, const char *szXPMFileName)
353 FILE *fICOFile;
354 ICONDIR iconDir;
355 ICONDIRENTRY *pIconDirEntry;
356 int nMax = 0;
357 int nIndex = 0;
358 void *pIcon;
359 int i;
360 char *filename;
362 filename = wine_get_unix_file_name(szFileName);
363 if (!(fICOFile = fopen(filename, "r")))
364 goto error1;
366 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1)
367 goto error2;
368 if ((iconDir.idReserved != 0) || (iconDir.idType != 1))
369 goto error2;
371 if ((pIconDirEntry = malloc(iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
372 goto error2;
373 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
374 goto error3;
376 for (i = 0; i < iconDir.idCount; i++)
377 if ((pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) > nMax)
379 nIndex = i;
380 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
382 if ((pIcon = malloc(pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
383 goto error3;
384 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
385 goto error4;
386 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
387 goto error4;
389 if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
390 goto error4;
392 free(pIcon);
393 free(pIconDirEntry);
394 fclose(fICOFile);
395 HeapFree(GetProcessHeap(), 0, filename);
396 return 1;
398 error4:
399 free(pIcon);
400 error3:
401 free(pIconDirEntry);
402 error2:
403 fclose(fICOFile);
404 error1:
405 HeapFree(GetProcessHeap(), 0, filename);
406 return 0;
409 static BOOL create_default_icon( const char *filename, const char* comment )
411 FILE *fXPM;
412 unsigned int i;
414 if (!(fXPM = fopen(filename, "w"))) return FALSE;
415 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
416 goto error;
417 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
418 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
419 goto error;
421 if (fprintf( fXPM, "};\n" ) <=0)
422 goto error;
423 fclose( fXPM );
424 return TRUE;
425 error:
426 fclose( fXPM );
427 unlink( filename );
428 return FALSE;
432 static unsigned short crc16(const char* string)
434 unsigned short crc = 0;
435 int i, j, xor_poly;
437 for (i = 0; string[i] != 0; i++)
439 char c = string[i];
440 for (j = 0; j < 8; c >>= 1, j++)
442 xor_poly = (c ^ crc) & 1;
443 crc >>= 1;
444 if (xor_poly)
445 crc ^= 0xa001;
448 return crc;
451 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
452 static char *extract_icon( LPCWSTR path, int index)
454 int nodefault = 1;
455 unsigned short crc;
456 char *iconsdir, *ico_path, *ico_name, *xpm_path;
457 char* s;
458 HKEY hkey;
459 int n;
461 /* Where should we save the icon? */
462 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
463 iconsdir=NULL; /* Default is no icon */
464 /* @@ Wine registry key: HKCU\Software\Wine\WineMenuBuilder */
465 if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\WineMenuBuilder", &hkey ))
467 static const WCHAR IconsDirW[] = {'I','c','o','n','s','D','i','r',0};
468 LPWSTR iconsdirW;
469 DWORD size = 0;
471 if (!RegQueryValueExW(hkey, IconsDirW, 0, NULL, NULL, &size))
473 iconsdirW = HeapAlloc(GetProcessHeap(), 0, size);
474 RegQueryValueExW(hkey, IconsDirW, 0, NULL, (LPBYTE)iconsdirW, &size);
476 if (!(iconsdir = wine_get_unix_file_name(iconsdirW)))
478 int n = WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, NULL, 0, NULL, NULL);
479 iconsdir = HeapAlloc(GetProcessHeap(), 0, n);
480 WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, iconsdir, n, NULL, NULL);
482 HeapFree(GetProcessHeap(), 0, iconsdirW);
484 RegCloseKey( hkey );
487 if (!iconsdir)
489 WCHAR path[MAX_PATH];
491 if (GetTempPathW(MAX_PATH, path)) iconsdir = wine_get_unix_file_name(path);
494 if (!iconsdir)
495 return NULL; /* No icon created */
497 if (!*iconsdir)
499 HeapFree(GetProcessHeap(), 0, iconsdir);
500 return NULL; /* No icon created */
503 /* If icon path begins with a '*' then this is a deferred call */
504 if (path[0] == '*')
506 path++;
507 nodefault = 0;
510 /* Determine the icon base name */
511 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
512 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
513 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
514 s=ico_name=ico_path;
515 while (*s!='\0') {
516 if (*s=='/' || *s=='\\') {
517 *s='\\';
518 ico_name=s;
519 } else {
520 *s=tolower(*s);
522 s++;
524 if (*ico_name=='\\') *ico_name++='\0';
525 s=strrchr(ico_name,'.');
526 if (s) *s='\0';
528 /* Compute the source-path hash */
529 crc=crc16(ico_path);
531 /* Try to treat the source file as an exe */
532 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
533 sprintf(xpm_path,"%s/%04x_%s.%d.xpm",iconsdir,crc,ico_name,index);
534 if (ExtractFromEXEDLL( path, index, xpm_path ))
535 goto end;
537 /* Must be something else, ignore the index in that case */
538 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
539 if (ExtractFromICO( path, xpm_path))
540 goto end;
541 if (!nodefault)
542 if (create_default_icon( xpm_path, ico_path ))
543 goto end;
545 HeapFree( GetProcessHeap(), 0, xpm_path );
546 xpm_path=NULL;
548 end:
549 HeapFree(GetProcessHeap(), 0, iconsdir);
550 HeapFree(GetProcessHeap(), 0, ico_path);
551 return xpm_path;
554 static BOOL DeferToRunOnce(LPWSTR link)
556 HKEY hkey;
557 LONG r, len;
558 static const WCHAR szRunOnce[] = {
559 'S','o','f','t','w','a','r','e','\\',
560 'M','i','c','r','o','s','o','f','t','\\',
561 'W','i','n','d','o','w','s','\\',
562 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
563 'R','u','n','O','n','c','e',0
565 static const WCHAR szFormat[] = { '%','s',' ','"','%','s','"',0 };
566 LPWSTR buffer;
567 WCHAR szExecutable[MAX_PATH];
569 WINE_TRACE( "Deferring icon creation to reboot.\n");
571 len = GetModuleFileNameW( 0, szExecutable, MAX_PATH );
572 if (!len || len >= MAX_PATH) return FALSE;
574 len = ( lstrlenW( link ) + lstrlenW( szExecutable ) + 4)*sizeof(WCHAR);
575 buffer = HeapAlloc( GetProcessHeap(), 0, len );
576 if( !buffer )
577 return FALSE;
579 wsprintfW( buffer, szFormat, szExecutable, link );
581 r = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szRunOnce, 0,
582 NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL);
583 if ( r == ERROR_SUCCESS )
585 r = RegSetValueExW(hkey, link, 0, REG_SZ,
586 (LPBYTE) buffer, (lstrlenW(buffer) + 1)*sizeof(WCHAR));
587 RegCloseKey(hkey);
589 HeapFree(GetProcessHeap(), 0, buffer);
591 return ! r;
594 /* This escapes \ in filenames */
595 static LPSTR escape(LPCWSTR arg)
597 LPSTR narg, x;
598 LPCWSTR esc;
599 int len = 0, n;
601 esc = arg;
602 while((esc = strchrW(esc, '\\')))
604 esc++;
605 len++;
608 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
609 narg = HeapAlloc(GetProcessHeap(), 0, len);
611 x = narg;
612 while (*arg)
614 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
615 x += n;
616 len -= n;
617 if (*arg == '\\')
618 *x++='\\'; /* escape \ */
619 arg++;
621 *x = 0;
622 return narg;
625 static int fork_and_wait( const char *linker, const char *link_name, const char *path,
626 int desktop, const char *args, const char *icon_name,
627 const char *workdir, const char *description )
629 int pos = 0;
630 const char *argv[20];
631 int retcode;
633 WINE_TRACE( "linker app='%s' link='%s' mode=%s "
634 "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
635 linker, link_name, desktop ? "desktop" : "menu",
636 path, args, icon_name, workdir, description );
638 argv[pos++] = linker ;
639 argv[pos++] = "--link";
640 argv[pos++] = link_name;
641 argv[pos++] = "--path";
642 argv[pos++] = path;
643 argv[pos++] = desktop ? "--desktop" : "--menu";
644 if (args && strlen(args))
646 argv[pos++] = "--args";
647 argv[pos++] = args;
649 if (icon_name)
651 argv[pos++] = "--icon";
652 argv[pos++] = icon_name;
654 if (workdir && strlen(workdir))
656 argv[pos++] = "--workdir";
657 argv[pos++] = workdir;
659 if (description && strlen(description))
661 argv[pos++] = "--descr";
662 argv[pos++] = description;
664 argv[pos] = NULL;
666 retcode=spawnvp( _P_WAIT, linker, argv );
667 if (retcode!=0)
668 WINE_ERR("%s returned %d\n",linker,retcode);
669 return retcode;
672 /* Return a heap-allocated copy of the unix format difference between the two
673 * Windows-format paths.
674 * locn is the owning location
675 * link is within locn
677 static char *relative_path( LPCWSTR link, LPCWSTR locn )
679 char *unix_locn, *unix_link;
680 char *relative = NULL;
682 unix_locn = wine_get_unix_file_name(locn);
683 unix_link = wine_get_unix_file_name(link);
684 if (unix_locn && unix_link)
686 size_t len_unix_locn, len_unix_link;
687 len_unix_locn = strlen (unix_locn);
688 len_unix_link = strlen (unix_link);
689 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
691 size_t len_rel;
692 char *p = strrchr (unix_link + len_unix_locn, '/');
693 p = strrchr (p, '.');
694 if (p)
696 *p = '\0';
697 len_unix_link = p - unix_link;
699 len_rel = len_unix_link - len_unix_locn;
700 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
701 if (relative)
703 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
707 if (!relative)
708 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
709 HeapFree(GetProcessHeap(), 0, unix_locn);
710 HeapFree(GetProcessHeap(), 0, unix_link);
711 return relative;
714 /***********************************************************************
716 * GetLinkLocation
718 * returns TRUE if successful
719 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
720 * *relative will contain the address of a heap-allocated copy of the portion
721 * of the filename that is within the specified location, in unix form
723 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
725 WCHAR filename[MAX_PATH], buffer[MAX_PATH];
726 DWORD len, i, r, filelen;
727 const DWORD locations[] = {
728 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
729 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
730 CSIDL_COMMON_STARTMENU };
732 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
733 filelen=GetFullPathNameW( linkfile, MAX_PATH, filename, NULL );
734 if (filelen==0 || filelen>MAX_PATH)
735 return FALSE;
737 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
739 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
741 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
742 continue;
744 len = lstrlenW(buffer);
745 if (len >= MAX_PATH)
746 continue; /* We've just trashed memory! Hopefully we are OK */
748 if (len > filelen || filename[len]!='\\')
749 continue;
750 /* do a lstrcmpinW */
751 filename[len] = 0;
752 r = lstrcmpiW( filename, buffer );
753 filename[len] = '\\';
754 if ( r )
755 continue;
757 /* return the remainder of the string and link type */
758 *loc = locations[i];
759 *relative = relative_path (filename, buffer);
760 return (*relative != NULL);
763 return FALSE;
766 /* gets the target path directly or through MSI */
767 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
768 LPWSTR szArgs, DWORD argsSize)
770 IShellLinkDataList *dl = NULL;
771 EXP_DARWIN_LINK *dar = NULL;
772 HRESULT hr;
774 szPath[0] = 0;
775 szArgs[0] = 0;
777 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
778 if (hr == S_OK && szPath[0])
780 IShellLinkW_GetArguments( sl, szArgs, argsSize );
781 return hr;
784 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
785 if (FAILED(hr))
786 return hr;
788 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
789 if (SUCCEEDED(hr))
791 WCHAR* szCmdline;
792 DWORD cmdSize;
794 cmdSize=0;
795 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
796 if (hr == ERROR_SUCCESS)
798 cmdSize++;
799 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
800 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
801 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
802 if (hr == ERROR_SUCCESS)
804 WCHAR *s, *d;
805 int bcount, in_quotes;
807 /* Extract the application path */
808 bcount=0;
809 in_quotes=0;
810 s=szCmdline;
811 d=szPath;
812 while (*s)
814 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
816 /* skip the remaining spaces */
817 do {
818 s++;
819 } while (*s==0x0009 || *s==0x0020);
820 break;
822 else if (*s==0x005c)
824 /* '\\' */
825 *d++=*s++;
826 bcount++;
828 else if (*s==0x0022)
830 /* '"' */
831 if ((bcount & 1)==0)
833 /* Preceded by an even number of '\', this is
834 * half that number of '\', plus a quote which
835 * we erase.
837 d-=bcount/2;
838 in_quotes=!in_quotes;
839 s++;
841 else
843 /* Preceded by an odd number of '\', this is
844 * half that number of '\' followed by a '"'
846 d=d-bcount/2-1;
847 *d++='"';
848 s++;
850 bcount=0;
852 else
854 /* a regular character */
855 *d++=*s++;
856 bcount=0;
858 if ((d-szPath) == pathSize)
860 /* Keep processing the path till we get to the
861 * arguments, but 'stand still'
863 d--;
866 /* Close the application path */
867 *d=0;
869 lstrcpynW(szArgs, s, argsSize);
871 HeapFree( GetProcessHeap(), 0, szCmdline );
873 LocalFree( dar );
876 IShellLinkDataList_Release( dl );
877 return hr;
880 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bAgain )
882 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
883 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
884 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
885 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
886 int iIconId = 0, r = -1;
887 DWORD csidl = -1;
889 if ( !link )
891 WINE_ERR("Link name is null\n");
892 return FALSE;
895 if( !GetLinkLocation( link, &csidl, &link_name ) )
897 WINE_WARN("Unknown link location '%s'. Ignoring.\n",wine_dbgstr_w(link));
898 return TRUE;
900 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
902 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
903 return TRUE;
905 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
907 szWorkDir[0] = 0;
908 IShellLinkW_GetWorkingDirectory( sl, szWorkDir, MAX_PATH );
909 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
911 szDescription[0] = 0;
912 IShellLinkW_GetDescription( sl, szDescription, INFOTIPSIZE );
913 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
915 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
916 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
917 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
919 szIconPath[0] = 0;
920 IShellLinkW_GetIconLocation( sl, szIconPath, MAX_PATH, &iIconId );
921 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
923 if( !szPath[0] )
925 LPITEMIDLIST pidl = NULL;
926 IShellLinkW_GetIDList( sl, &pidl );
927 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
928 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
931 /* extract the icon */
932 if( szIconPath[0] )
933 icon_name = extract_icon( szIconPath , iIconId );
934 else
935 icon_name = extract_icon( szPath, iIconId );
937 /* fail - try once again at reboot time */
938 if( !icon_name )
940 if (bAgain)
942 WINE_WARN("Unable to extract icon, deferring.\n");
943 goto cleanup;
945 WINE_ERR("failed to extract icon.\n");
948 /* check the path */
949 if( szPath[0] )
951 static const WCHAR exeW[] = {'.','e','x','e',0};
952 WCHAR *p;
954 /* check for .exe extension */
955 if (!(p = strrchrW( szPath, '.' ))) return FALSE;
956 if (strchrW( p, '\\' ) || strchrW( p, '/' )) return FALSE;
957 if (lstrcmpiW( p, exeW )) return FALSE;
959 /* convert app working dir */
960 if (szWorkDir[0])
961 work_dir = wine_get_unix_file_name( szWorkDir );
963 else
965 static const WCHAR startW[] = {
966 '\\','c','o','m','m','a','n','d',
967 '\\','s','t','a','r','t','.','e','x','e',0};
969 /* if there's no path... try run the link itself */
970 lstrcpynW(szArgs, link, MAX_PATH);
971 GetWindowsDirectoryW(szPath, MAX_PATH);
972 lstrcatW(szPath, startW);
975 /* escape the path and parameters */
976 escaped_path = escape(szPath);
977 escaped_args = escape(szArgs);
978 escaped_description = escape(szDescription);
980 r = fork_and_wait("wineshelllink", link_name, escaped_path,
981 in_desktop_dir(csidl), escaped_args, icon_name,
982 work_dir ? work_dir : "", escaped_description);
984 cleanup:
985 HeapFree( GetProcessHeap(), 0, icon_name );
986 HeapFree( GetProcessHeap(), 0, work_dir );
987 HeapFree( GetProcessHeap(), 0, link_name );
988 HeapFree( GetProcessHeap(), 0, escaped_args );
989 HeapFree( GetProcessHeap(), 0, escaped_path );
990 HeapFree( GetProcessHeap(), 0, escaped_description );
992 if (r)
994 WINE_ERR("failed to fork and exec wineshelllink\n" );
995 return FALSE;
998 return TRUE;
1002 static BOOL Process_Link( LPCWSTR linkname, BOOL bAgain )
1004 IShellLinkW *sl;
1005 IPersistFile *pf;
1006 HRESULT r;
1007 WCHAR fullname[MAX_PATH];
1008 DWORD len;
1010 WINE_TRACE("%s, again %d\n", wine_dbgstr_w(linkname), bAgain);
1012 if( !linkname[0] )
1014 WINE_ERR("link name missing\n");
1015 return 1;
1018 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1019 if (len==0 || len>MAX_PATH)
1021 WINE_ERR("couldn't get full path of link file\n");
1022 return 1;
1025 r = CoInitialize( NULL );
1026 if( FAILED( r ) )
1028 WINE_ERR("CoInitialize failed\n");
1029 return 1;
1032 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1033 &IID_IShellLinkW, (LPVOID *) &sl );
1034 if( FAILED( r ) )
1036 WINE_ERR("No IID_IShellLink\n");
1037 return 1;
1040 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1041 if( FAILED( r ) )
1043 WINE_ERR("No IID_IPersistFile\n");
1044 return 1;
1047 r = IPersistFile_Load( pf, fullname, STGM_READ );
1048 if( SUCCEEDED( r ) )
1050 /* If something fails (eg. Couldn't extract icon)
1051 * defer this menu entry to reboot via runonce
1053 if( ! InvokeShellLinker( sl, fullname, bAgain ) && bAgain )
1054 DeferToRunOnce( fullname );
1055 else
1056 WINE_TRACE("Success.\n");
1059 IPersistFile_Release( pf );
1060 IShellLinkW_Release( sl );
1062 CoUninitialize();
1064 return !r;
1068 static CHAR *next_token( LPSTR *p )
1070 LPSTR token = NULL, t = *p;
1072 if( !t )
1073 return NULL;
1075 while( t && !token )
1077 switch( *t )
1079 case ' ':
1080 t++;
1081 continue;
1082 case '"':
1083 /* unquote the token */
1084 token = ++t;
1085 t = strchr( token, '"' );
1086 if( t )
1087 *t++ = 0;
1088 break;
1089 case 0:
1090 t = NULL;
1091 break;
1092 default:
1093 token = t;
1094 t = strchr( token, ' ' );
1095 if( t )
1096 *t++ = 0;
1097 break;
1100 *p = t;
1101 return token;
1104 /***********************************************************************
1106 * WinMain
1108 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1110 LPSTR token = NULL, p;
1111 BOOL bAgain = FALSE;
1112 HANDLE hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1113 int ret = 0;
1115 /* running multiple instances of wineshelllink
1116 at the same time may be dangerous */
1117 if( WAIT_OBJECT_0 != WaitForSingleObject( hsem, INFINITE ) )
1119 CloseHandle(hsem);
1120 return FALSE;
1123 for( p = cmdline; p && *p; )
1125 token = next_token( &p );
1126 if( !token )
1127 break;
1128 if( !lstrcmpA( token, "-r" ) )
1129 bAgain = TRUE;
1130 else if( token[0] == '-' )
1132 WINE_ERR( "unknown option %s\n",token);
1134 else
1136 WCHAR link[MAX_PATH];
1138 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1139 if( !Process_Link( link, bAgain ) )
1141 WINE_ERR( "failed to build menu item for %s\n",token);
1142 ret = 1;
1147 ReleaseSemaphore( hsem, 1, NULL );
1148 CloseHandle( hsem );
1150 return ret;