winemenubuilder: Improve traces.
[wine/multimedia.git] / programs / winemenubuilder / winemenubuilder.c
blob50fd6154a9c3b03848baa3dec3cc100d60e32762
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")))
166 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
167 return FALSE;
170 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
171 comment = malloc(i);
172 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
174 nHeight = pIcon->bmiHeader.biHeight / 2;
175 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
176 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
177 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
178 + ((pIcon->bmiHeader.biWidth % 32) > 0));
179 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
180 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
181 : 1 << pIcon->bmiHeader.biBitCount;
182 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
183 pAND = pXOR + nHeight * nXORWidthBytes;
185 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
186 #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)
188 for (i = 0; i < nHeight; i++) {
189 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
190 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
192 aColorUsed[COLOR(j,i)] = TRUE;
193 nColorsUsed++;
198 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
199 goto error;
200 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
201 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
202 goto error;
204 for (i = 0; i < nColors; i++) {
205 if (aColorUsed[i])
206 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
207 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
208 goto error;
210 if (fprintf(fXPMFile, "\" c None\"") <= 0)
211 goto error;
213 for (i = 0; i < nHeight; i++)
215 if (fprintf(fXPMFile, ",\n\"") <= 0)
216 goto error;
217 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
219 if MASK(j,i)
221 if (fprintf(fXPMFile, " ") <= 0)
222 goto error;
224 else
225 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
226 goto error;
228 if (fprintf(fXPMFile, "\"") <= 0)
229 goto error;
231 if (fprintf(fXPMFile, "};\n") <= 0)
232 goto error;
234 #undef MASK
235 #undef COLOR
237 free(comment);
238 fclose(fXPMFile);
239 return TRUE;
241 error:
242 free(comment);
243 fclose(fXPMFile);
244 unlink( szXPMFileName );
245 return FALSE;
248 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
250 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
252 if (!sEnumRes->nIndex--)
254 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
255 return FALSE;
257 else
258 return TRUE;
261 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
263 HMODULE hModule;
264 HRSRC hResInfo;
265 LPCWSTR lpName = NULL;
266 HGLOBAL hResData;
267 GRPICONDIR *pIconDir;
268 BITMAPINFO *pIcon;
269 ENUMRESSTRUCT sEnumRes;
270 int nMax = 0;
271 int nMaxBits = 0;
272 int i;
273 BOOL ret = FALSE;
275 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
276 if (!hModule)
278 WINE_ERR("LoadLibraryExW (%s) failed, error %ld\n",
279 wine_dbgstr_w(szFileName), GetLastError());
280 return FALSE;
283 if (nIndex < 0)
285 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
286 WINE_TRACE("FindResourceW (%s) called, return %p, error %ld\n",
287 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
289 else
291 hResInfo=NULL;
292 sEnumRes.pResInfo = &hResInfo;
293 sEnumRes.nIndex = nIndex;
294 EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON, EnumResNameProc, (LONG_PTR)&sEnumRes);
297 if (hResInfo)
299 if ((hResData = LoadResource(hModule, hResInfo)))
301 if ((pIconDir = LockResource(hResData)))
303 for (i = 0; i < pIconDir->idCount; i++)
305 if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
307 nMaxBits = pIconDir->idEntries[i].wBitCount;
309 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
311 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
312 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
318 FreeResource(hResData);
321 else
323 WINE_ERR("ExtractFromEXEDLL failed, error %ld\n", GetLastError());
324 FreeLibrary(hModule);
325 return FALSE;
328 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
330 if ((hResData = LoadResource(hModule, hResInfo)))
332 if ((pIcon = LockResource(hResData)))
334 if(SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
335 ret = TRUE;
338 FreeResource(hResData);
342 FreeLibrary(hModule);
343 return ret;
346 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
348 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
349 !extract_icon16(szFileName, szXPMFileName)*/)
350 return FALSE;
351 return TRUE;
354 static int ExtractFromICO(LPCWSTR szFileName, const char *szXPMFileName)
356 FILE *fICOFile;
357 ICONDIR iconDir;
358 ICONDIRENTRY *pIconDirEntry;
359 int nMax = 0;
360 int nIndex = 0;
361 void *pIcon;
362 int i;
363 char *filename;
365 filename = wine_get_unix_file_name(szFileName);
366 if (!(fICOFile = fopen(filename, "r")))
368 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
369 goto error1;
372 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1)
373 goto error2;
374 if ((iconDir.idReserved != 0) || (iconDir.idType != 1))
375 goto error2;
377 if ((pIconDirEntry = malloc(iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
378 goto error2;
379 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
380 goto error3;
382 for (i = 0; i < iconDir.idCount; i++)
383 if ((pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) > nMax)
385 nIndex = i;
386 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
388 if ((pIcon = malloc(pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
389 goto error3;
390 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
391 goto error4;
392 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
393 goto error4;
395 if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
396 goto error4;
398 free(pIcon);
399 free(pIconDirEntry);
400 fclose(fICOFile);
401 HeapFree(GetProcessHeap(), 0, filename);
402 return 1;
404 error4:
405 free(pIcon);
406 error3:
407 free(pIconDirEntry);
408 error2:
409 fclose(fICOFile);
410 error1:
411 HeapFree(GetProcessHeap(), 0, filename);
412 return 0;
415 static BOOL create_default_icon( const char *filename, const char* comment )
417 FILE *fXPM;
418 unsigned int i;
420 if (!(fXPM = fopen(filename, "w"))) return FALSE;
421 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
422 goto error;
423 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
424 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
425 goto error;
427 if (fprintf( fXPM, "};\n" ) <=0)
428 goto error;
429 fclose( fXPM );
430 return TRUE;
431 error:
432 fclose( fXPM );
433 unlink( filename );
434 return FALSE;
438 static unsigned short crc16(const char* string)
440 unsigned short crc = 0;
441 int i, j, xor_poly;
443 for (i = 0; string[i] != 0; i++)
445 char c = string[i];
446 for (j = 0; j < 8; c >>= 1, j++)
448 xor_poly = (c ^ crc) & 1;
449 crc >>= 1;
450 if (xor_poly)
451 crc ^= 0xa001;
454 return crc;
457 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
458 static char *extract_icon( LPCWSTR path, int index)
460 int nodefault = 1;
461 unsigned short crc;
462 char *iconsdir, *ico_path, *ico_name, *xpm_path;
463 char* s;
464 HKEY hkey;
465 int n;
467 /* Where should we save the icon? */
468 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
469 iconsdir=NULL; /* Default is no icon */
470 /* @@ Wine registry key: HKCU\Software\Wine\WineMenuBuilder */
471 if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\WineMenuBuilder", &hkey ))
473 static const WCHAR IconsDirW[] = {'I','c','o','n','s','D','i','r',0};
474 LPWSTR iconsdirW;
475 DWORD size = 0;
477 if (!RegQueryValueExW(hkey, IconsDirW, 0, NULL, NULL, &size))
479 iconsdirW = HeapAlloc(GetProcessHeap(), 0, size);
480 RegQueryValueExW(hkey, IconsDirW, 0, NULL, (LPBYTE)iconsdirW, &size);
482 if (!(iconsdir = wine_get_unix_file_name(iconsdirW)))
484 int n = WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, NULL, 0, NULL, NULL);
485 iconsdir = HeapAlloc(GetProcessHeap(), 0, n);
486 WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, iconsdir, n, NULL, NULL);
488 HeapFree(GetProcessHeap(), 0, iconsdirW);
490 RegCloseKey( hkey );
493 if (!iconsdir)
495 WCHAR path[MAX_PATH];
496 if (GetTempPathW(MAX_PATH, path))
497 iconsdir = wine_get_unix_file_name(path);
498 if (!iconsdir)
500 WINE_TRACE("no IconsDir\n");
501 return NULL; /* No icon created */
505 if (!*iconsdir)
507 WINE_TRACE("icon generation disabled\n");
508 HeapFree(GetProcessHeap(), 0, iconsdir);
509 return NULL; /* No icon created */
512 /* If icon path begins with a '*' then this is a deferred call */
513 if (path[0] == '*')
515 path++;
516 nodefault = 0;
519 /* Determine the icon base name */
520 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
521 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
522 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
523 s=ico_name=ico_path;
524 while (*s!='\0') {
525 if (*s=='/' || *s=='\\') {
526 *s='\\';
527 ico_name=s;
528 } else {
529 *s=tolower(*s);
531 s++;
533 if (*ico_name=='\\') *ico_name++='\0';
534 s=strrchr(ico_name,'.');
535 if (s) *s='\0';
537 /* Compute the source-path hash */
538 crc=crc16(ico_path);
540 /* Try to treat the source file as an exe */
541 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
542 sprintf(xpm_path,"%s/%04x_%s.%d.xpm",iconsdir,crc,ico_name,index);
543 if (ExtractFromEXEDLL( path, index, xpm_path ))
544 goto end;
546 /* Must be something else, ignore the index in that case */
547 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
548 if (ExtractFromICO( path, xpm_path))
549 goto end;
550 if (!nodefault)
551 if (create_default_icon( xpm_path, ico_path ))
552 goto end;
554 HeapFree( GetProcessHeap(), 0, xpm_path );
555 xpm_path=NULL;
557 end:
558 HeapFree(GetProcessHeap(), 0, iconsdir);
559 HeapFree(GetProcessHeap(), 0, ico_path);
560 return xpm_path;
563 static BOOL DeferToRunOnce(LPWSTR link)
565 HKEY hkey;
566 LONG r, len;
567 static const WCHAR szRunOnce[] = {
568 'S','o','f','t','w','a','r','e','\\',
569 'M','i','c','r','o','s','o','f','t','\\',
570 'W','i','n','d','o','w','s','\\',
571 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
572 'R','u','n','O','n','c','e',0
574 static const WCHAR szFormat[] = { '%','s',' ','"','%','s','"',0 };
575 LPWSTR buffer;
576 WCHAR szExecutable[MAX_PATH];
578 WINE_TRACE( "Deferring icon creation to reboot.\n");
580 len = GetModuleFileNameW( 0, szExecutable, MAX_PATH );
581 if (!len || len >= MAX_PATH) return FALSE;
583 len = ( lstrlenW( link ) + lstrlenW( szExecutable ) + 4)*sizeof(WCHAR);
584 buffer = HeapAlloc( GetProcessHeap(), 0, len );
585 if( !buffer )
586 return FALSE;
588 wsprintfW( buffer, szFormat, szExecutable, link );
590 r = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szRunOnce, 0,
591 NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL);
592 if ( r == ERROR_SUCCESS )
594 r = RegSetValueExW(hkey, link, 0, REG_SZ,
595 (LPBYTE) buffer, (lstrlenW(buffer) + 1)*sizeof(WCHAR));
596 RegCloseKey(hkey);
598 HeapFree(GetProcessHeap(), 0, buffer);
600 return ! r;
603 /* This escapes \ in filenames */
604 static LPSTR escape(LPCWSTR arg)
606 LPSTR narg, x;
607 LPCWSTR esc;
608 int len = 0, n;
610 esc = arg;
611 while((esc = strchrW(esc, '\\')))
613 esc++;
614 len++;
617 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
618 narg = HeapAlloc(GetProcessHeap(), 0, len);
620 x = narg;
621 while (*arg)
623 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
624 x += n;
625 len -= n;
626 if (*arg == '\\')
627 *x++='\\'; /* escape \ */
628 arg++;
630 *x = 0;
631 return narg;
634 static int fork_and_wait( const char *linker, const char *link_name, const char *path,
635 int desktop, const char *args, const char *icon_name,
636 const char *workdir, const char *description )
638 int pos = 0;
639 const char *argv[20];
640 int retcode;
642 WINE_TRACE( "linker app='%s' link='%s' mode=%s "
643 "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
644 linker, link_name, desktop ? "desktop" : "menu",
645 path, args, icon_name, workdir, description );
647 argv[pos++] = linker ;
648 argv[pos++] = "--link";
649 argv[pos++] = link_name;
650 argv[pos++] = "--path";
651 argv[pos++] = path;
652 argv[pos++] = desktop ? "--desktop" : "--menu";
653 if (args && strlen(args))
655 argv[pos++] = "--args";
656 argv[pos++] = args;
658 if (icon_name)
660 argv[pos++] = "--icon";
661 argv[pos++] = icon_name;
663 if (workdir && strlen(workdir))
665 argv[pos++] = "--workdir";
666 argv[pos++] = workdir;
668 if (description && strlen(description))
670 argv[pos++] = "--descr";
671 argv[pos++] = description;
673 argv[pos] = NULL;
675 retcode=spawnvp( _P_WAIT, linker, argv );
676 if (retcode!=0)
677 WINE_ERR("%s returned %d\n",linker,retcode);
678 return retcode;
681 /* Return a heap-allocated copy of the unix format difference between the two
682 * Windows-format paths.
683 * locn is the owning location
684 * link is within locn
686 static char *relative_path( LPCWSTR link, LPCWSTR locn )
688 char *unix_locn, *unix_link;
689 char *relative = NULL;
691 unix_locn = wine_get_unix_file_name(locn);
692 unix_link = wine_get_unix_file_name(link);
693 if (unix_locn && unix_link)
695 size_t len_unix_locn, len_unix_link;
696 len_unix_locn = strlen (unix_locn);
697 len_unix_link = strlen (unix_link);
698 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
700 size_t len_rel;
701 char *p = strrchr (unix_link + len_unix_locn, '/');
702 p = strrchr (p, '.');
703 if (p)
705 *p = '\0';
706 len_unix_link = p - unix_link;
708 len_rel = len_unix_link - len_unix_locn;
709 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
710 if (relative)
712 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
716 if (!relative)
717 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
718 HeapFree(GetProcessHeap(), 0, unix_locn);
719 HeapFree(GetProcessHeap(), 0, unix_link);
720 return relative;
723 /***********************************************************************
725 * GetLinkLocation
727 * returns TRUE if successful
728 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
729 * *relative will contain the address of a heap-allocated copy of the portion
730 * of the filename that is within the specified location, in unix form
732 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
734 WCHAR filename[MAX_PATH], buffer[MAX_PATH];
735 DWORD len, i, r, filelen;
736 const DWORD locations[] = {
737 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
738 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
739 CSIDL_COMMON_STARTMENU };
741 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
742 filelen=GetFullPathNameW( linkfile, MAX_PATH, filename, NULL );
743 if (filelen==0 || filelen>MAX_PATH)
744 return FALSE;
746 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
748 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
750 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
751 continue;
753 len = lstrlenW(buffer);
754 if (len >= MAX_PATH)
755 continue; /* We've just trashed memory! Hopefully we are OK */
757 if (len > filelen || filename[len]!='\\')
758 continue;
759 /* do a lstrcmpinW */
760 filename[len] = 0;
761 r = lstrcmpiW( filename, buffer );
762 filename[len] = '\\';
763 if ( r )
764 continue;
766 /* return the remainder of the string and link type */
767 *loc = locations[i];
768 *relative = relative_path (filename, buffer);
769 return (*relative != NULL);
772 return FALSE;
775 /* gets the target path directly or through MSI */
776 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
777 LPWSTR szArgs, DWORD argsSize)
779 IShellLinkDataList *dl = NULL;
780 EXP_DARWIN_LINK *dar = NULL;
781 HRESULT hr;
783 szPath[0] = 0;
784 szArgs[0] = 0;
786 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
787 if (hr == S_OK && szPath[0])
789 IShellLinkW_GetArguments( sl, szArgs, argsSize );
790 return hr;
793 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
794 if (FAILED(hr))
795 return hr;
797 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
798 if (SUCCEEDED(hr))
800 WCHAR* szCmdline;
801 DWORD cmdSize;
803 cmdSize=0;
804 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
805 if (hr == ERROR_SUCCESS)
807 cmdSize++;
808 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
809 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
810 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
811 if (hr == ERROR_SUCCESS)
813 WCHAR *s, *d;
814 int bcount, in_quotes;
816 /* Extract the application path */
817 bcount=0;
818 in_quotes=0;
819 s=szCmdline;
820 d=szPath;
821 while (*s)
823 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
825 /* skip the remaining spaces */
826 do {
827 s++;
828 } while (*s==0x0009 || *s==0x0020);
829 break;
831 else if (*s==0x005c)
833 /* '\\' */
834 *d++=*s++;
835 bcount++;
837 else if (*s==0x0022)
839 /* '"' */
840 if ((bcount & 1)==0)
842 /* Preceded by an even number of '\', this is
843 * half that number of '\', plus a quote which
844 * we erase.
846 d-=bcount/2;
847 in_quotes=!in_quotes;
848 s++;
850 else
852 /* Preceded by an odd number of '\', this is
853 * half that number of '\' followed by a '"'
855 d=d-bcount/2-1;
856 *d++='"';
857 s++;
859 bcount=0;
861 else
863 /* a regular character */
864 *d++=*s++;
865 bcount=0;
867 if ((d-szPath) == pathSize)
869 /* Keep processing the path till we get to the
870 * arguments, but 'stand still'
872 d--;
875 /* Close the application path */
876 *d=0;
878 lstrcpynW(szArgs, s, argsSize);
880 HeapFree( GetProcessHeap(), 0, szCmdline );
882 LocalFree( dar );
885 IShellLinkDataList_Release( dl );
886 return hr;
889 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bAgain )
891 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
892 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
893 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
894 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
895 int iIconId = 0, r = -1;
896 DWORD csidl = -1;
898 if ( !link )
900 WINE_ERR("Link name is null\n");
901 return FALSE;
904 if( !GetLinkLocation( link, &csidl, &link_name ) )
906 WINE_WARN("Unknown link location '%s'. Ignoring.\n",wine_dbgstr_w(link));
907 return TRUE;
909 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
911 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
912 return TRUE;
914 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
916 szWorkDir[0] = 0;
917 IShellLinkW_GetWorkingDirectory( sl, szWorkDir, MAX_PATH );
918 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
920 szDescription[0] = 0;
921 IShellLinkW_GetDescription( sl, szDescription, INFOTIPSIZE );
922 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
924 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
925 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
926 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
928 szIconPath[0] = 0;
929 IShellLinkW_GetIconLocation( sl, szIconPath, MAX_PATH, &iIconId );
930 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
932 if( !szPath[0] )
934 LPITEMIDLIST pidl = NULL;
935 IShellLinkW_GetIDList( sl, &pidl );
936 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
937 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
940 /* extract the icon */
941 if( szIconPath[0] )
942 icon_name = extract_icon( szIconPath , iIconId );
943 else
944 icon_name = extract_icon( szPath, iIconId );
946 /* fail - try once again at reboot time */
947 if( !icon_name )
949 if (bAgain)
951 WINE_WARN("Unable to extract icon, deferring.\n");
952 goto cleanup;
954 WINE_ERR("failed to extract icon.\n");
957 /* check the path */
958 if( szPath[0] )
960 static const WCHAR exeW[] = {'.','e','x','e',0};
961 WCHAR *p;
963 /* check for .exe extension */
964 if (!(p = strrchrW( szPath, '.' ))) return FALSE;
965 if (strchrW( p, '\\' ) || strchrW( p, '/' )) return FALSE;
966 if (lstrcmpiW( p, exeW )) return FALSE;
968 /* convert app working dir */
969 if (szWorkDir[0])
970 work_dir = wine_get_unix_file_name( szWorkDir );
972 else
974 static const WCHAR startW[] = {
975 '\\','c','o','m','m','a','n','d',
976 '\\','s','t','a','r','t','.','e','x','e',0};
978 /* if there's no path... try run the link itself */
979 lstrcpynW(szArgs, link, MAX_PATH);
980 GetWindowsDirectoryW(szPath, MAX_PATH);
981 lstrcatW(szPath, startW);
984 /* escape the path and parameters */
985 escaped_path = escape(szPath);
986 escaped_args = escape(szArgs);
987 escaped_description = escape(szDescription);
989 r = fork_and_wait("wineshelllink", link_name, escaped_path,
990 in_desktop_dir(csidl), escaped_args, icon_name,
991 work_dir ? work_dir : "", escaped_description);
993 cleanup:
994 HeapFree( GetProcessHeap(), 0, icon_name );
995 HeapFree( GetProcessHeap(), 0, work_dir );
996 HeapFree( GetProcessHeap(), 0, link_name );
997 HeapFree( GetProcessHeap(), 0, escaped_args );
998 HeapFree( GetProcessHeap(), 0, escaped_path );
999 HeapFree( GetProcessHeap(), 0, escaped_description );
1001 if (r)
1003 WINE_ERR("failed to fork and exec wineshelllink\n" );
1004 return FALSE;
1007 return TRUE;
1011 static BOOL Process_Link( LPCWSTR linkname, BOOL bAgain )
1013 IShellLinkW *sl;
1014 IPersistFile *pf;
1015 HRESULT r;
1016 WCHAR fullname[MAX_PATH];
1017 DWORD len;
1019 WINE_TRACE("%s, again %d\n", wine_dbgstr_w(linkname), bAgain);
1021 if( !linkname[0] )
1023 WINE_ERR("link name missing\n");
1024 return 1;
1027 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1028 if (len==0 || len>MAX_PATH)
1030 WINE_ERR("couldn't get full path of link file\n");
1031 return 1;
1034 r = CoInitialize( NULL );
1035 if( FAILED( r ) )
1037 WINE_ERR("CoInitialize failed\n");
1038 return 1;
1041 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1042 &IID_IShellLinkW, (LPVOID *) &sl );
1043 if( FAILED( r ) )
1045 WINE_ERR("No IID_IShellLink\n");
1046 return 1;
1049 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1050 if( FAILED( r ) )
1052 WINE_ERR("No IID_IPersistFile\n");
1053 return 1;
1056 r = IPersistFile_Load( pf, fullname, STGM_READ );
1057 if( SUCCEEDED( r ) )
1059 /* If something fails (eg. Couldn't extract icon)
1060 * defer this menu entry to reboot via runonce
1062 if( ! InvokeShellLinker( sl, fullname, bAgain ) && bAgain )
1063 DeferToRunOnce( fullname );
1064 else
1065 WINE_TRACE("Success.\n");
1068 IPersistFile_Release( pf );
1069 IShellLinkW_Release( sl );
1071 CoUninitialize();
1073 return !r;
1077 static CHAR *next_token( LPSTR *p )
1079 LPSTR token = NULL, t = *p;
1081 if( !t )
1082 return NULL;
1084 while( t && !token )
1086 switch( *t )
1088 case ' ':
1089 t++;
1090 continue;
1091 case '"':
1092 /* unquote the token */
1093 token = ++t;
1094 t = strchr( token, '"' );
1095 if( t )
1096 *t++ = 0;
1097 break;
1098 case 0:
1099 t = NULL;
1100 break;
1101 default:
1102 token = t;
1103 t = strchr( token, ' ' );
1104 if( t )
1105 *t++ = 0;
1106 break;
1109 *p = t;
1110 return token;
1113 /***********************************************************************
1115 * WinMain
1117 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1119 LPSTR token = NULL, p;
1120 BOOL bAgain = FALSE;
1121 HANDLE hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1122 int ret = 0;
1124 /* running multiple instances of wineshelllink
1125 at the same time may be dangerous */
1126 if( WAIT_OBJECT_0 != WaitForSingleObject( hsem, INFINITE ) )
1128 CloseHandle(hsem);
1129 return FALSE;
1132 for( p = cmdline; p && *p; )
1134 token = next_token( &p );
1135 if( !token )
1136 break;
1137 if( !lstrcmpA( token, "-r" ) )
1138 bAgain = TRUE;
1139 else if( token[0] == '-' )
1141 WINE_ERR( "unknown option %s\n",token);
1143 else
1145 WCHAR link[MAX_PATH];
1147 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1148 if( !Process_Link( link, bAgain ) )
1150 WINE_ERR( "failed to build menu item for %s\n",token);
1151 ret = 1;
1156 ReleaseSemaphore( hsem, 1, NULL );
1157 CloseHandle( hsem );
1159 return ret;