Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / programs / winemenubuilder / winemenubuilder.c
blob499dc6cb2a22b3a9df63c8f742c9cc6ea68e1629
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/winbase16.h"
78 #include "wine/unicode.h"
79 #include "wine/debug.h"
80 #include "wine.xpm"
82 WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);
84 #define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
85 (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
86 #define in_startmenu(csidl) ((csidl)==CSIDL_STARTMENU || \
87 (csidl)==CSIDL_COMMON_STARTMENU)
88 static const DWORD locations[] = {
89 CSIDL_STARTMENU,
90 CSIDL_COMMON_STARTMENU,
91 CSIDL_DESKTOPDIRECTORY,
92 CSIDL_COMMON_DESKTOPDIRECTORY
94 #define LOCATION_COUNT sizeof(locations)/sizeof(locations[0])
96 /* link file formats */
98 #include "pshpack1.h"
100 typedef struct
102 BYTE bWidth;
103 BYTE bHeight;
104 BYTE bColorCount;
105 BYTE bReserved;
106 WORD wPlanes;
107 WORD wBitCount;
108 DWORD dwBytesInRes;
109 WORD nID;
110 } GRPICONDIRENTRY;
112 typedef struct
114 WORD idReserved;
115 WORD idType;
116 WORD idCount;
117 GRPICONDIRENTRY idEntries[1];
118 } GRPICONDIR;
120 typedef struct
122 BYTE bWidth;
123 BYTE bHeight;
124 BYTE bColorCount;
125 BYTE bReserved;
126 WORD wPlanes;
127 WORD wBitCount;
128 DWORD dwBytesInRes;
129 DWORD dwImageOffset;
130 } ICONDIRENTRY;
132 typedef struct
134 WORD idReserved;
135 WORD idType;
136 WORD idCount;
137 } ICONDIR;
140 #include "poppack.h"
142 typedef struct
144 HRSRC *pResInfo;
145 int nIndex;
146 } ENUMRESSTRUCT;
149 /* Icon extraction routines
151 * FIXME: should use PrivateExtractIcons and friends
152 * FIXME: should not use stdio
155 #ifdef __APPLE__
156 #define CREATE_ICO_FILES 1
157 #else
158 #undef CREATE_ICO_FILES
159 #endif
161 #if CREATE_ICO_FILES
162 #define EXPORTED_ICON_EXT "ico"
163 #else
164 #define EXPORTED_ICON_EXT "xpm"
165 #endif
168 #if CREATE_ICO_FILES
170 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szICOFileName, LPCWSTR commentW)
172 BITMAPINFOHEADER* pHdr = (BITMAPINFOHEADER*)pIcon;
173 FILE* fICOFile;
174 ICONDIR iconDir;
175 ICONDIRENTRY dirEntry;
176 BOOL ret = FALSE;
178 fICOFile = fopen(szICOFileName, "w");
179 if (!fICOFile)
180 return FALSE;
182 /* Create the directory header */
183 iconDir.idReserved = 0;
184 iconDir.idType = 1;
185 iconDir.idCount = 1;
186 if (fwrite(&iconDir, 1, sizeof(iconDir), fICOFile) != sizeof(iconDir))
187 goto error;
189 /* Create the directory entry */
190 dirEntry.bWidth = pHdr->biWidth;
191 dirEntry.bHeight = pHdr->biHeight / 2;
192 dirEntry.bColorCount = pHdr->biClrUsed;
193 dirEntry.bReserved = 0;
194 dirEntry.wPlanes = pHdr->biPlanes;
195 dirEntry.wBitCount = pHdr->biBitCount;
196 dirEntry.dwBytesInRes = pHdr->biSize + pHdr->biClrUsed*sizeof(RGBQUAD) + pHdr->biSizeImage;
197 dirEntry.dwImageOffset = sizeof(iconDir) + sizeof(dirEntry);
199 if (fwrite(&dirEntry, 1, sizeof(dirEntry), fICOFile) != sizeof(dirEntry))
200 goto error;
202 /* Copy the image */
203 if (fwrite(pIcon, 1, dirEntry.dwBytesInRes, fICOFile) != dirEntry.dwBytesInRes)
204 goto error;
206 ret = TRUE;
208 error:
209 fclose(fICOFile);
210 if (!ret)
211 unlink(szICOFileName);
212 return ret;
215 static BOOL extract_icon_dir(HMODULE hModule, GRPICONDIR* pIconDir, const char *szICOFileName, LPCWSTR commentW)
217 FILE* fICOFile;
218 HRSRC hResInfo;
219 HGLOBAL hResData;
220 BITMAPINFO *pIcon;
221 DWORD imageOffset;
222 int i;
223 BOOL ret = FALSE;
225 fICOFile = fopen(szICOFileName, "w");
226 if (!fICOFile)
228 WINE_ERR("fopen(\"%s\", \"w\") failed, errno %d\n", szICOFileName, errno);
229 return FALSE;
232 /* Copy the directory header */
233 /* The first part of a GRPICONDIR matches an ICONDIR */
234 if (fwrite(pIconDir, 1, sizeof(ICONDIR), fICOFile) != sizeof(ICONDIR))
236 WINE_ERR("fwrite(pIconDir) failed, errno %d\n", errno);
237 goto error;
240 imageOffset = sizeof(ICONDIR) + pIconDir->idCount * sizeof(ICONDIRENTRY);
242 /* Copy the directory entries */
243 for (i = 0; i < pIconDir->idCount; i++)
245 ICONDIRENTRY dirEntry;
246 /* ICONDIRENTRY and GRPICONDIRENTRY are identical up to the last field */
247 memcpy(&dirEntry, &pIconDir->idEntries[i], offsetof(ICONDIRENTRY, dwImageOffset));
248 dirEntry.dwImageOffset = imageOffset;
249 imageOffset += dirEntry.dwBytesInRes;
251 if (fwrite(&dirEntry, 1, sizeof(dirEntry), fICOFile) != sizeof(dirEntry))
253 WINE_ERR("fwrite(dirEntry) failed, i = %d/%d, errno %d\n", i, pIconDir->idCount, errno);
254 goto error;
258 /* Copy the images */
259 for (i = 0; i < pIconDir->idCount; i++)
261 hResInfo = FindResourceW
263 hModule,
264 MAKEINTRESOURCEW(pIconDir->idEntries[i].nID),
265 (LPCWSTR) RT_ICON
267 if (!hResInfo)
269 WINE_ERR("FindResourceW failed, i = %d/%d, nID = %hd/%p, error %u\n", i, pIconDir->idCount, pIconDir->idEntries[i].nID, MAKEINTRESOURCEW(pIconDir->idEntries[i].nID), GetLastError());
270 goto error;
273 if (!(hResData = LoadResource(hModule, hResInfo)))
275 WINE_ERR("LoadResource failed, i = %d/%d, error %u\n", i, pIconDir->idCount, GetLastError());
276 goto error;
279 if (
280 !(pIcon = LockResource(hResData)) ||
281 fwrite(pIcon, 1, pIconDir->idEntries[i].dwBytesInRes, fICOFile) !=
282 pIconDir->idEntries[i].dwBytesInRes
285 if (!pIcon)
286 WINE_ERR("LockResource failed, i = %d/%d, error %u\n", i, pIconDir->idCount, GetLastError());
287 else
288 WINE_ERR("fwrite failed, i = %d/%d, dwBytesInRes = %u, errno %d\n", i, pIconDir->idCount, pIconDir->idEntries[i].dwBytesInRes, errno);
289 FreeResource(hResData);
290 goto error;
293 FreeResource(hResData);
296 ret = TRUE;
298 error:
299 fclose(fICOFile);
300 if (!ret)
301 unlink(szICOFileName);
302 return ret;
305 #else
307 static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
309 FILE *fXPMFile;
310 int nHeight;
311 int nXORWidthBytes;
312 int nANDWidthBytes;
313 BOOL b8BitColors;
314 int nColors;
315 const BYTE *pXOR;
316 const BYTE *pAND;
317 BOOL aColorUsed[256] = {0};
318 int nColorsUsed = 0;
319 int i,j;
320 char *comment;
322 if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
324 WINE_FIXME("Unsupported color depth %d-bit\n", pIcon->bmiHeader.biBitCount);
325 return FALSE;
328 if (!(fXPMFile = fopen(szXPMFileName, "w")))
330 WINE_TRACE("unable to open '%s' for writing: %s\n", szXPMFileName, strerror(errno));
331 return FALSE;
334 i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
335 comment = HeapAlloc(GetProcessHeap(), 0, i);
336 WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);
338 nHeight = pIcon->bmiHeader.biHeight / 2;
339 nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
340 + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
341 nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
342 + ((pIcon->bmiHeader.biWidth % 32) > 0));
343 b8BitColors = pIcon->bmiHeader.biBitCount == 8;
344 nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
345 : 1 << pIcon->bmiHeader.biBitCount;
346 pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
347 pAND = pXOR + nHeight * nXORWidthBytes;
349 #define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
350 #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)
352 for (i = 0; i < nHeight; i++) {
353 for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
354 if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
356 aColorUsed[COLOR(j,i)] = TRUE;
357 nColorsUsed++;
362 if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
363 goto error;
364 if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
365 (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
366 goto error;
368 for (i = 0; i < nColors; i++) {
369 if (aColorUsed[i])
370 if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
371 pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
372 goto error;
374 if (fprintf(fXPMFile, "\" c None\"") <= 0)
375 goto error;
377 for (i = 0; i < nHeight; i++)
379 if (fprintf(fXPMFile, ",\n\"") <= 0)
380 goto error;
381 for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
383 if MASK(j,i)
385 if (fprintf(fXPMFile, " ") <= 0)
386 goto error;
388 else
389 if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
390 goto error;
392 if (fprintf(fXPMFile, "\"") <= 0)
393 goto error;
395 if (fprintf(fXPMFile, "};\n") <= 0)
396 goto error;
398 #undef MASK
399 #undef COLOR
401 HeapFree(GetProcessHeap(), 0, comment);
402 fclose(fXPMFile);
403 return TRUE;
405 error:
406 HeapFree(GetProcessHeap(), 0, comment);
407 fclose(fXPMFile);
408 unlink( szXPMFileName );
409 return FALSE;
412 static BOOL extract_icon_dir(HMODULE hModule, GRPICONDIR* pIconDir, const char *szXPMFileName, LPCWSTR commentW)
414 BITMAPINFO *pIcon;
415 int nMax = 0;
416 int nMaxBits = 0;
417 LPCWSTR lpName = NULL;
418 int i;
419 HRSRC hResInfo;
420 HGLOBAL hResData;
421 BOOL ret = FALSE;
423 for (i = 0; i < pIconDir->idCount; i++)
425 if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
427 nMaxBits = pIconDir->idEntries[i].wBitCount;
429 if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
431 lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
432 nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
437 if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
439 if ((hResData = LoadResource(hModule, hResInfo)))
441 if ((pIcon = LockResource(hResData)))
443 if(SaveIconResAsXPM(pIcon, szXPMFileName, commentW))
444 ret = TRUE;
447 FreeResource(hResData);
451 return ret;
454 #endif
456 static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
458 ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;
460 if (!sEnumRes->nIndex--)
462 *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
463 return FALSE;
465 else
466 return TRUE;
469 static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
471 HMODULE hModule;
472 HRSRC hResInfo;
473 HGLOBAL hResData;
474 GRPICONDIR *pIconDir;
475 ENUMRESSTRUCT sEnumRes;
476 BOOL ret = FALSE;
478 hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
479 if (!hModule)
481 WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
482 wine_dbgstr_w(szFileName), GetLastError());
483 return FALSE;
486 if (nIndex < 0)
488 hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
489 WINE_TRACE("FindResourceW (%s, %d/%p) called, return %p, error %d\n",
490 wine_dbgstr_w(szFileName), -nIndex, MAKEINTRESOURCEW(-nIndex), hResInfo, GetLastError());
492 else
494 hResInfo=NULL;
495 sEnumRes.pResInfo = &hResInfo;
496 sEnumRes.nIndex = nIndex;
497 if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
498 EnumResNameProc, (LONG_PTR)&sEnumRes))
500 WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
504 if (hResInfo)
506 if ((hResData = LoadResource(hModule, hResInfo)))
508 if ((pIconDir = LockResource(hResData)))
510 ret = extract_icon_dir(hModule, pIconDir, szXPMFileName, szFileName);
513 FreeResource(hResData);
516 else
518 WINE_WARN("found no icon\n");
519 FreeLibrary(hModule);
520 return FALSE;
523 FreeLibrary(hModule);
524 return ret;
527 static BOOL extract_icon16(LPCWSTR szFileName, const char *szXPMFileName)
529 BITMAPINFO *pIcon;
530 int len;
531 HINSTANCE16 hInstance16;
532 HRSRC16 hRsrc;
533 HGLOBAL16 handle;
534 char *file_name;
535 BOOL ret = FALSE;
537 len = WideCharToMultiByte(CP_ACP, 0, szFileName, -1, NULL, 0, NULL, NULL);
538 file_name = HeapAlloc(GetProcessHeap(), 0, len);
539 WideCharToMultiByte(CP_ACP, 0, szFileName, -1, file_name, len, NULL, NULL);
541 if ((hInstance16 = LoadLibrary16(file_name)) >= 32)
543 if ((hRsrc = FindResource16( hInstance16, MAKEINTRESOURCE(1), (LPSTR)RT_ICON )))
545 if ((handle = LoadResource16( hInstance16, hRsrc )))
547 if ((pIcon = LockResource16(handle)))
549 if (SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
550 ret = TRUE;
552 FreeResource16( handle );
557 HeapFree(GetProcessHeap(), 0, file_name);
558 FreeLibrary16( hInstance16);
559 return ret;
562 static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
564 if (!extract_icon32(szFileName, nIndex, szXPMFileName) &&
565 !extract_icon16(szFileName, szXPMFileName))
566 return FALSE;
567 return TRUE;
570 #if CREATE_ICO_FILES
572 static int ExtractFromICO(LPCWSTR szFileName, const char *szICOFileName)
574 char* szFileNameA;
575 FILE* fTest;
576 off_t fileSize, dataSize = 0, imagesStart;
577 ICONDIR iconDir;
578 ICONDIRENTRY dirEntry;
579 int i;
580 int ret = 0;
582 /* Verify that the file seems to be a valid ICO file */
583 szFileNameA = wine_get_unix_file_name(szFileName);
584 if (!(fTest = fopen(szFileNameA, "r")))
586 WINE_WARN("unable to open '%s' for reading: %s\n", szFileNameA, strerror(errno));
587 goto error1;
590 if (fseek(fTest, 0, SEEK_END))
592 WINE_WARN("failed to seek to end of '%s': %s\n", szFileNameA, strerror(errno));
593 goto error2;
595 if ((fileSize = ftello(fTest)) == -1)
597 WINE_WARN("failed to tell position in '%s': %s\n", szFileNameA, strerror(errno));
598 goto error2;
600 if (fseek(fTest, 0, SEEK_SET))
602 WINE_WARN("failed to seek to beginning of '%s': %s\n", szFileNameA, strerror(errno));
603 goto error2;
606 if (fread(&iconDir, 1, sizeof(iconDir), fTest) != sizeof(iconDir))
608 WINE_WARN("failed to read %lu bytes from '%s': %s\n", sizeof(iconDir), szFileNameA, strerror(errno));
609 goto error2;
611 dataSize += sizeof(iconDir);
613 if (iconDir.idReserved != 0 || iconDir.idType != 1)
615 WINE_TRACE("'%s' doesn't seem to be a valid ICO file: idReserved = %hd (should be 0), idType = %hd (should be 1)\n", szFileNameA, iconDir.idReserved, iconDir.idType);
616 goto error2;
619 imagesStart = sizeof(iconDir) + iconDir.idCount * sizeof(dirEntry);
620 for (i = 0; i < iconDir.idCount; i++)
622 if (fread(&dirEntry, 1, sizeof(dirEntry), fTest) != sizeof(dirEntry))
624 WINE_WARN("failed to read %lu bytes from '%s': %s\n", sizeof(dirEntry), szFileNameA, strerror(errno));
625 goto error2;
627 dataSize += sizeof(dirEntry);
629 if (
630 dirEntry.bWidth == 0 ||
631 dirEntry.bHeight == 0 ||
632 dirEntry.bReserved != 0 ||
633 dirEntry.dwBytesInRes == 0 ||
634 dirEntry.dwBytesInRes > fileSize ||
635 dirEntry.dwImageOffset < imagesStart ||
636 dirEntry.dwImageOffset > fileSize - dirEntry.dwBytesInRes
639 WINE_TRACE("'%s' doesn't seem to be a valid ICO file: for entry %d, bWidth = %d, bHeight = %d, bReserved = %d, dwBytesInRes = %u, dwImageOffset = %u, fileSize = %ld, imagesStart = %ld\n", szFileNameA, i, (int)dirEntry.bWidth, (int)dirEntry.bHeight, (int)dirEntry.bReserved, dirEntry.dwBytesInRes, dirEntry.dwImageOffset, (long)fileSize, (long)imagesStart);
640 goto error2;
642 dataSize += dirEntry.dwBytesInRes;
645 if (dataSize > fileSize)
647 WINE_TRACE("'%s' doesn't seem to be a valid ICO file: dataSize = %ld (should be less than fileSize, %ld)\n", szFileNameA, (long)dataSize, (long)fileSize);
648 goto error2;
651 /* Seems to be a valid ICO file. Copy it. */
652 if (CopyFileA(szFileNameA, szICOFileName, FALSE))
653 ret = 1;
654 else
655 WINE_ERR("Failed to copy '%s' to '%s', error %u\n", szFileNameA, szICOFileName, GetLastError());
657 error2:
658 fclose(fTest);
659 error1:
660 HeapFree(GetProcessHeap(), 0, szFileNameA);
661 return ret;
664 #else
666 static int ExtractFromICO(LPCWSTR szFileName, const char *szXPMFileName)
668 FILE *fICOFile;
669 ICONDIR iconDir;
670 ICONDIRENTRY *pIconDirEntry;
671 int nMax = 0, nMaxBits = 0;
672 int nIndex = 0;
673 void *pIcon;
674 int i;
675 char *filename;
677 filename = wine_get_unix_file_name(szFileName);
678 if (!(fICOFile = fopen(filename, "r")))
680 WINE_TRACE("unable to open '%s' for reading: %s\n", filename, strerror(errno));
681 goto error1;
684 if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1 ||
685 (iconDir.idReserved != 0) || (iconDir.idType != 1))
687 WINE_WARN("Invalid ico file format\n");
688 goto error2;
691 if ((pIconDirEntry = HeapAlloc(GetProcessHeap(), 0, iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
692 goto error2;
693 if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
694 goto error3;
696 for (i = 0; i < iconDir.idCount; i++)
697 if (pIconDirEntry[i].wBitCount <= 8 && pIconDirEntry[i].wBitCount >= nMaxBits &&
698 (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
700 nIndex = i;
701 nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
702 nMaxBits = pIconDirEntry[i].wBitCount;
704 if ((pIcon = HeapAlloc(GetProcessHeap(), 0, pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
705 goto error3;
706 if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
707 goto error4;
708 if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
709 goto error4;
711 if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
712 goto error4;
714 HeapFree(GetProcessHeap(), 0, pIcon);
715 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
716 fclose(fICOFile);
717 HeapFree(GetProcessHeap(), 0, filename);
718 return 1;
720 error4:
721 HeapFree(GetProcessHeap(), 0, pIcon);
722 error3:
723 HeapFree(GetProcessHeap(), 0, pIconDirEntry);
724 error2:
725 fclose(fICOFile);
726 error1:
727 HeapFree(GetProcessHeap(), 0, filename);
728 return 0;
731 #endif
733 static BOOL create_default_icon( const char *filename, const char* comment )
735 FILE *fXPM;
736 unsigned int i;
738 if (!(fXPM = fopen(filename, "w"))) return FALSE;
739 if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
740 goto error;
741 for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
742 if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
743 goto error;
745 if (fprintf( fXPM, "};\n" ) <=0)
746 goto error;
747 fclose( fXPM );
748 return TRUE;
749 error:
750 fclose( fXPM );
751 unlink( filename );
752 return FALSE;
756 static unsigned short crc16(const char* string)
758 unsigned short crc = 0;
759 int i, j, xor_poly;
761 for (i = 0; string[i] != 0; i++)
763 char c = string[i];
764 for (j = 0; j < 8; c >>= 1, j++)
766 xor_poly = (c ^ crc) & 1;
767 crc >>= 1;
768 if (xor_poly)
769 crc ^= 0xa001;
772 return crc;
775 /* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
776 static char *extract_icon( LPCWSTR path, int index)
778 int nodefault = 1;
779 unsigned short crc;
780 char *iconsdir, *ico_path, *ico_name, *new_icon_path;
781 char* s;
782 HKEY hkey;
783 int n;
785 /* Where should we save the icon? */
786 WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
787 iconsdir=NULL; /* Default is no icon */
788 /* @@ Wine registry key: HKCU\Software\Wine\WineMenuBuilder */
789 if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\WineMenuBuilder", &hkey ))
791 static const WCHAR IconsDirW[] = {'I','c','o','n','s','D','i','r',0};
792 LPWSTR iconsdirW;
793 DWORD size = 0;
795 if (!RegQueryValueExW(hkey, IconsDirW, 0, NULL, NULL, &size))
797 iconsdirW = HeapAlloc(GetProcessHeap(), 0, size);
798 RegQueryValueExW(hkey, IconsDirW, 0, NULL, (LPBYTE)iconsdirW, &size);
800 if (!(iconsdir = wine_get_unix_file_name(iconsdirW)))
802 int n = WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, NULL, 0, NULL, NULL);
803 iconsdir = HeapAlloc(GetProcessHeap(), 0, n);
804 WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, iconsdir, n, NULL, NULL);
806 HeapFree(GetProcessHeap(), 0, iconsdirW);
808 RegCloseKey( hkey );
811 if (!iconsdir)
813 WCHAR path[MAX_PATH];
814 if (GetTempPathW(MAX_PATH, path))
815 iconsdir = wine_get_unix_file_name(path);
816 if (!iconsdir)
818 WINE_TRACE("no IconsDir\n");
819 return NULL; /* No icon created */
823 if (!*iconsdir)
825 WINE_TRACE("icon generation disabled\n");
826 HeapFree(GetProcessHeap(), 0, iconsdir);
827 return NULL; /* No icon created */
830 /* If icon path begins with a '*' then this is a deferred call */
831 if (path[0] == '*')
833 path++;
834 nodefault = 0;
837 /* Determine the icon base name */
838 n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
839 ico_path = HeapAlloc(GetProcessHeap(), 0, n);
840 WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
841 s=ico_name=ico_path;
842 while (*s!='\0') {
843 if (*s=='/' || *s=='\\') {
844 *s='\\';
845 ico_name=s;
846 } else {
847 *s=tolower(*s);
849 s++;
851 if (*ico_name=='\\') *ico_name++='\0';
852 s=strrchr(ico_name,'.');
853 if (s) *s='\0';
855 /* Compute the source-path hash */
856 crc=crc16(ico_path);
858 /* Try to treat the source file as an exe */
859 new_icon_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
860 sprintf(new_icon_path,"%s/%04x_%s.%d.%s",iconsdir,crc,ico_name,index,EXPORTED_ICON_EXT);
861 if (ExtractFromEXEDLL( path, index, new_icon_path ))
862 goto end;
864 /* Must be something else, ignore the index in that case */
865 sprintf(new_icon_path,"%s/%04x_%s.%s",iconsdir,crc,ico_name,EXPORTED_ICON_EXT);
866 if (ExtractFromICO( path, new_icon_path))
867 goto end;
868 if (!nodefault)
869 if (create_default_icon( new_icon_path, ico_path ))
870 goto end;
872 HeapFree( GetProcessHeap(), 0, new_icon_path );
873 new_icon_path=NULL;
875 end:
876 HeapFree(GetProcessHeap(), 0, iconsdir);
877 HeapFree(GetProcessHeap(), 0, ico_path);
878 return new_icon_path;
881 static BOOL DeferToRunOnce(LPWSTR link)
883 HKEY hkey;
884 LONG r, len;
885 static const WCHAR szRunOnce[] = {
886 'S','o','f','t','w','a','r','e','\\',
887 'M','i','c','r','o','s','o','f','t','\\',
888 'W','i','n','d','o','w','s','\\',
889 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
890 'R','u','n','O','n','c','e',0
892 static const WCHAR szFormat[] = { '%','s',' ','"','%','s','"',0 };
893 LPWSTR buffer;
894 WCHAR szExecutable[MAX_PATH];
896 WINE_TRACE( "Deferring icon creation to reboot.\n");
898 len = GetModuleFileNameW( 0, szExecutable, MAX_PATH );
899 if (!len || len >= MAX_PATH) return FALSE;
901 len = ( lstrlenW( link ) + lstrlenW( szExecutable ) + 4)*sizeof(WCHAR);
902 buffer = HeapAlloc( GetProcessHeap(), 0, len );
903 if( !buffer )
904 return FALSE;
906 wsprintfW( buffer, szFormat, szExecutable, link );
908 r = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szRunOnce, 0,
909 NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL);
910 if ( r == ERROR_SUCCESS )
912 r = RegSetValueExW(hkey, link, 0, REG_SZ,
913 (LPBYTE) buffer, (lstrlenW(buffer) + 1)*sizeof(WCHAR));
914 RegCloseKey(hkey);
916 HeapFree(GetProcessHeap(), 0, buffer);
918 return ! r;
921 static LPSTR to_utf8(LPCWSTR strW)
923 LPSTR str;
924 int len;
926 len = WideCharToMultiByte(CP_UTF8, 0, strW, -1, NULL, 0, NULL, NULL);
927 str = HeapAlloc(GetProcessHeap(), 0, len);
928 WideCharToMultiByte(CP_UTF8, 0, strW, -1, str, len, NULL, NULL);
929 return str;
932 static int fork_and_wait( const char *linker, const char *link_root, const char *link_path, const char *path,
933 int desktop, const char *args, const char *icon_name,
934 const char *workdir, const char *description )
936 int pos = 0;
937 const char *argv[20];
938 int retcode;
940 WINE_TRACE( "linker app='%s' root='%s' link='%s' mode=%s "
941 "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
942 linker, link_root, link_path, desktop ? "desktop" : "menu",
943 path, args, icon_name, workdir, description );
945 argv[pos++] = linker ;
946 argv[pos++] = "--utf8";
947 argv[pos++] = "--root";
948 argv[pos++] = link_root;
949 argv[pos++] = "--link";
950 argv[pos++] = link_path;
951 argv[pos++] = "--path";
952 argv[pos++] = path;
953 argv[pos++] = desktop ? "--desktop" : "--menu";
954 if (args && strlen(args))
956 argv[pos++] = "--args";
957 argv[pos++] = args;
959 if (icon_name)
961 argv[pos++] = "--icon";
962 argv[pos++] = icon_name;
964 if (workdir && strlen(workdir))
966 argv[pos++] = "--workdir";
967 argv[pos++] = workdir;
969 if (description && strlen(description))
971 argv[pos++] = "--descr";
972 argv[pos++] = description;
974 argv[pos] = NULL;
976 retcode=spawnvp( _P_WAIT, linker, argv );
977 if (retcode!=0)
978 WINE_ERR("%s returned %d\n",linker,retcode);
979 return retcode;
982 /***********************************************************************
984 * GetLinkLocation
986 * returns TRUE if successful
987 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, etc.
988 * *relative will contain the address of a heap-allocated copy of the portion
989 * of the filename that is within the specified location, in unix form
991 static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, WCHAR* *root )
993 WCHAR filename[MAX_PATH], buffer[MAX_PATH];
994 DWORD len, i, r, filelen;
996 WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
997 filelen=GetFullPathNameW( linkfile, MAX_PATH, filename, NULL );
998 if (filelen==0 || filelen>MAX_PATH)
999 return FALSE;
1001 WINE_TRACE("%s\n", wine_dbgstr_w(filename));
1003 for (i = 0; i < LOCATION_COUNT; i++)
1005 if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
1006 continue;
1008 len = lstrlenW(buffer);
1009 if (len >= MAX_PATH)
1010 continue; /* We've just trashed memory! Hopefully we are OK */
1012 if (len > filelen || filename[len]!='\\')
1013 continue;
1014 /* do a lstrcmpinW */
1015 filename[len] = 0;
1016 r = lstrcmpiW( filename, buffer );
1017 filename[len] = '\\';
1018 if ( r )
1019 continue;
1021 /* return the root path and clsid type */
1022 *loc = locations[i];
1023 *root = HeapAlloc(GetProcessHeap(), 0, (len+1)*sizeof(**root));
1024 lstrcpyW(*root, buffer);
1025 return TRUE;
1028 return FALSE;
1031 /* gets the target path directly or through MSI */
1032 static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
1033 LPWSTR szArgs, DWORD argsSize)
1035 IShellLinkDataList *dl = NULL;
1036 EXP_DARWIN_LINK *dar = NULL;
1037 HRESULT hr;
1039 szPath[0] = 0;
1040 szArgs[0] = 0;
1042 hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1043 if (hr == S_OK && szPath[0])
1045 IShellLinkW_GetArguments( sl, szArgs, argsSize );
1046 return hr;
1049 hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
1050 if (FAILED(hr))
1051 return hr;
1053 hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
1054 if (SUCCEEDED(hr))
1056 WCHAR* szCmdline;
1057 DWORD cmdSize;
1059 cmdSize=0;
1060 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
1061 if (hr == ERROR_SUCCESS)
1063 cmdSize++;
1064 szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
1065 hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
1066 WINE_TRACE(" command : %s\n", wine_dbgstr_w(szCmdline));
1067 if (hr == ERROR_SUCCESS)
1069 WCHAR *s, *d;
1070 int bcount, in_quotes;
1072 /* Extract the application path */
1073 bcount=0;
1074 in_quotes=0;
1075 s=szCmdline;
1076 d=szPath;
1077 while (*s)
1079 if ((*s==0x0009 || *s==0x0020) && !in_quotes)
1081 /* skip the remaining spaces */
1082 do {
1083 s++;
1084 } while (*s==0x0009 || *s==0x0020);
1085 break;
1087 else if (*s==0x005c)
1089 /* '\\' */
1090 *d++=*s++;
1091 bcount++;
1093 else if (*s==0x0022)
1095 /* '"' */
1096 if ((bcount & 1)==0)
1098 /* Preceded by an even number of '\', this is
1099 * half that number of '\', plus a quote which
1100 * we erase.
1102 d-=bcount/2;
1103 in_quotes=!in_quotes;
1104 s++;
1106 else
1108 /* Preceded by an odd number of '\', this is
1109 * half that number of '\' followed by a '"'
1111 d=d-bcount/2-1;
1112 *d++='"';
1113 s++;
1115 bcount=0;
1117 else
1119 /* a regular character */
1120 *d++=*s++;
1121 bcount=0;
1123 if ((d-szPath) == pathSize)
1125 /* Keep processing the path till we get to the
1126 * arguments, but 'stand still'
1128 d--;
1131 /* Close the application path */
1132 *d=0;
1134 lstrcpynW(szArgs, s, argsSize);
1136 HeapFree( GetProcessHeap(), 0, szCmdline );
1138 LocalFree( dar );
1141 IShellLinkDataList_Release( dl );
1142 return hr;
1145 static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bAgain )
1147 char *link_root = NULL, *link_path = NULL, *icon_name = NULL, *work_dir = NULL;
1148 char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
1149 WCHAR* szRoot = NULL;
1150 WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
1151 WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
1152 int iIconId = 0, r = -1;
1153 DWORD csidl = -1;
1155 if ( !link )
1157 WINE_ERR("Link name is null\n");
1158 return FALSE;
1161 WINE_TRACE("link=[%s]\n", wine_dbgstr_w(link));
1162 if( !GetLinkLocation( link, &csidl, &szRoot ) )
1164 WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
1165 return TRUE;
1167 if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
1169 WINE_WARN("Not under desktop or start menu. Ignoring.\n");
1170 return TRUE;
1172 WINE_TRACE("Root : %s\n", wine_dbgstr_w(szRoot));
1174 szWorkDir[0] = 0;
1175 IShellLinkW_GetWorkingDirectory( sl, szWorkDir, MAX_PATH );
1176 WINE_TRACE("workdir : %s\n", wine_dbgstr_w(szWorkDir));
1178 szDescription[0] = 0;
1179 IShellLinkW_GetDescription( sl, szDescription, INFOTIPSIZE );
1180 WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
1182 get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
1183 WINE_TRACE("path : %s\n", wine_dbgstr_w(szPath));
1184 WINE_TRACE("args : %s\n", wine_dbgstr_w(szArgs));
1186 szIconPath[0] = 0;
1187 IShellLinkW_GetIconLocation( sl, szIconPath, MAX_PATH, &iIconId );
1188 WINE_TRACE("icon file : %s\n", wine_dbgstr_w(szIconPath) );
1189 WINE_TRACE("icon id : %d (%#X)\n", iIconId, iIconId );
1191 if( !szPath[0] )
1193 LPITEMIDLIST pidl = NULL;
1194 IShellLinkW_GetIDList( sl, &pidl );
1195 if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
1196 WINE_TRACE("pidl path : %s\n", wine_dbgstr_w(szPath));
1199 /* extract the icon */
1200 if( szIconPath[0] )
1201 icon_name = extract_icon( szIconPath , iIconId );
1202 else
1203 icon_name = extract_icon( szPath, iIconId );
1205 /* fail - try once again at reboot time */
1206 if( !icon_name )
1208 if (bAgain)
1210 WINE_WARN("Unable to extract icon, deferring.\n");
1211 goto cleanup;
1213 WINE_ERR("failed to extract icon from %s\n",
1214 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
1217 /* convert app working dir */
1218 if (szWorkDir[0])
1219 work_dir = wine_get_unix_file_name( szWorkDir );
1221 link_root = to_utf8(szRoot);
1222 link_path = to_utf8(link);
1223 escaped_path = to_utf8(szPath);
1224 escaped_args = to_utf8(szArgs);
1225 escaped_description = to_utf8(szDescription);
1227 r = fork_and_wait("wineshelllink", link_root, link_path, escaped_path,
1228 in_desktop_dir(csidl), escaped_args, icon_name,
1229 work_dir ? work_dir : "", escaped_description);
1231 cleanup:
1232 HeapFree( GetProcessHeap(), 0, icon_name );
1233 HeapFree( GetProcessHeap(), 0, work_dir );
1234 HeapFree( GetProcessHeap(), 0, szRoot );
1235 HeapFree( GetProcessHeap(), 0, link_root );
1236 HeapFree( GetProcessHeap(), 0, link_path );
1237 HeapFree( GetProcessHeap(), 0, escaped_args );
1238 HeapFree( GetProcessHeap(), 0, escaped_path );
1239 HeapFree( GetProcessHeap(), 0, escaped_description );
1241 if (r)
1243 WINE_ERR("failed to fork and exec wineshelllink\n" );
1244 return FALSE;
1247 return TRUE;
1251 static BOOL Process_Link( LPCWSTR linkname, BOOL bAgain )
1253 IShellLinkW *sl;
1254 IPersistFile *pf;
1255 HRESULT r;
1256 WCHAR fullname[MAX_PATH];
1257 DWORD len;
1259 WINE_TRACE("%s, again %d\n", wine_dbgstr_w(linkname), bAgain);
1261 if( !linkname[0] )
1263 WINE_ERR("link name missing\n");
1264 return 1;
1267 len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
1268 if (len==0 || len>MAX_PATH)
1270 WINE_ERR("couldn't get full path of link file\n");
1271 return 1;
1274 r = CoInitialize( NULL );
1275 if( FAILED( r ) )
1277 WINE_ERR("CoInitialize failed\n");
1278 return 1;
1281 r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1282 &IID_IShellLinkW, (LPVOID *) &sl );
1283 if( FAILED( r ) )
1285 WINE_ERR("No IID_IShellLink\n");
1286 return 1;
1289 r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1290 if( FAILED( r ) )
1292 WINE_ERR("No IID_IPersistFile\n");
1293 return 1;
1296 r = IPersistFile_Load( pf, fullname, STGM_READ );
1297 if( SUCCEEDED( r ) )
1299 /* If something fails (eg. Couldn't extract icon)
1300 * defer this menu entry to reboot via runonce
1302 if( ! InvokeShellLinker( sl, fullname, bAgain ) && bAgain )
1303 DeferToRunOnce( fullname );
1304 else
1305 WINE_TRACE("Success.\n");
1308 IPersistFile_Release( pf );
1309 IShellLinkW_Release( sl );
1311 CoUninitialize();
1313 return !r;
1316 static const WCHAR wWILD[]={'\\','*',0};
1318 static BOOL Process_Dir(WCHAR* dir)
1320 static const WCHAR wDOT[]={'.',0};
1321 static const WCHAR wDOTDOT[]={'.','.',0};
1322 static const WCHAR wLNK[]={'.','l','n','k',0};
1323 HANDLE hFind;
1324 WIN32_FIND_DATAW item;
1325 int lendir, len;
1326 WCHAR* path;
1327 BOOL rc;
1329 WINE_TRACE("scanning directory %s\n", wine_dbgstr_w(dir));
1330 lendir=lstrlenW(dir);
1331 lstrcatW(dir, wWILD);
1332 hFind=FindFirstFileW(dir, &item);
1333 if (hFind == INVALID_HANDLE_VALUE)
1335 WINE_TRACE("unable to open the '%s' directory\n", wine_dbgstr_w(dir));
1336 return FALSE;
1339 rc=TRUE;
1340 path=HeapAlloc(GetProcessHeap(), 0, (lendir+1+MAX_PATH+2+1)*sizeof(WCHAR));
1341 lstrcpyW(path, dir);
1342 path[lendir]='\\';
1343 while (1)
1345 if (lstrcmpW(item.cFileName, wDOT) && lstrcmpW(item.cFileName, wDOTDOT))
1347 WINE_TRACE(" %s\n", wine_dbgstr_w(item.cFileName));
1348 len=lstrlenW(item.cFileName);
1349 if ((item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1350 (len >= 5 && lstrcmpiW(item.cFileName+len-4, wLNK)==0))
1352 lstrcpyW(path+lendir+1, item.cFileName);
1353 if (item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1355 if (!(item.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) /* skip symlinks */
1357 if (!Process_Dir(path))
1358 rc=FALSE;
1361 else
1363 WINE_TRACE(" link %s\n", wine_dbgstr_w(path));
1364 if (!Process_Link(path, FALSE))
1365 rc=FALSE;
1370 if (!FindNextFileW(hFind, &item))
1372 if (GetLastError() != ERROR_NO_MORE_FILES)
1374 WINE_TRACE("got error %d while scanning the '%s' directory\n", GetLastError(), wine_dbgstr_w(dir));
1375 rc=FALSE;
1377 FindClose(hFind);
1378 break;
1382 HeapFree(GetProcessHeap(), 0, path);
1383 return rc;
1386 static BOOL Process_All_Links()
1388 WCHAR dir[MAX_PATH+2]; /* +2 for Process_Dir */
1389 DWORD i, len;
1390 BOOL rc;
1392 rc=TRUE;
1393 for (i = 0; i < LOCATION_COUNT; i++)
1395 if (!SHGetSpecialFolderPathW(0, dir, locations[i], FALSE))
1397 WINE_TRACE("unable to get the path of folder %08x\n", locations[i]);
1398 /* Some special folders are not defined in some bottles
1399 * so this is not an error
1401 continue;
1404 len = lstrlenW(dir);
1405 if (len >= MAX_PATH)
1407 /* We've just trashed memory! Hopefully we are OK */
1408 WINE_TRACE("Ignoring special folder %08x because its path is too long: %s\n", locations[i], wine_dbgstr_w(dir));
1409 rc=FALSE;
1410 continue;
1413 if (!Process_Dir(dir))
1414 rc=FALSE;
1416 return rc;
1419 static CHAR *next_token( LPSTR *p )
1421 LPSTR token = NULL, t = *p;
1423 if( !t )
1424 return NULL;
1426 while( t && !token )
1428 switch( *t )
1430 case ' ':
1431 t++;
1432 continue;
1433 case '"':
1434 /* unquote the token */
1435 token = ++t;
1436 t = strchr( token, '"' );
1437 if( t )
1438 *t++ = 0;
1439 break;
1440 case 0:
1441 t = NULL;
1442 break;
1443 default:
1444 token = t;
1445 t = strchr( token, ' ' );
1446 if( t )
1447 *t++ = 0;
1448 break;
1451 *p = t;
1452 return token;
1455 /***********************************************************************
1457 * WinMain
1459 int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1461 LPSTR token = NULL, p;
1462 BOOL bAgain = FALSE;
1463 HANDLE hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
1464 int ret = 0;
1466 /* running multiple instances of wineshelllink
1467 at the same time may be dangerous */
1468 if( WAIT_OBJECT_0 != WaitForSingleObject( hsem, INFINITE ) )
1470 CloseHandle(hsem);
1471 return FALSE;
1474 for( p = cmdline; p && *p; )
1476 token = next_token( &p );
1477 if( !token )
1478 break;
1479 if( !lstrcmpA( token, "-r" ) )
1480 bAgain = TRUE;
1481 else if( !lstrcmpA( token, "-a" ) )
1483 if (!Process_All_Links())
1485 WINE_ERR("failed to build some menu items\n");
1486 ret = 1;
1489 else if( token[0] == '-' )
1491 WINE_ERR( "unknown option %s\n",token);
1493 else
1495 WCHAR link[MAX_PATH];
1497 MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1498 if( !Process_Link( link, bAgain ) )
1500 WINE_ERR( "failed to build menu item for %s\n",token);
1501 ret = 1;
1506 ReleaseSemaphore( hsem, 1, NULL );
1507 CloseHandle( hsem );
1509 return ret;