Implement the beginnings of the stateblock class, and a first method
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blob7c627e355f23bc37fc03f500b870b8f6ad73d0fd
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
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * This program will read a Windows shortcut file using the IShellLink
24 * interface, then invoke wineshelllink with the appropriate arguments
25 * to create a KDE/Gnome menu entry for the shortcut.
27 * winemenubuilder [ -r ] <shortcut.lnk>
29 * If the -r parameter is passed, and the shortcut cannot be created,
30 * this program will add RunOnce entry to invoke itself at the next
31 * reboot. This covers the case when a ShortCut is created before the
32 * executable containing its icon.
36 #include "config.h"
37 #include "wine/port.h"
39 #include <ctype.h>
40 #include <stdio.h>
41 #ifdef HAVE_STRING_H
42 #include <string.h>
43 #endif
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif
47 #include <errno.h>
48 #include <stdarg.h>
50 #define COBJMACROS
52 #include <windows.h>
53 #include <shlobj.h>
54 #include <objidl.h>
55 #include <shlguid.h>
57 #include "wine/debug.h"
58 #include "wine.xpm"
60 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
62 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
63 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
64 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
65 (csidl)==CSIDL_COMMON_STARTMENU)
67 /* link file formats */
69 #include "pshpack1.h"
71 typedef struct
73 BYTE bWidth;
74 BYTE bHeight;
75 BYTE bColorCount;
76 BYTE bReserved;
77 WORD wPlanes;
78 WORD wBitCount;
79 DWORD dwBytesInRes;
80 WORD nID;
81 } GRPICONDIRENTRY;
83 typedef struct
85 WORD idReserved;
86 WORD idType;
87 WORD idCount;
88 GRPICONDIRENTRY idEntries[1];
89 } GRPICONDIR;
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 DWORD dwImageOffset;
101 } ICONDIRENTRY;
103 typedef struct
105 WORD idReserved;
106 WORD idType;
107 WORD idCount;
108 } ICONDIR;
111 #include "poppack.h"
113 typedef struct
115 HRSRC *pResInfo;
116 int nIndex;
117 } ENUMRESSTRUCT;
120 /* Icon extraction routines
122 * FIXME: should use PrivateExtractIcons and friends
123 * FIXME: should not use stdio
126 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, const char *comment)
128 FILE *fXPMFile;
129 int nHeight;
130 int nXORWidthBytes;
131 int nANDWidthBytes;
132 BOOL b8BitColors;
133 int nColors;
134 BYTE *pXOR;
135 BYTE *pAND;
136 BOOL aColorUsed[256] = {0};
137 int nColorsUsed = 0;
138 int i,j;
140 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
141 return FALSE;
143 if (!(fXPMFile = fopen(szXPMFileName, "w")))
144 return FALSE;
146 nHeight = pIcon->bmiHeader.biHeight / 2;
147 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
148 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
149 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
150 + ((pIcon->bmiHeader.biWidth % 32) > 0));
151 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
152 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
153 : 1 << pIcon->bmiHeader.biBitCount;
154 pXOR = (BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
155 pAND = pXOR + nHeight * nXORWidthBytes;
157 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
158 #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)
160 for (i = 0; i < nHeight; i++) {
161 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
162 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
164 aColorUsed[COLOR(j,i)] = TRUE;
165 nColorsUsed++;
170 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
171 goto error;
172 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
173 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
174 goto error;
176 for (i = 0; i < nColors; i++) {
177 if (aColorUsed[i])
178 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
179 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
180 goto error;
182 if (fprintf(fXPMFile, "\" c None\"") <= 0)
183 goto error;
185 for (i = 0; i < nHeight; i++)
187 if (fprintf(fXPMFile, ",\n\"") <= 0)
188 goto error;
189 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
191 if MASK(j,i)
193 if (fprintf(fXPMFile, " ") <= 0)
194 goto error;
196 else
197 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
198 goto error;
200 if (fprintf(fXPMFile, "\"") <= 0)
201 goto error;
203 if (fprintf(fXPMFile, "};\n") <= 0)
204 goto error;
206 #undef MASK
207 #undef COLOR
209 fclose(fXPMFile);
210 return TRUE;
212 error:
213 fclose(fXPMFile);
214 unlink( szXPMFileName );
215 return FALSE;
218 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCSTR lpszType, LPSTR lpszName, LONG lParam)
220 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
222 if (!sEnumRes->nIndex--)
224 *sEnumRes->pResInfo = FindResourceA(hModule, lpszName, (LPSTR)RT_GROUP_ICON);
225 return FALSE;
227 else
228 return TRUE;
231 static BOOL ExtractFromEXEDLL(const char *szFileName, int nIndex, const char *szXPMFileName)
233 HMODULE hModule;
234 HRSRC hResInfo;
235 char *lpName = NULL;
236 HGLOBAL hResData;
237 GRPICONDIR *pIconDir;
238 BITMAPINFO *pIcon;
239 ENUMRESSTRUCT sEnumRes;
240 int nMax = 0;
241 int nMaxBits = 0;
242 int i;
244 if (!(hModule = LoadLibraryExA(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE)))
246 WINE_ERR("LoadLibraryExA (%s) failed, error %ld\n", szFileName, GetLastError());
247 goto error1;
250 if (nIndex < 0)
252 hResInfo = FindResourceA(hModule, MAKEINTRESOURCEA(-nIndex), (LPSTR)RT_GROUP_ICON);
253 WINE_ERR("FindResourceA (%s) called, return %p, error %ld\n", szFileName, hResInfo, GetLastError());
255 else
257 hResInfo=NULL;
258 sEnumRes.pResInfo = &hResInfo;
259 sEnumRes.nIndex = nIndex;
260 EnumResourceNamesA(hModule, (LPSTR)RT_GROUP_ICON, &EnumResNameProc, (LONG) &sEnumRes);
263 if (!hResInfo)
265 WINE_ERR("ExtractFromEXEDLL failed, error %ld\n", GetLastError());
266 goto error2;
269 if (!(hResData = LoadResource(hModule, hResInfo)))
271 WINE_ERR("LoadResource failed, error %ld\n", GetLastError());
272 goto error2;
274 if (!(pIconDir = LockResource(hResData)))
276 WINE_ERR("LockResource failed, error %ld\n", GetLastError());
277 goto error3;
280 for (i = 0; i < pIconDir->idCount; i++)
281 if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
283 if (pIconDir->idEntries[i].wBitCount > nMaxBits)
285 nMaxBits = pIconDir->idEntries[i].wBitCount;
286 nMax = 0;
288 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) > nMax)
290 lpName = MAKEINTRESOURCEA(pIconDir->idEntries[i].nID);
291 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
295 FreeResource(hResData);
297 if (!(hResInfo = FindResourceA(hModule, lpName, (LPSTR)RT_ICON)))
299 WINE_ERR("Second FindResourceA failed, error %ld\n", GetLastError());
300 goto error2;
302 if (!(hResData = LoadResource(hModule, hResInfo)))
304 WINE_ERR("Second LoadResource failed, error %ld\n", GetLastError());
305 goto error2;
307 if (!(pIcon = LockResource(hResData)))
309 WINE_ERR("Second LockResource failed, error %ld\n", GetLastError());
310 goto error3;
313 if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
315 WINE_ERR("Failed saving icon as XPM, error %ld\n", GetLastError());
316 goto error3;
319 FreeResource(hResData);
320 FreeLibrary(hModule);
322 return TRUE;
324 error3:
325 FreeResource(hResData);
326 error2:
327 FreeLibrary(hModule);
328 error1:
329 return FALSE;
332 /* get the Unix file name for a given path, allocating the string */
333 inline static char *get_unix_file_name( const char *dos )
335 WCHAR dosW[MAX_PATH];
337 MultiByteToWideChar(CP_ACP, 0, dos, -1, dosW, MAX_PATH);
338 return wine_get_unix_file_name( dosW );
341 static int ExtractFromICO(const char *szFileName, const char *szXPMFileName)
343 FILE *fICOFile;
344 ICONDIR iconDir;
345 ICONDIRENTRY *pIconDirEntry;
346 int nMax = 0;
347 int nIndex = 0;
348 void *pIcon;
349 int i;
350 char *filename;
352 filename = get_unix_file_name(szFileName);
353 if (!(fICOFile = fopen(filename, "r")))
354 goto error1;
356 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1)
357 goto error2;
358 if ((iconDir.idReserved != 0) || (iconDir.idType != 1))
359 goto error2;
361 if ((pIconDirEntry = malloc(iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
362 goto error2;
363 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
364 goto error3;
366 for (i = 0; i < iconDir.idCount; i++)
367 if ((pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) > nMax)
369 nIndex = i;
370 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
372 if ((pIcon = malloc(pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
373 goto error3;
374 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
375 goto error4;
376 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
377 goto error4;
379 if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
380 goto error4;
382 free(pIcon);
383 free(pIconDirEntry);
384 fclose(fICOFile);
386 return 1;
388 error4:
389 free(pIcon);
390 error3:
391 free(pIconDirEntry);
392 error2:
393 fclose(fICOFile);
394 error1:
395 HeapFree(GetProcessHeap(), 0, filename);
396 return 0;
399 static BOOL create_default_icon( const char *filename, const char* comment )
401 FILE *fXPM;
402 unsigned int i;
404 if (!(fXPM = fopen(filename, "w"))) return FALSE;
405 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
406 goto error;
407 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
408 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
409 goto error;
411 if (fprintf( fXPM, "};\n" ) <=0)
412 goto error;
413 fclose( fXPM );
414 return TRUE;
415 error:
416 fclose( fXPM );
417 unlink( filename );
418 return FALSE;
422 static unsigned short crc16(const char* string)
424 unsigned short crc = 0;
425 int i, j, xor_poly;
427 for (i = 0; string[i] != 0; i++)
429 char c = string[i];
430 for (j = 0; j < 8; c >>= 1, j++)
432 xor_poly = (c ^ crc) & 1;
433 crc >>= 1;
434 if (xor_poly)
435 crc ^= 0xa001;
438 return crc;
441 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
442 static char *extract_icon( const char *path, int index)
444 int nodefault = 1;
445 unsigned short crc;
446 char *iconsdir, *ico_path, *ico_name, *xpm_path;
447 char* s;
448 HKEY hkey;
450 /* Where should we save the icon? */
451 WINE_TRACE("path=[%s] index=%d\n",path,index);
452 iconsdir=NULL; /* Default is no icon */
453 if (!RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Wine", &hkey ))
455 DWORD size = 0;
456 if (RegQueryValueExA(hkey, "IconsDir", 0, NULL, NULL, &size)==0) {
457 iconsdir = HeapAlloc(GetProcessHeap(), 0, size);
458 RegQueryValueExA(hkey, "IconsDir", 0, NULL, iconsdir, &size);
460 s=get_unix_file_name(iconsdir);
461 if (s) {
462 HeapFree(GetProcessHeap(), 0, iconsdir);
463 iconsdir=s;
465 } else {
466 char path[MAX_PATH];
468 if (GetTempPath(sizeof(path),path)) {
469 s=get_unix_file_name(path);
470 if (s) {
471 iconsdir=s;
475 RegCloseKey( hkey );
477 if (iconsdir==NULL || *iconsdir=='\0')
479 if (iconsdir)
480 HeapFree(GetProcessHeap(), 0, iconsdir);
481 return NULL; /* No icon created */
484 /* If icon path begins with a '*' then this is a deferred call */
485 if (path[0] == '*')
487 path++;
488 nodefault = 0;
491 /* Determine the icon base name */
492 ico_path=HeapAlloc(GetProcessHeap(), 0, lstrlenA(path)+1);
493 strcpy(ico_path, path);
494 s=ico_name=ico_path;
495 while (*s!='\0') {
496 if (*s=='/' || *s=='\\') {
497 *s='\\';
498 ico_name=s;
499 } else {
500 *s=tolower(*s);
502 s++;
504 if (*ico_name=='\\') *ico_name++='\0';
505 s=strrchr(ico_name,'.');
506 if (s) *s='\0';
508 /* Compute the source-path hash */
509 crc=crc16(ico_path);
511 /* Try to treat the source file as an exe */
512 xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
513 sprintf(xpm_path,"%s/%04x_%s.%d.xpm",iconsdir,crc,ico_name,index);
514 if (ExtractFromEXEDLL( path, index, xpm_path ))
515 goto end;
517 /* Must be something else, ignore the index in that case */
518 sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
519 if (ExtractFromICO( path, xpm_path))
520 goto end;
521 if (!nodefault)
522 if (create_default_icon( xpm_path, path ))
523 goto end;
525 HeapFree( GetProcessHeap(), 0, xpm_path );
526 xpm_path=NULL;
528 end:
529 HeapFree(GetProcessHeap(), 0, iconsdir);
530 HeapFree(GetProcessHeap(), 0, ico_path);
531 return xpm_path;
534 static BOOL DeferToRunOnce(LPWSTR link)
536 HKEY hkey;
537 LONG r, len;
538 static const WCHAR szRunOnce[] = {
539 'S','o','f','t','w','a','r','e','\\',
540 'M','i','c','r','o','s','o','f','t','\\',
541 'W','i','n','d','o','w','s','\\',
542 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
543 'R','u','n','O','n','c','e',0
545 static const WCHAR szFormat[] = { '%','s',' ','"','%','s','"',0 };
546 LPWSTR buffer;
547 WCHAR szExecutable[MAX_PATH];
549 WINE_TRACE( "Deferring icon creation to reboot.\n");
551 len = GetModuleFileNameW( 0, szExecutable, MAX_PATH );
552 if (!len || len >= MAX_PATH) return FALSE;
554 len = ( lstrlenW( link ) + lstrlenW( szExecutable ) + 4)*sizeof(WCHAR);
555 buffer = HeapAlloc( GetProcessHeap(), 0, len );
556 if( !buffer )
557 return FALSE;
559 wsprintfW( buffer, szFormat, szExecutable, link );
561 r = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szRunOnce, 0,
562 NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL);
563 if ( r == ERROR_SUCCESS )
565 r = RegSetValueExW(hkey, link, 0, REG_SZ,
566 (LPBYTE) buffer, (lstrlenW(buffer) + 1)*sizeof(WCHAR));
567 RegCloseKey(hkey);
569 HeapFree(GetProcessHeap(), 0, buffer);
571 return ! r;
574 /* This escapes \ in filenames */
575 static LPSTR
576 escape(LPCSTR arg) {
577 LPSTR narg, x;
579 narg = HeapAlloc(GetProcessHeap(),0,2*strlen(arg)+2);
580 x = narg;
581 while (*arg) {
582 *x++ = *arg;
583 if (*arg == '\\')
584 *x++='\\'; /* escape \ */
585 arg++;
587 *x = 0;
588 return narg;
591 static int fork_and_wait( char *linker, char *link_name, char *path,
592 int desktop, char *args, char *icon_name,
593 char *workdir, char *description )
595 int pos = 0;
596 const char *argv[20];
597 int retcode;
599 WINE_TRACE( "linker app='%s' link='%s' mode=%s "
600 "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
601 linker, link_name, desktop ? "desktop" : "menu",
602 path, args, icon_name, workdir, description );
604 argv[pos++] = linker ;
605 argv[pos++] = "--link";
606 argv[pos++] = link_name;
607 argv[pos++] = "--path";
608 argv[pos++] = path;
609 argv[pos++] = desktop ? "--desktop" : "--menu";
610 if (args && strlen(args))
612 argv[pos++] = "--args";
613 argv[pos++] = args;
615 if (icon_name)
617 argv[pos++] = "--icon";
618 argv[pos++] = icon_name;
620 if (workdir && strlen(workdir))
622 argv[pos++] = "--workdir";
623 argv[pos++] = workdir;
625 if (description && strlen(description))
627 argv[pos++] = "--descr";
628 argv[pos++] = description;
630 argv[pos] = NULL;
632 retcode=spawnvp( _P_WAIT, linker, argv );
633 if (retcode!=0)
634 WINE_ERR("%s returned %d\n",linker,retcode);
635 return retcode;
638 static char *cleanup_link( LPCWSTR link )
640 char *p, *link_name;
641 int len;
643 /* make link name a Unix name -
644 strip leading slashes & remove extension */
645 while ( (*link == '\\') || (*link == '/' ) )
646 link++;
647 len = WideCharToMultiByte( CP_ACP, 0, link, -1, NULL, 0, NULL, NULL);
648 link_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof (WCHAR) );
649 if( ! link_name )
650 return link_name;
651 len = WideCharToMultiByte( CP_ACP, 0, link, -1, link_name, len, NULL, NULL);
652 for (p = link_name; *p; p++)
653 if (*p == '\\')
654 *p = '/';
655 p = strrchr( link_name, '.' );
656 if (p)
657 *p = 0;
658 return link_name;
661 /***********************************************************************
663 * GetLinkLocation
665 * returns TRUE if successful
666 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP
668 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *ofs, DWORD *loc )
670 WCHAR filename[MAX_PATH], buffer[MAX_PATH];
671 DWORD len, i, r, filelen;
672 const DWORD locations[] = {
673 CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
674 CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
675 CSIDL_COMMON_STARTMENU };
677 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
678 filelen=GetFullPathNameW( linkfile, MAX_PATH, filename, NULL );
679 if (filelen==0 || filelen>MAX_PATH)
680 return FALSE;
682 for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
684 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
685 continue;
687 len = lstrlenW(buffer);
688 if (len >= MAX_PATH)
689 continue;
691 if (len > filelen || filename[len]!='\\')
692 continue;
693 /* do a lstrcmpinW */
694 filename[len] = 0;
695 r = lstrcmpiW( filename, buffer );
696 filename[len] = '\\';
697 if ( r )
698 continue;
700 /* return the remainder of the string and link type */
701 *ofs = len;
702 *loc = locations[i];
703 return TRUE;
706 return FALSE;
709 static BOOL InvokeShellLinker( IShellLinkA *sl, LPCWSTR link )
711 char *link_name, *p, *icon_name = NULL, *work_dir = NULL;
712 char *escaped_path = NULL, *escaped_args = NULL;
713 CHAR szDescription[MAX_PATH], szPath[MAX_PATH], szWorkDir[MAX_PATH];
714 CHAR szArgs[MAX_PATH], szIconPath[MAX_PATH];
715 int iIconId = 0, r;
716 DWORD ofs=0, csidl= -1;
718 if ( !link )
720 WINE_ERR("Link name is null\n");
721 return FALSE;
724 if( !GetLinkLocation( link, &ofs, &csidl ) )
726 WINE_WARN("Unknown link location '%s'. Ignoring.\n",wine_dbgstr_w(link));
727 return TRUE;
729 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
731 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
732 return TRUE;
735 szWorkDir[0]=0;
736 IShellLinkA_GetWorkingDirectory( sl, szWorkDir, sizeof(szWorkDir));
737 WINE_TRACE("workdir : %s\n", szWorkDir);
739 szDescription[0] = 0;
740 IShellLinkA_GetDescription( sl, szDescription, sizeof(szDescription));
741 WINE_TRACE("description: %s\n", szDescription);
743 szPath[0] = 0;
744 IShellLinkA_GetPath( sl, szPath, sizeof(szPath), NULL, SLGP_RAWPATH );
745 WINE_TRACE("path : %s\n", szPath);
747 szArgs[0] = 0;
748 IShellLinkA_GetArguments( sl, szArgs, sizeof(szArgs) );
749 WINE_TRACE("args : %s\n", szArgs);
751 szIconPath[0] = 0;
752 IShellLinkA_GetIconLocation( sl, szIconPath,
753 sizeof(szIconPath), &iIconId );
754 WINE_TRACE("icon file : %s\n", szIconPath );
756 if( !szPath[0] )
758 LPITEMIDLIST pidl = NULL;
759 IShellLinkA_GetIDList( sl, &pidl );
760 if( pidl && SHGetPathFromIDListA( pidl, szPath ) );
761 WINE_TRACE("pidl path : %s\n", szPath );
764 /* extract the icon */
765 if( szIconPath[0] )
766 icon_name = extract_icon( szIconPath , iIconId );
767 else
768 icon_name = extract_icon( szPath, iIconId );
770 /* fail - try once again at reboot time */
771 if( !icon_name )
773 WINE_ERR("failed to extract icon.\n");
774 return FALSE;
777 /* check the path */
778 if( szPath[0] )
780 /* check for .exe extension */
781 if (!(p = strrchr( szPath, '.' ))) return FALSE;
782 if (strchr( p, '\\' ) || strchr( p, '/' )) return FALSE;
783 if (strcasecmp( p, ".exe" )) return FALSE;
785 /* convert app working dir */
786 if (szWorkDir[0])
787 work_dir = get_unix_file_name( szWorkDir );
789 else
791 /* if there's no path... try run the link itself */
792 WideCharToMultiByte( CP_ACP, 0, link, -1, szArgs, MAX_PATH, NULL, NULL );
793 GetWindowsDirectoryA(szPath, MAX_PATH);
794 strncat(szPath, "\\command\\start.exe",
795 MAX_PATH - GetWindowsDirectoryA(NULL, 0));
798 link_name = cleanup_link( &link[ofs] );
799 if( !link_name )
801 WINE_ERR("Couldn't clean up link name\n");
802 return FALSE;
805 /* escape the path and parameters */
806 escaped_path = escape(szPath);
807 if (szArgs)
808 escaped_args = escape(szArgs);
810 r = fork_and_wait("wineshelllink", link_name, escaped_path,
811 in_desktop_dir(csidl), escaped_args, icon_name,
812 work_dir ? work_dir : "", szDescription );
814 HeapFree( GetProcessHeap(), 0, icon_name );
815 HeapFree( GetProcessHeap(), 0, work_dir );
816 HeapFree( GetProcessHeap(), 0, link_name );
817 if (escaped_args)
818 HeapFree( GetProcessHeap(), 0, escaped_args );
819 if (escaped_path)
820 HeapFree( GetProcessHeap(), 0, escaped_path );
822 if (r)
824 WINE_ERR("failed to fork and exec wineshelllink\n" );
825 return FALSE;
828 return TRUE;
832 static BOOL Process_Link( LPWSTR linkname, BOOL bAgain )
834 IShellLinkA *sl;
835 IPersistFile *pf;
836 HRESULT r;
837 WCHAR fullname[MAX_PATH];
838 DWORD len;
840 if( !linkname[0] )
842 WINE_ERR("link name missing\n");
843 return 1;
846 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
847 if (len==0 || len>MAX_PATH)
849 WINE_ERR("couldn't get full path of link file\n");
850 return 1;
853 r = CoInitialize( NULL );
854 if( FAILED( r ) )
856 WINE_ERR("CoInitialize failed\n");
857 return 1;
860 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
861 &IID_IShellLink, (LPVOID *) &sl );
862 if( FAILED( r ) )
864 WINE_ERR("No IID_IShellLink\n");
865 return 1;
868 r = IShellLinkA_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
869 if( FAILED( r ) )
871 WINE_ERR("No IID_IPersistFile\n");
872 return 1;
875 r = IPersistFile_Load( pf, fullname, STGM_READ );
876 if( SUCCEEDED( r ) )
878 /* If we something fails (eg. Couldn't extract icon)
879 * defer this menu entry to reboot via runonce
881 if( ! InvokeShellLinker( sl, fullname ) && bAgain )
882 DeferToRunOnce( fullname );
883 else
884 WINE_TRACE("Success.\n");
887 IPersistFile_Release( pf );
888 IShellLinkA_Release( sl );
890 CoUninitialize();
892 return !r;
896 static CHAR *next_token( LPSTR *p )
898 LPSTR token = NULL, t = *p;
900 if( !t )
901 return NULL;
903 while( t && !token )
905 switch( *t )
907 case ' ':
908 t++;
909 continue;
910 case '"':
911 /* unquote the token */
912 token = ++t;
913 t = strchr( token, '"' );
914 if( t )
915 *t++ = 0;
916 break;
917 case 0:
918 t = NULL;
919 break;
920 default:
921 token = t;
922 t = strchr( token, ' ' );
923 if( t )
924 *t++ = 0;
925 break;
928 *p = t;
929 return token;
932 /***********************************************************************
934 * WinMain
936 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
938 LPSTR token = NULL, p;
939 BOOL bAgain = FALSE;
940 HANDLE hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
941 int ret = 0;
943 /* running multiple instances of wineshelllink
944 at the same time may be dangerous */
945 if( WAIT_OBJECT_0 != WaitForSingleObject( hsem, INFINITE ) )
946 return FALSE;
948 for( p = cmdline; p && *p; )
950 token = next_token( &p );
951 if( !token )
952 break;
953 if( !lstrcmpA( token, "-r" ) )
954 bAgain = TRUE;
955 else if( token[0] == '-' )
957 WINE_ERR( "unknown option %s\n",token);
959 else
961 WCHAR link[MAX_PATH];
963 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link) );
964 if( !Process_Link( link, bAgain ) )
966 WINE_ERR( "failed to build menu item for %s\n",token);
967 ret = 1;
968 break;
973 ReleaseSemaphore( hsem, 1, NULL );
974 CloseHandle( hsem );
976 return ret;