ws2_32: Rewrite WSAGetOverlappedResult for the new async I/O behavior.
[wine/testsucceed.git] / programs / winemenubuilder / winemenubuilder.c
blob7c537cab4e704f184275c6a6d3b298c4e9be0fce
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 [ -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)))
163 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
164 return FALSE;
167 if (!(fXPMFile = fopen(szXPMFileName, "w")))
169 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
170 return FALSE;
173 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
174 comment = HeapAlloc(GetProcessHeap(), 0, i);
175 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
177 nHeight = pIcon->bmiHeader.biHeight / 2;
178 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
179 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
180 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
181 + ((pIcon->bmiHeader.biWidth % 32) > 0));
182 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
183 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
184 : 1 << pIcon->bmiHeader.biBitCount;
185 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
186 pAND = pXOR + nHeight * nXORWidthBytes;
188 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
189 #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)
191 for (i = 0; i < nHeight; i++) {
192 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
193 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
195 aColorUsed[COLOR(j,i)] = TRUE;
196 nColorsUsed++;
201 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
202 goto error;
203 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
204 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
205 goto error;
207 for (i = 0; i < nColors; i++) {
208 if (aColorUsed[i])
209 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
210 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
211 goto error;
213 if (fprintf(fXPMFile, "\" c None\"") <= 0)
214 goto error;
216 for (i = 0; i < nHeight; i++)
218 if (fprintf(fXPMFile, ",\n\"") <= 0)
219 goto error;
220 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
222 if MASK(j,i)
224 if (fprintf(fXPMFile, " ") <= 0)
225 goto error;
227 else
228 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
229 goto error;
231 if (fprintf(fXPMFile, "\"") <= 0)
232 goto error;
234 if (fprintf(fXPMFile, "};\n") <= 0)
235 goto error;
237 #undef MASK
238 #undef COLOR
240 HeapFree(GetProcessHeap(), 0, comment);
241 fclose(fXPMFile);
242 return TRUE;
244 error:
245 HeapFree(GetProcessHeap(), 0, comment);
246 fclose(fXPMFile);
247 unlink( szXPMFileName );
248 return FALSE;
251 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
253 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
255 if (!sEnumRes->nIndex--)
257 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
258 return FALSE;
260 else
261 return TRUE;
264 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
266 HMODULE hModule;
267 HRSRC hResInfo;
268 LPCWSTR lpName = NULL;
269 HGLOBAL hResData;
270 GRPICONDIR *pIconDir;
271 BITMAPINFO *pIcon;
272 ENUMRESSTRUCT sEnumRes;
273 int nMax = 0;
274 int nMaxBits = 0;
275 int i;
276 BOOL ret = FALSE;
278 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
279 if (!hModule)
281 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
282 wine_dbgstr_w(szFileName), GetLastError());
283 return FALSE;
286 if (nIndex < 0)
288 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
289 WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
290 wine_dbgstr_w(szFileName), hResInfo, GetLastError());
292 else
294 hResInfo=NULL;
295 sEnumRes.pResInfo = &hResInfo;
296 sEnumRes.nIndex = nIndex;
297 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
298 EnumResNameProc, (LONG_PTR)&sEnumRes))
300 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
304 if (hResInfo)
306 if ((hResData = LoadResource(hModule, hResInfo)))
308 if ((pIconDir = LockResource(hResData)))
310 for (i = 0; i < pIconDir->idCount; i++)
312 if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
314 nMaxBits = pIconDir->idEntries[i].wBitCount;
316 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
318 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
319 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
325 FreeResource(hResData);
328 else
330 WINE_WARN("found no icon\n");
331 FreeLibrary(hModule);
332 return FALSE;
335 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
337 if ((hResData = LoadResource(hModule, hResInfo)))
339 if ((pIcon = LockResource(hResData)))
341 if(SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
342 ret = TRUE;
345 FreeResource(hResData);
349 FreeLibrary(hModule);
350 return ret;
353 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
355 if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
356 !extract_icon16(szFileName, szXPMFileName)*/)
357 return FALSE;
358 return TRUE;
361 static int ExtractFromICO(LPCWSTR szFileName, const char *szXPMFileName)
363 FILE *fICOFile;
364 ICONDIR iconDir;
365 ICONDIRENTRY *pIconDirEntry;
366 int nMax = 0, nMaxBits = 0;
367 int nIndex = 0;
368 void *pIcon;
369 int i;
370 char *filename;
372 filename = wine_get_unix_file_name(szFileName);
373 if (!(fICOFile = fopen(filename, "r")))
375 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
376 goto error1;
379 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
380 (iconDir.idReserved != 0) || (iconDir.idType != 1))
382 WINE_WARN("Invalid ico file format\n");
383 goto error2;
386 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
387 goto error2;
388 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
389 goto error3;
391 for (i = 0; i < iconDir.idCount; i++)
392 if (pIconDirEntry[i].wBitCount <= 8 && pIconDirEntry[i].wBitCount >= nMaxBits &&
393 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
395 nIndex = i;
396 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
397 nMaxBits = pIconDirEntry[i].wBitCount;
399 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
400 goto error3;
401 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
402 goto error4;
403 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
404 goto error4;
406 if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
407 goto error4;
409 HeapFree(GetProcessHeap(), 0, pIcon);
410 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
411 fclose(fICOFile);
412 HeapFree(GetProcessHeap(), 0, filename);
413 return 1;
415 error4:
416 HeapFree(GetProcessHeap(), 0, pIcon);
417 error3:
418 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
419 error2:
420 fclose(fICOFile);
421 error1:
422 HeapFree(GetProcessHeap(), 0, filename);
423 return 0;
426 static BOOL create_default_icon( const char *filename, const char* comment )
428 FILE *fXPM;
429 unsigned int i;
431 if (!(fXPM = fopen(filename, "w"))) return FALSE;
432 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
433 goto error;
434 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
435 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
436 goto error;
438 if (fprintf( fXPM, "};\n" ) <=0)
439 goto error;
440 fclose( fXPM );
441 return TRUE;
442 error:
443 fclose( fXPM );
444 unlink( filename );
445 return FALSE;
449 static unsigned short crc16(const char* string)
451 unsigned short crc = 0;
452 int i, j, xor_poly;
454 for (i = 0; string[i] != 0; i++)
456 char c = string[i];
457 for (j = 0; j < 8; c >>= 1, j++)
459 xor_poly = (c ^ crc) & 1;
460 crc >>= 1;
461 if (xor_poly)
462 crc ^= 0xa001;
465 return crc;
468 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
469 static char *extract_icon( LPCWSTR path, int index)
471 int nodefault = 1;
472 unsigned short crc;
473 char *iconsdir, *ico_path, *ico_name, *xpm_path;
474 char* s;
475 HKEY hkey;
476 int n;
478 /* Where should we save the icon? */
479 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
480 iconsdir=NULL; /* Default is no icon */
481 /* @@ Wine registry key: HKCU\Software\Wine\WineMenuBuilder */
482 if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\WineMenuBuilder", &hkey ))
484 static const WCHAR IconsDirW[] = {'I','c','o','n','s','D','i','r',0};
485 LPWSTR iconsdirW;
486 DWORD size = 0;
488 if (!RegQueryValueExW(hkey, IconsDirW, 0, NULL, NULL, &size))
490 iconsdirW = HeapAlloc(GetProcessHeap(), 0, size);
491 RegQueryValueExW(hkey, IconsDirW, 0, NULL, (LPBYTE)iconsdirW, &size);
493 if (!(iconsdir = wine_get_unix_file_name(iconsdirW)))
495 int n = WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, NULL, 0, NULL, NULL);
496 iconsdir = HeapAlloc(GetProcessHeap(), 0, n);
497 WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, iconsdir, n, NULL, NULL);
499 HeapFree(GetProcessHeap(), 0, iconsdirW);
501 RegCloseKey( hkey );
504 if (!iconsdir)
506 WCHAR path[MAX_PATH];
507 if (GetTempPathW(MAX_PATH, path))
508 iconsdir = wine_get_unix_file_name(path);
509 if (!iconsdir)
511 WINE_TRACE("no IconsDir\n");
512 return NULL; /* No icon created */
516 if (!*iconsdir)
518 WINE_TRACE("icon generation disabled\n");
519 HeapFree(GetProcessHeap(), 0, iconsdir);
520 return NULL; /* No icon created */
523 /* If icon path begins with a '*' then this is a deferred call */
524 if (path[0] == '*')
526 path++;
527 nodefault = 0;
530 /* Determine the icon base name */
531 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
532 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
533 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
534 s=ico_name=ico_path;
535 while (*s!='\0') {
536 if (*s=='/' || *s=='\\') {
537 *s='\\';
538 ico_name=s;
539 } else {
540 *s=tolower(*s);
542 s++;
544 if (*ico_name=='\\') *ico_name++='\0';
545 s=strrchr(ico_name,'.');
546 if (s) *s='\0';
548 /* Compute the source-path hash */
549 crc=crc16(ico_path);
551 /* Try to treat the source file as an exe */
552 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
553 sprintf(xpm_path,"%s/%04x_%s.%d.xpm",iconsdir,crc,ico_name,index);
554 if (ExtractFromEXEDLL( path, index, xpm_path ))
555 goto end;
557 /* Must be something else, ignore the index in that case */
558 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
559 if (ExtractFromICO( path, xpm_path))
560 goto end;
561 if (!nodefault)
562 if (create_default_icon( xpm_path, ico_path ))
563 goto end;
565 HeapFree( GetProcessHeap(), 0, xpm_path );
566 xpm_path=NULL;
568 end:
569 HeapFree(GetProcessHeap(), 0, iconsdir);
570 HeapFree(GetProcessHeap(), 0, ico_path);
571 return xpm_path;
574 static BOOL DeferToRunOnce(LPWSTR link)
576 HKEY hkey;
577 LONG r, len;
578 static const WCHAR szRunOnce[] = {
579 'S','o','f','t','w','a','r','e','\\',
580 'M','i','c','r','o','s','o','f','t','\\',
581 'W','i','n','d','o','w','s','\\',
582 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
583 'R','u','n','O','n','c','e',0
585 static const WCHAR szFormat[] = { '%','s',' ','"','%','s','"',0 };
586 LPWSTR buffer;
587 WCHAR szExecutable[MAX_PATH];
589 WINE_TRACE( "Deferring icon creation to reboot.\n");
591 len = GetModuleFileNameW( 0, szExecutable, MAX_PATH );
592 if (!len || len >= MAX_PATH) return FALSE;
594 len = ( lstrlenW( link ) + lstrlenW( szExecutable ) + 4)*sizeof(WCHAR);
595 buffer = HeapAlloc( GetProcessHeap(), 0, len );
596 if( !buffer )
597 return FALSE;
599 wsprintfW( buffer, szFormat, szExecutable, link );
601 r = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szRunOnce, 0,
602 NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL);
603 if ( r == ERROR_SUCCESS )
605 r = RegSetValueExW(hkey, link, 0, REG_SZ,
606 (LPBYTE) buffer, (lstrlenW(buffer) + 1)*sizeof(WCHAR));
607 RegCloseKey(hkey);
609 HeapFree(GetProcessHeap(), 0, buffer);
611 return ! r;
614 /* This escapes \ in filenames */
615 static LPSTR escape(LPCWSTR arg)
617 LPSTR narg, x;
618 LPCWSTR esc;
619 int len = 0, n;
621 esc = arg;
622 while((esc = strchrW(esc, '\\')))
624 esc++;
625 len++;
628 len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
629 narg = HeapAlloc(GetProcessHeap(), 0, len);
631 x = narg;
632 while (*arg)
634 n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
635 x += n;
636 len -= n;
637 if (*arg == '\\')
638 *x++='\\'; /* escape \ */
639 arg++;
641 *x = 0;
642 return narg;
645 static int fork_and_wait( const char *linker, const char *link_name, const char *path,
646 int desktop, const char *args, const char *icon_name,
647 const char *workdir, const char *description )
649 int pos = 0;
650 const char *argv[20];
651 int retcode;
653 WINE_TRACE( "linker app='%s' link='%s' mode=%s "
654 "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
655 linker, link_name, desktop ? "desktop" : "menu",
656 path, args, icon_name, workdir, description );
658 argv[pos++] = linker ;
659 argv[pos++] = "--link";
660 argv[pos++] = link_name;
661 argv[pos++] = "--path";
662 argv[pos++] = path;
663 argv[pos++] = desktop ? "--desktop" : "--menu";
664 if (args && strlen(args))
666 argv[pos++] = "--args";
667 argv[pos++] = args;
669 if (icon_name)
671 argv[pos++] = "--icon";
672 argv[pos++] = icon_name;
674 if (workdir && strlen(workdir))
676 argv[pos++] = "--workdir";
677 argv[pos++] = workdir;
679 if (description && strlen(description))
681 argv[pos++] = "--descr";
682 argv[pos++] = description;
684 argv[pos] = NULL;
686 retcode=spawnvp( _P_WAIT, linker, argv );
687 if (retcode!=0)
688 WINE_ERR("%s returned %d\n",linker,retcode);
689 return retcode;
692 /* Return a heap-allocated copy of the unix format difference between the two
693 * Windows-format paths.
694 * locn is the owning location
695 * link is within locn
697 static char *relative_path( LPCWSTR link, LPCWSTR locn )
699 char *unix_locn, *unix_link;
700 char *relative = NULL;
702 unix_locn = wine_get_unix_file_name(locn);
703 unix_link = wine_get_unix_file_name(link);
704 if (unix_locn && unix_link)
706 size_t len_unix_locn, len_unix_link;
707 len_unix_locn = strlen (unix_locn);
708 len_unix_link = strlen (unix_link);
709 if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
711 size_t len_rel;
712 char *p = strrchr (unix_link + len_unix_locn, '/');
713 p = strrchr (p, '.');
714 if (p)
716 *p = '\0';
717 len_unix_link = p - unix_link;
719 len_rel = len_unix_link - len_unix_locn;
720 relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
721 if (relative)
723 memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
727 if (!relative)
728 WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
729 HeapFree(GetProcessHeap(), 0, unix_locn);
730 HeapFree(GetProcessHeap(), 0, unix_link);
731 return relative;
734 /***********************************************************************
736 * GetLinkLocation
738 * returns TRUE if successful
739 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
740 * *relative will contain the address of a heap-allocated copy of the portion
741 * of the filename that is within the specified location, in unix form
743 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
745 WCHAR filename[MAX_PATH], buffer[MAX_PATH];
746 DWORD len, i, r, filelen;
747 const DWORD locations[] = {
748 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
749 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
750 CSIDL_COMMON_STARTMENU };
752 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
753 filelen=GetFullPathNameW( linkfile, MAX_PATH, filename, NULL );
754 if (filelen==0 || filelen>MAX_PATH)
755 return FALSE;
757 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
759 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
761 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
762 continue;
764 len = lstrlenW(buffer);
765 if (len >= MAX_PATH)
766 continue; /* We've just trashed memory! Hopefully we are OK */
768 if (len > filelen || filename[len]!='\\')
769 continue;
770 /* do a lstrcmpinW */
771 filename[len] = 0;
772 r = lstrcmpiW( filename, buffer );
773 filename[len] = '\\';
774 if ( r )
775 continue;
777 /* return the remainder of the string and link type */
778 *loc = locations[i];
779 *relative = relative_path (filename, buffer);
780 return (*relative != NULL);
783 return FALSE;
786 /* gets the target path directly or through MSI */
787 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
788 LPWSTR szArgs, DWORD argsSize)
790 IShellLinkDataList *dl = NULL;
791 EXP_DARWIN_LINK *dar = NULL;
792 HRESULT hr;
794 szPath[0] = 0;
795 szArgs[0] = 0;
797 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
798 if (hr == S_OK && szPath[0])
800 IShellLinkW_GetArguments( sl, szArgs, argsSize );
801 return hr;
804 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
805 if (FAILED(hr))
806 return hr;
808 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
809 if (SUCCEEDED(hr))
811 WCHAR* szCmdline;
812 DWORD cmdSize;
814 cmdSize=0;
815 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
816 if (hr == ERROR_SUCCESS)
818 cmdSize++;
819 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
820 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
821 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
822 if (hr == ERROR_SUCCESS)
824 WCHAR *s, *d;
825 int bcount, in_quotes;
827 /* Extract the application path */
828 bcount=0;
829 in_quotes=0;
830 s=szCmdline;
831 d=szPath;
832 while (*s)
834 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
836 /* skip the remaining spaces */
837 do {
838 s++;
839 } while (*s==0x0009 || *s==0x0020);
840 break;
842 else if (*s==0x005c)
844 /* '\\' */
845 *d++=*s++;
846 bcount++;
848 else if (*s==0x0022)
850 /* '"' */
851 if ((bcount & 1)==0)
853 /* Preceded by an even number of '\', this is
854 * half that number of '\', plus a quote which
855 * we erase.
857 d-=bcount/2;
858 in_quotes=!in_quotes;
859 s++;
861 else
863 /* Preceded by an odd number of '\', this is
864 * half that number of '\' followed by a '"'
866 d=d-bcount/2-1;
867 *d++='"';
868 s++;
870 bcount=0;
872 else
874 /* a regular character */
875 *d++=*s++;
876 bcount=0;
878 if ((d-szPath) == pathSize)
880 /* Keep processing the path till we get to the
881 * arguments, but 'stand still'
883 d--;
886 /* Close the application path */
887 *d=0;
889 lstrcpynW(szArgs, s, argsSize);
891 HeapFree( GetProcessHeap(), 0, szCmdline );
893 LocalFree( dar );
896 IShellLinkDataList_Release( dl );
897 return hr;
900 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bAgain )
902 static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
903 '\\','s','t','a','r','t','.','e','x','e',0};
904 char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
905 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
906 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
907 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
908 int iIconId = 0, r = -1;
909 DWORD csidl = -1;
911 if ( !link )
913 WINE_ERR("Link name is null\n");
914 return FALSE;
917 if( !GetLinkLocation( link, &csidl, &link_name ) )
919 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
920 return TRUE;
922 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
924 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
925 return TRUE;
927 WINE_TRACE("Link : %s\n", wine_dbgstr_a(link_name));
929 szWorkDir[0] = 0;
930 IShellLinkW_GetWorkingDirectory( sl, szWorkDir, MAX_PATH );
931 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
933 szDescription[0] = 0;
934 IShellLinkW_GetDescription( sl, szDescription, INFOTIPSIZE );
935 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
937 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
938 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
939 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
941 szIconPath[0] = 0;
942 IShellLinkW_GetIconLocation( sl, szIconPath, MAX_PATH, &iIconId );
943 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
945 if( !szPath[0] )
947 LPITEMIDLIST pidl = NULL;
948 IShellLinkW_GetIDList( sl, &pidl );
949 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
950 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
953 /* extract the icon */
954 if( szIconPath[0] )
955 icon_name = extract_icon( szIconPath , iIconId );
956 else
957 icon_name = extract_icon( szPath, iIconId );
959 /* fail - try once again at reboot time */
960 if( !icon_name )
962 if (bAgain)
964 WINE_WARN("Unable to extract icon, deferring.\n");
965 goto cleanup;
967 WINE_ERR("failed to extract icon from %s\n",
968 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
971 /* check the path */
972 if( szPath[0] )
974 static const WCHAR exeW[] = {'.','e','x','e',0};
975 WCHAR *p;
977 /* check for .exe extension */
978 if (!(p = strrchrW( szPath, '.' )) ||
979 strchrW( p, '\\' ) || strchrW( p, '/' ) ||
980 lstrcmpiW( p, exeW ))
982 /* Not .exe - use 'start.exe' to launch this file */
983 p = szArgs + lstrlenW(szPath) + 2;
984 if (szArgs[0])
986 p[0] = ' ';
987 memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
988 sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
990 else
991 p[0] = 0;
993 szArgs[0] = '"';
994 lstrcpyW(szArgs + 1, szPath);
995 p[-1] = '"';
997 GetWindowsDirectoryW(szPath, MAX_PATH);
998 lstrcatW(szPath, startW);
1001 /* convert app working dir */
1002 if (szWorkDir[0])
1003 work_dir = wine_get_unix_file_name( szWorkDir );
1005 else
1007 /* if there's no path... try run the link itself */
1008 lstrcpynW(szArgs, link, MAX_PATH);
1009 GetWindowsDirectoryW(szPath, MAX_PATH);
1010 lstrcatW(szPath, startW);
1013 /* escape the path and parameters */
1014 escaped_path = escape(szPath);
1015 escaped_args = escape(szArgs);
1016 escaped_description = escape(szDescription);
1018 r = fork_and_wait("wineshelllink", link_name, escaped_path,
1019 in_desktop_dir(csidl), escaped_args, icon_name,
1020 work_dir ? work_dir : "", escaped_description);
1022 cleanup:
1023 HeapFree( GetProcessHeap(), 0, icon_name );
1024 HeapFree( GetProcessHeap(), 0, work_dir );
1025 HeapFree( GetProcessHeap(), 0, link_name );
1026 HeapFree( GetProcessHeap(), 0, escaped_args );
1027 HeapFree( GetProcessHeap(), 0, escaped_path );
1028 HeapFree( GetProcessHeap(), 0, escaped_description );
1030 if (r)
1032 WINE_ERR("failed to fork and exec wineshelllink\n" );
1033 return FALSE;
1036 return TRUE;
1040 static BOOL Process_Link( LPCWSTR linkname, BOOL bAgain )
1042 IShellLinkW *sl;
1043 IPersistFile *pf;
1044 HRESULT r;
1045 WCHAR fullname[MAX_PATH];
1046 DWORD len;
1048 WINE_TRACE("%s, again %d\n", wine_dbgstr_w(linkname), bAgain);
1050 if( !linkname[0] )
1052 WINE_ERR("link name missing\n");
1053 return 1;
1056 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1057 if (len==0 || len>MAX_PATH)
1059 WINE_ERR("couldn't get full path of link file\n");
1060 return 1;
1063 r = CoInitialize( NULL );
1064 if( FAILED( r ) )
1066 WINE_ERR("CoInitialize failed\n");
1067 return 1;
1070 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1071 &IID_IShellLinkW, (LPVOID *) &sl );
1072 if( FAILED( r ) )
1074 WINE_ERR("No IID_IShellLink\n");
1075 return 1;
1078 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1079 if( FAILED( r ) )
1081 WINE_ERR("No IID_IPersistFile\n");
1082 return 1;
1085 r = IPersistFile_Load( pf, fullname, STGM_READ );
1086 if( SUCCEEDED( r ) )
1088 /* If something fails (eg. Couldn't extract icon)
1089 * defer this menu entry to reboot via runonce
1091 if( ! InvokeShellLinker( sl, fullname, bAgain ) && bAgain )
1092 DeferToRunOnce( fullname );
1093 else
1094 WINE_TRACE("Success.\n");
1097 IPersistFile_Release( pf );
1098 IShellLinkW_Release( sl );
1100 CoUninitialize();
1102 return !r;
1106 static CHAR *next_token( LPSTR *p )
1108 LPSTR token = NULL, t = *p;
1110 if( !t )
1111 return NULL;
1113 while( t && !token )
1115 switch( *t )
1117 case ' ':
1118 t++;
1119 continue;
1120 case '"':
1121 /* unquote the token */
1122 token = ++t;
1123 t = strchr( token, '"' );
1124 if( t )
1125 *t++ = 0;
1126 break;
1127 case 0:
1128 t = NULL;
1129 break;
1130 default:
1131 token = t;
1132 t = strchr( token, ' ' );
1133 if( t )
1134 *t++ = 0;
1135 break;
1138 *p = t;
1139 return token;
1142 /***********************************************************************
1144 * WinMain
1146 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1148 LPSTR token = NULL, p;
1149 BOOL bAgain = FALSE;
1150 HANDLE hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1151 int ret = 0;
1153 /* running multiple instances of wineshelllink
1154 at the same time may be dangerous */
1155 if( WAIT_OBJECT_0 != WaitForSingleObject( hsem, INFINITE ) )
1157 CloseHandle(hsem);
1158 return FALSE;
1161 for( p = cmdline; p && *p; )
1163 token = next_token( &p );
1164 if( !token )
1165 break;
1166 if( !lstrcmpA( token, "-r" ) )
1167 bAgain = TRUE;
1168 else if( token[0] == '-' )
1170 WINE_ERR( "unknown option %s\n",token);
1172 else
1174 WCHAR link[MAX_PATH];
1176 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1177 if( !Process_Link( link, bAgain ) )
1179 WINE_ERR( "failed to build menu item for %s\n",token);
1180 ret = 1;
1185 ReleaseSemaphore( hsem, 1, NULL );
1186 CloseHandle( hsem );
1188 return ret;