Improved Italian translations.
[wine] / programs / winemenubuilder / winemenubuilder.c
1 /*
2  * Helper program to build unix menu entries
3  *
4  * Copyright 1997 Marcus Meissner
5  * Copyright 1998 Juergen Schmied
6  * Copyright 2003 Mike McCormack for CodeWeavers
7  *
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.
12  *
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.
17  *
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
21  *
22  *
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.
26  *
27  *  winemenubuilder [ -r ] <shortcut.lnk>
28  *
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.
33  *
34  */
35
36 #include "config.h"
37 #include "wine/port.h"
38
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>
49
50 #include <windows.h>
51 #include <shlobj.h>
52 #include <objidl.h>
53 #include <shlguid.h>
54
55 #include "bitmaps/wine.xpm"
56 #include "wine/debug.h"
57
58 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
59
60 /* link file formats */
61
62 #include "pshpack1.h"
63
64 typedef struct
65 {
66     BYTE bWidth;
67     BYTE bHeight;
68     BYTE bColorCount;
69     BYTE bReserved;
70     WORD wPlanes;
71     WORD wBitCount;
72     DWORD dwBytesInRes;
73     WORD nID;
74 } GRPICONDIRENTRY;
75
76 typedef struct
77 {
78     WORD idReserved;
79     WORD idType;
80     WORD idCount;
81     GRPICONDIRENTRY idEntries[1];
82 } GRPICONDIR;
83
84 typedef struct
85 {
86     BYTE bWidth;
87     BYTE bHeight;
88     BYTE bColorCount;
89     BYTE bReserved;
90     WORD wPlanes;
91     WORD wBitCount;
92     DWORD dwBytesInRes;
93     DWORD dwImageOffset;
94 } ICONDIRENTRY;
95
96 typedef struct
97 {
98     WORD idReserved;
99     WORD idType;
100     WORD idCount;
101 } ICONDIR;
102
103
104 #include "poppack.h"
105
106 typedef struct
107 {
108         HRSRC *pResInfo;
109         int   nIndex;
110 } ENUMRESSTRUCT;
111
112
113 /* Icon extraction routines
114  *
115  * FIXME: should use PrivateExtractIcons and friends
116  * FIXME: should not use stdio
117  */
118
119 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, const char *comment)
120 {
121     FILE *fXPMFile;
122     int nHeight;
123     int nXORWidthBytes;
124     int nANDWidthBytes;
125     BOOL b8BitColors;
126     int nColors;
127     BYTE *pXOR;
128     BYTE *pAND;
129     BOOL aColorUsed[256] = {0};
130     int nColorsUsed = 0;
131     int i,j;
132
133     if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
134         return FALSE;
135
136     if (!(fXPMFile = fopen(szXPMFileName, "w")))
137         return FALSE;
138
139     nHeight = pIcon->bmiHeader.biHeight / 2;
140     nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
141                           + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
142     nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
143                           + ((pIcon->bmiHeader.biWidth % 32) > 0));
144     b8BitColors = pIcon->bmiHeader.biBitCount == 8;
145     nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
146         : 1 << pIcon->bmiHeader.biBitCount;
147     pXOR = (BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
148     pAND = pXOR + nHeight * nXORWidthBytes;
149
150 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
151 #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)
152
153     for (i = 0; i < nHeight; i++) {
154         for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
155             if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
156             {
157                 aColorUsed[COLOR(j,i)] = TRUE;
158                 nColorsUsed++;
159             }
160         }
161     }
162
163     if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
164         goto error;
165     if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
166                 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
167         goto error;
168
169     for (i = 0; i < nColors; i++) {
170         if (aColorUsed[i])
171             if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
172                         pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
173                 goto error;
174     }
175     if (fprintf(fXPMFile, "\"   c None\"") <= 0)
176         goto error;
177
178     for (i = 0; i < nHeight; i++)
179     {
180         if (fprintf(fXPMFile, ",\n\"") <= 0)
181             goto error;
182         for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
183         {
184             if MASK(j,i)
185                 {
186                     if (fprintf(fXPMFile, "  ") <= 0)
187                         goto error;
188                 }
189             else
190                 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
191                     goto error;
192         }
193         if (fprintf(fXPMFile, "\"") <= 0)
194             goto error;
195     }
196     if (fprintf(fXPMFile, "};\n") <= 0)
197         goto error;
198
199 #undef MASK
200 #undef COLOR
201
202     fclose(fXPMFile);
203     return TRUE;
204
205  error:
206     fclose(fXPMFile);
207     unlink( szXPMFileName );
208     return FALSE;
209 }
210
211 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCSTR lpszType, LPSTR lpszName, LONG lParam)
212 {
213     ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
214
215     if (!sEnumRes->nIndex--)
216     {
217       *sEnumRes->pResInfo = FindResourceA(hModule, lpszName, (LPSTR)RT_GROUP_ICON);
218       return FALSE;
219     }
220     else
221       return TRUE;
222 }
223
224 static BOOL ExtractFromEXEDLL(const char *szFileName, int nIndex, const char *szXPMFileName)
225 {
226     HMODULE hModule;
227     HRSRC hResInfo;
228     char *lpName = NULL;
229     HGLOBAL hResData;
230     GRPICONDIR *pIconDir;
231     BITMAPINFO *pIcon;
232     ENUMRESSTRUCT sEnumRes;
233     int nMax = 0;
234     int nMaxBits = 0;
235     int i;
236
237     if (!(hModule = LoadLibraryExA(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE)))
238     {
239         WINE_ERR("LoadLibraryExA (%s) failed, error %ld\n", szFileName, GetLastError());
240         goto error1;
241     }
242
243     if (nIndex < 0)
244     {
245         hResInfo = FindResourceA(hModule, MAKEINTRESOURCEA(-nIndex), (LPSTR)RT_GROUP_ICON);
246         WINE_ERR("FindResourceA (%s) called, return %p, error %ld\n", szFileName, hResInfo, GetLastError());
247     }
248     else
249     {
250         hResInfo=NULL;
251         sEnumRes.pResInfo = &hResInfo;
252         sEnumRes.nIndex = nIndex;
253         EnumResourceNamesA(hModule, (LPSTR)RT_GROUP_ICON, &EnumResNameProc, (LONG) &sEnumRes);
254     }
255
256     if (!hResInfo)
257     {
258         WINE_ERR("ExtractFromEXEDLL failed, error %ld\n", GetLastError());
259         goto error2;
260     }
261
262     if (!(hResData = LoadResource(hModule, hResInfo)))
263     {
264         WINE_ERR("LoadResource failed, error %ld\n", GetLastError());
265         goto error2;
266     }
267     if (!(pIconDir = LockResource(hResData)))
268     {
269         WINE_ERR("LockResource failed, error %ld\n", GetLastError());
270         goto error3;
271     }
272
273     for (i = 0; i < pIconDir->idCount; i++)
274         if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
275         {
276           if (pIconDir->idEntries[i].wBitCount > nMaxBits)
277           {
278               nMaxBits = pIconDir->idEntries[i].wBitCount;
279               nMax = 0;
280           }
281           if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) > nMax)
282           {
283               lpName = MAKEINTRESOURCEA(pIconDir->idEntries[i].nID);
284               nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
285           }
286         }
287
288     FreeResource(hResData);
289
290     if (!(hResInfo = FindResourceA(hModule, lpName, (LPSTR)RT_ICON)))
291     {
292         WINE_ERR("Second FindResourceA failed, error %ld\n", GetLastError());
293         goto error2;
294     }
295     if (!(hResData = LoadResource(hModule, hResInfo)))
296     {
297         WINE_ERR("Second LoadResource failed, error %ld\n", GetLastError());
298         goto error2;
299     }
300     if (!(pIcon = LockResource(hResData)))
301     {
302         WINE_ERR("Second LockResource failed, error %ld\n", GetLastError());
303         goto error3;
304     }
305
306     if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
307     {
308         WINE_ERR("Failed saving icon as XPM, error %ld\n", GetLastError());
309         goto error3;
310     }
311
312     FreeResource(hResData);
313     FreeLibrary(hModule);
314
315     return TRUE;
316
317  error3:
318     FreeResource(hResData);
319  error2:
320     FreeLibrary(hModule);
321  error1:
322     return FALSE;
323 }
324
325 /* get the Unix file name for a given path, allocating the string */
326 inline static char *get_unix_file_name( const char *dos )
327 {
328     char buffer[MAX_PATH], *ret;
329
330     if (!wine_get_unix_file_name( dos, buffer, sizeof(buffer) )) return NULL;
331     ret = HeapAlloc( GetProcessHeap(), 0, lstrlenA( buffer ) + 1 );
332     lstrcpyA( ret, buffer );
333     return ret;
334 }
335
336 static int ExtractFromICO(const char *szFileName, const char *szXPMFileName)
337 {
338     FILE *fICOFile;
339     ICONDIR iconDir;
340     ICONDIRENTRY *pIconDirEntry;
341     int nMax = 0;
342     int nIndex = 0;
343     void *pIcon;
344     int i;
345     char *filename;
346
347     filename = get_unix_file_name(szFileName);
348     if (!(fICOFile = fopen(filename, "r")))
349         goto error1;
350
351     if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1)
352         goto error2;
353     if ((iconDir.idReserved != 0) || (iconDir.idType != 1))
354         goto error2;
355
356     if ((pIconDirEntry = malloc(iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
357         goto error2;
358     if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
359         goto error3;
360
361     for (i = 0; i < iconDir.idCount; i++)
362         if ((pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) > nMax)
363         {
364             nIndex = i;
365             nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
366         }
367     if ((pIcon = malloc(pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
368         goto error3;
369     if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
370         goto error4;
371     if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
372         goto error4;
373
374     if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
375         goto error4;
376
377     free(pIcon);
378     free(pIconDirEntry);
379     fclose(fICOFile);
380
381     return 1;
382
383  error4:
384     free(pIcon);
385  error3:
386     free(pIconDirEntry);
387  error2:
388     fclose(fICOFile);
389  error1:
390     HeapFree(GetProcessHeap(), 0, filename);
391     return 0;
392 }
393
394 static BOOL create_default_icon( const char *filename, const char* comment )
395 {
396     FILE *fXPM;
397     int i;
398
399     if (!(fXPM = fopen(filename, "w"))) return FALSE;
400     if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
401         goto error;
402     for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
403         if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
404             goto error;
405     }
406     if (fprintf( fXPM, "};\n" ) <=0)
407         goto error;
408     fclose( fXPM );
409     return TRUE;
410  error:
411     fclose( fXPM );
412     unlink( filename );
413     return FALSE;
414
415 }
416
417 static unsigned short crc16(const char* string)
418 {
419     unsigned short crc = 0;
420     int i, j, xor_poly;
421
422     for (i = 0; string[i] != 0; i++)
423     {
424         char c = string[i];
425         for (j = 0; j < 8; c >>= 1, j++)
426         {
427             xor_poly = (c ^ crc) & 1;
428             crc >>= 1;
429             if (xor_poly)
430                 crc ^= 0xa001;
431         }
432     }
433     return crc;
434 }
435
436 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
437 static char *extract_icon( const char *path, int index)
438 {
439     int nodefault = 1;
440     unsigned short crc;
441     char *iconsdir, *ico_path, *ico_name, *xpm_path;
442     char* s;
443     HKEY hkey;
444
445     /* Where should we save the icon? */
446     WINE_TRACE("path=[%s] index=%d\n",path,index);
447     iconsdir=NULL;  /* Default is no icon */
448     if (!RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Wine", &hkey ))
449     {
450         DWORD size = 0;
451         if (RegQueryValueExA(hkey, "IconsDir", 0, NULL, NULL, &size)==0) {
452             iconsdir = HeapAlloc(GetProcessHeap(), 0, size);
453             RegQueryValueExA(hkey, "IconsDir", 0, NULL, iconsdir, &size);
454
455             s=get_unix_file_name(iconsdir);
456             if (s) {
457                 HeapFree(GetProcessHeap(), 0, iconsdir);
458                 iconsdir=s;
459             }
460         }
461         RegCloseKey( hkey );
462     }
463     if (iconsdir==NULL || *iconsdir=='\0')
464     {
465         if (iconsdir)
466             HeapFree(GetProcessHeap(), 0, iconsdir);
467         return NULL;  /* No icon created */
468     }
469
470     /* If icon path begins with a '*' then this is a deferred call */
471     if (path[0] == '*')
472     {
473         path++;
474         nodefault = 0;
475     }
476
477     /* Determine the icon base name */
478     ico_path=HeapAlloc(GetProcessHeap(), 0, lstrlenA(path)+1);
479     strcpy(ico_path, path);
480     s=ico_name=ico_path;
481     while (*s!='\0') {
482         if (*s=='/' || *s=='\\') {
483             *s='\\';
484             ico_name=s;
485         } else {
486             *s=tolower(*s);
487         }
488         s++;
489     }
490     if (*ico_name=='\\') *ico_name++='\0';
491     s=strrchr(ico_name,'.');
492     if (s) *s='\0';
493
494     /* Compute the source-path hash */
495     crc=crc16(ico_path);
496
497     /* Try to treat the source file as an exe */
498     xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
499     sprintf(xpm_path,"%s/%04x_%s.%d.xpm",iconsdir,crc,ico_name,index);
500     if (ExtractFromEXEDLL( path, index, xpm_path ))
501         goto end;
502
503     /* Must be something else, ignore the index in that case */
504     sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
505     if (ExtractFromICO( path, xpm_path))
506         goto end;
507     if (!nodefault)
508         if (create_default_icon( xpm_path, path ))
509             goto end;
510
511     HeapFree( GetProcessHeap(), 0, xpm_path );
512     xpm_path=NULL;
513
514  end:
515     HeapFree( GetProcessHeap(), 0, ico_path );
516     return xpm_path;
517 }
518
519 static BOOL DeferToRunOnce(LPWSTR link)
520 {
521     HKEY hkey;
522     LONG r, len;
523     const WCHAR szRunOnce[] = {
524         'S','o','f','t','w','a','r','e','\\',
525         'M','i','c','r','o','s','o','f','t','\\',
526         'W','i','n','d','o','w','s','\\',
527         'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
528         'R','u','n','O','n','c','e',0
529     };
530     const WCHAR szFormat[] = { '%','s',' ','"','%','s','"',0 };
531     LPWSTR buffer;
532     WCHAR szExecutable[MAX_PATH];
533
534     WINE_TRACE( "Deferring icon creation to reboot.\n");
535
536     if( !GetModuleFileNameW( 0, szExecutable, MAX_PATH ) )
537         return FALSE;
538
539     len = ( lstrlenW( link ) + lstrlenW( szExecutable ) + 4)*sizeof(WCHAR);
540     buffer = HeapAlloc( GetProcessHeap(), 0, len );
541     if( !buffer )
542         return FALSE;
543
544     wsprintfW( buffer, szFormat, szExecutable, link );
545
546     r = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szRunOnce, 0,
547               NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL);
548     if ( r == ERROR_SUCCESS )
549     {
550         r = RegSetValueExW(hkey, link, 0, REG_SZ,
551                    (LPBYTE) buffer, (lstrlenW(buffer) + 1)*sizeof(WCHAR));
552         RegCloseKey(hkey);
553     }
554     HeapFree(GetProcessHeap(), 0, buffer);
555
556     return ! r;
557 }
558
559 /* This escapes \ in filenames */
560 static LPSTR
561 escape(LPCSTR arg) {
562     LPSTR      narg, x;
563
564     narg = HeapAlloc(GetProcessHeap(),0,2*strlen(arg)+2);
565     x = narg;
566     while (*arg) {
567         *x++ = *arg;
568         if (*arg == '\\')
569             *x++='\\'; /* escape \ */
570         arg++;
571     }
572     *x = 0;
573     return narg;
574 }
575
576 static int fork_and_wait( char *linker, char *link_name, char *path,
577                           int desktop, char *args, char *icon_name,
578                           char *workdir, char *description )
579 {
580     int pos = 0;
581     const char *argv[20];
582
583     WINE_TRACE( "linker app='%s' link='%s' mode=%s "
584         "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
585         linker, link_name, desktop ? "desktop" : "menu",
586         path, args, icon_name, workdir, description  );
587
588     argv[pos++] = linker ;
589     argv[pos++] = "--link";
590     argv[pos++] = link_name;
591     argv[pos++] = "--path";
592     argv[pos++] = path;
593     argv[pos++] = desktop ? "--desktop" : "--menu";
594     if (args && strlen(args))
595     {
596         argv[pos++] = "--args";
597         argv[pos++] = args;
598     }
599     if (icon_name)
600     {
601         argv[pos++] = "--icon";
602         argv[pos++] = icon_name;
603     }
604     if (workdir && strlen(workdir))
605     {
606         argv[pos++] = "--workdir";
607         argv[pos++] = workdir;
608     }
609     if (description && strlen(description))
610     {
611         argv[pos++] = "--descr";
612         argv[pos++] = description;
613     }
614     argv[pos] = NULL;
615
616     return spawnvp( _P_WAIT, linker, argv );
617 }
618
619 /* write the name of the ShellLinker into the buffer provided */
620 static BOOL GetLinkerName( LPSTR szLinker, DWORD max )
621 {
622     LONG r;
623     DWORD type = 0;
624     HKEY hkey;
625
626     szLinker[0] = 0;
627     r = RegOpenKeyExA( HKEY_LOCAL_MACHINE,
628                         "Software\\Wine\\Wine\\Config\\Wine",
629                         0, KEY_ALL_ACCESS, &hkey );
630     if( r )
631         return FALSE;
632     r = RegQueryValueExA( hkey, "ShellLinker", 0, &type, szLinker, &max );
633     RegCloseKey( hkey );
634     if( r || ( type != REG_SZ ) )
635         return FALSE;
636
637     return TRUE ;
638 }
639
640 static char *cleanup_link( LPCWSTR link )
641 {
642     char  *p, *link_name;
643     int len;
644
645     /* make link name a Unix name -
646        strip leading slashes & remove extension */
647     while ( (*link == '\\') || (*link == '/' ) )
648         link++;
649     len = WideCharToMultiByte( CP_ACP, 0, link, -1, NULL, 0, NULL, NULL);
650     link_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof (WCHAR) );
651     if( ! link_name )
652         return link_name;
653     len = WideCharToMultiByte( CP_ACP, 0, link, -1, link_name, len, NULL, NULL);
654     for (p = link_name; *p; p++)
655         if (*p == '\\')
656              *p = '/';
657     p = strrchr( link_name, '.' );
658     if (p)
659         *p = 0;
660     return link_name;
661 }
662
663 /***********************************************************************
664  *
665  *           GetLinkLocation
666  *
667  * returns TRUE if successful
668  * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP
669  */
670 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *ofs, DWORD *loc )
671 {
672     WCHAR ch, filename[MAX_PATH], buffer[MAX_PATH];
673     DWORD len, i, r;
674     const DWORD locations[] = {
675         CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU };
676
677     if( !GetFullPathNameW( linkfile, MAX_PATH, filename, NULL ))
678         return FALSE;
679
680     for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
681     {
682         if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
683             continue;
684
685         len = lstrlenW(buffer);
686         if( len >= MAX_PATH )
687             continue;
688
689         /* do a lstrcmpinW */
690         ch = filename[len];
691         filename[len] = 0;
692         r = lstrcmpiW( filename, buffer );
693         filename[len] = ch;
694
695         if ( r )
696             continue;
697
698         /* return the remainder of the string and link type */
699         *ofs = len;
700         *loc = locations[i];
701         return TRUE;
702     }
703
704     return FALSE;
705 }
706
707 static BOOL InvokeShellLinker( IShellLinkA *sl, LPCWSTR link )
708 {
709     char *link_name, *p, *icon_name = NULL, *work_dir = NULL;
710     char *escaped_path = NULL, *escaped_args = NULL;
711     CHAR szDescription[MAX_PATH], szPath[MAX_PATH], szWorkDir[MAX_PATH];
712     CHAR szArgs[MAX_PATH], szIconPath[MAX_PATH], szLinker[MAX_PATH];
713     int iIconId = 0, r;
714     DWORD ofs=0, csidl= -1;
715
716     if ( !link )
717     {
718         WINE_ERR("Link name is null\n");
719         return FALSE;
720     }
721
722     if( !GetLinkerName( szLinker, MAX_PATH ) )
723     {
724         WINE_ERR("Can't find the name of the linker script\n");
725         return FALSE;
726     }
727
728     if( !GetLinkLocation( link, &ofs, &csidl ) )
729     {
730         WINE_WARN("Unknown link location (%08lx). Ignoring\n", csidl);
731         return TRUE;
732     }
733     if( (csidl != CSIDL_DESKTOPDIRECTORY) && (csidl != CSIDL_STARTMENU) )
734     {
735         WINE_WARN("Not under desktop or start menu. Ignoring.\n");
736         return TRUE;
737     }
738
739     szWorkDir[0]=0;
740     IShellLinkA_GetWorkingDirectory( sl, szWorkDir, sizeof(szWorkDir));
741     WINE_TRACE("workdir    : %s\n", szWorkDir);
742
743     szDescription[0] = 0;
744     IShellLinkA_GetDescription( sl, szDescription, sizeof(szDescription));
745     WINE_TRACE("description: %s\n", szDescription);
746
747     szPath[0] = 0;
748     IShellLinkA_GetPath( sl, szPath, sizeof(szPath), NULL, SLGP_RAWPATH );
749     WINE_TRACE("path       : %s\n", szPath);
750
751     szArgs[0] = 0;
752     IShellLinkA_GetArguments( sl, szArgs, sizeof(szArgs) );
753     WINE_TRACE("args       : %s\n", szArgs);
754
755     szIconPath[0] = 0;
756     IShellLinkA_GetIconLocation( sl, szIconPath,
757                         sizeof(szIconPath), &iIconId );
758     WINE_TRACE("icon file  : %s\n", szIconPath );
759
760     if( !szPath[0] )
761     {
762         LPITEMIDLIST pidl = NULL;
763         IShellLinkA_GetIDList( sl, &pidl );
764         if( pidl && SHGetPathFromIDListA( pidl, szPath ) );
765             WINE_TRACE("pidl path  : %s\n", szPath );
766     }
767
768     /* extract the icon */
769     if( szIconPath[0] )
770         icon_name = extract_icon( szIconPath , iIconId );
771     else
772         icon_name = extract_icon( szPath, iIconId );
773
774     /* fail - try once again at reboot time */
775     if( !icon_name )
776     {
777         WINE_ERR("failed to extract icon.\n");
778         return FALSE;
779     }
780
781     /* check the path */
782     if( szPath[0] )
783     {
784         /* check for .exe extension */
785         if (!(p = strrchr( szPath, '.' ))) return FALSE;
786         if (strchr( p, '\\' ) || strchr( p, '/' )) return FALSE;
787         if (strcasecmp( p, ".exe" )) return FALSE;
788
789         /* convert app working dir */
790         if (szWorkDir[0])
791             work_dir = get_unix_file_name( szWorkDir );
792     }
793     else
794     {
795         /* if there's no path... try run the link itself */
796         WideCharToMultiByte( CP_ACP, 0, link, -1, szArgs, MAX_PATH, NULL, NULL );
797         strcpy(szPath, "C:\\Windows\\System\\start.exe");
798     }
799
800     link_name = cleanup_link( &link[ofs] );
801     if( !link_name )
802     {
803         WINE_ERR("Couldn't clean up link name\n");
804         return FALSE;
805     }
806
807     /* escape the path and parameters */
808     escaped_path = escape(szPath);
809     if (szArgs)
810         escaped_args = escape(szArgs);
811
812     r = fork_and_wait(szLinker, link_name, escaped_path,
813                   (csidl == CSIDL_DESKTOPDIRECTORY), escaped_args, icon_name,
814                    work_dir ? work_dir : "", szDescription );
815
816     HeapFree( GetProcessHeap(), 0, icon_name );
817     HeapFree( GetProcessHeap(), 0, work_dir );
818     HeapFree( GetProcessHeap(), 0, link_name );
819     if (escaped_args)
820         HeapFree( GetProcessHeap(), 0, escaped_args );
821     if (escaped_path)
822         HeapFree( GetProcessHeap(), 0, escaped_path );
823
824     if (r)
825     {
826         WINE_ERR("failed to fork and exec %s\n", szLinker );
827         return FALSE;
828     }
829
830     return TRUE;
831 }
832
833
834 static BOOL Process_Link( LPWSTR linkname, BOOL bAgain )
835 {
836     IShellLinkA *sl;
837     IPersistFile *pf;
838     HRESULT r;
839     WCHAR fullname[MAX_PATH];
840  
841     if( !linkname[0] )
842     {
843         WINE_ERR("link name missing\n");
844         return 1;
845     }
846
847     if( !GetFullPathNameW( linkname, MAX_PATH, fullname, NULL ))
848     {
849         WINE_ERR("couldn't get full path of link file\n");
850         return 1;
851     }
852
853     r = CoInitialize( NULL );
854     if( FAILED( r ) )
855         return 1;
856
857     r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
858                       &IID_IShellLink, (LPVOID *) &sl );
859     if( FAILED( r ) )
860     {
861         WINE_ERR("No IID_IShellLink\n");
862         return 1;
863     }
864
865     r = IShellLinkA_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
866     if( FAILED( r ) )
867     {
868         WINE_ERR("No IID_IPersistFile\n");
869         return 1;
870     }
871
872     r = IPersistFile_Load( pf, fullname, STGM_READ );
873     if( SUCCEEDED( r ) )
874     {
875         /* If we something fails (eg. Couldn't extract icon)
876          * defer this menu entry to reboot via runonce
877          */
878         if( ! InvokeShellLinker( sl, fullname ) && bAgain )
879             DeferToRunOnce( fullname );
880         else
881             WINE_TRACE("Success.\n");
882     }
883
884     IPersistFile_Release( pf );
885     IShellLinkA_Release( sl );
886
887     CoUninitialize();
888
889     return !r;
890 }
891
892
893 static CHAR *next_token( LPSTR *p )
894 {
895     LPSTR token = NULL, t = *p;
896
897     if( !t )
898         return NULL;
899
900     while( t && !token )
901     {
902         switch( *t )
903         {
904         case ' ':
905             t++;
906             continue;
907         case '"':
908             /* unquote the token */
909             token = ++t;
910             t = strchr( token, '"' );
911             if( t )
912                  *t++ = 0;
913             break;
914         case 0:
915             t = NULL;
916             break;
917         default:
918             token = t;
919             t = strchr( token, ' ' );
920             if( t )
921                  *t++ = 0;
922             break;
923         }
924     }
925     *p = t;
926     return token;
927 }
928
929 /***********************************************************************
930  *
931  *           WinMain
932  */
933 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
934 {
935     LPSTR token = NULL, p;
936     BOOL bAgain = FALSE;
937     HANDLE hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
938     int ret = 0;
939
940     /* running multiple instances of wineshelllink
941        at the same time may be dangerous */
942     if( WAIT_OBJECT_0 != WaitForSingleObject( hsem, INFINITE ) )
943         return FALSE;
944
945     for( p = cmdline; p && *p; )
946     {
947         token = next_token( &p );
948         if( !token )
949             break;
950         if( !lstrcmpA( token, "-r" ) )
951             bAgain = TRUE;
952         else if( token[0] == '-' )
953         {
954             WINE_ERR( "unknown option %s\n",token);
955         }
956         else
957         {
958             WCHAR link[MAX_PATH];
959
960             MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link) );
961             if( !Process_Link( link, bAgain ) )
962             {
963                 WINE_ERR( "failed to build menu item for %s\n",token);
964                 ret = 1;
965                 break;
966             }
967         }
968     }
969
970     ReleaseSemaphore( hsem, 1, NULL );
971     CloseHandle( hsem );
972
973     return ret;
974 }