winemenubuilder.c 30.7 KB
Newer Older
1 2 3 4 5
/*
 * Helper program to build unix menu entries
 *
 * Copyright 1997 Marcus Meissner
 * Copyright 1998 Juergen Schmied
6
 * Copyright 2003 Mike McCormack for CodeWeavers
7
 * Copyright 2004 Dmitry Timoshkov
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 *  This program will read a Windows shortcut file using the IShellLink
 * interface, then invoke wineshelllink with the appropriate arguments
 * to create a KDE/Gnome menu entry for the shortcut.
 *
 *  winemenubuilder [ -r ] <shortcut.lnk>
 *
 *  If the -r parameter is passed, and the shortcut cannot be created,
 * this program will add RunOnce entry to invoke itself at the next
 * reboot.  This covers the case when a ShortCut is created before the
 * executable containing its icon.
 *
 */

#include "config.h"
#include "wine/port.h"

#include <ctype.h>
#include <stdio.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#include <stdarg.h>

49 50
#define COBJMACROS

51 52 53 54
#include <windows.h>
#include <shlobj.h>
#include <objidl.h>
#include <shlguid.h>
55
#include <appmgmt.h>
56

57
#include "wine/unicode.h"
58
#include "wine/debug.h"
59
#include "wine.xpm"
60 61 62

WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);

63 64 65 66 67
#define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
                               (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
#define in_startmenu(csidl)   ((csidl)==CSIDL_STARTMENU || \
                               (csidl)==CSIDL_COMMON_STARTMENU)
        
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
/* link file formats */

#include "pshpack1.h"

typedef struct
{
    BYTE bWidth;
    BYTE bHeight;
    BYTE bColorCount;
    BYTE bReserved;
    WORD wPlanes;
    WORD wBitCount;
    DWORD dwBytesInRes;
    WORD nID;
} GRPICONDIRENTRY;

typedef struct
{
    WORD idReserved;
    WORD idType;
    WORD idCount;
    GRPICONDIRENTRY idEntries[1];
} GRPICONDIR;

typedef struct
{
    BYTE bWidth;
    BYTE bHeight;
    BYTE bColorCount;
    BYTE bReserved;
    WORD wPlanes;
    WORD wBitCount;
    DWORD dwBytesInRes;
    DWORD dwImageOffset;
} ICONDIRENTRY;

typedef struct
{
    WORD idReserved;
    WORD idType;
    WORD idCount;
} ICONDIR;


#include "poppack.h"

typedef struct
{
        HRSRC *pResInfo;
        int   nIndex;
} ENUMRESSTRUCT;


/* Icon extraction routines
 *
 * FIXME: should use PrivateExtractIcons and friends
 * FIXME: should not use stdio
 */

127
static BOOL SaveIconResAsXPM(const BITMAPINFO *pIcon, const char *szXPMFileName, LPCWSTR commentW)
128 129 130 131 132 133 134
{
    FILE *fXPMFile;
    int nHeight;
    int nXORWidthBytes;
    int nANDWidthBytes;
    BOOL b8BitColors;
    int nColors;
Eric Pouech's avatar
Eric Pouech committed
135 136
    const BYTE *pXOR;
    const BYTE *pAND;
137 138 139
    BOOL aColorUsed[256] = {0};
    int nColorsUsed = 0;
    int i,j;
140
    char *comment;
141 142 143 144 145 146 147

    if (!((pIcon->bmiHeader.biBitCount == 4) || (pIcon->bmiHeader.biBitCount == 8)))
        return FALSE;

    if (!(fXPMFile = fopen(szXPMFileName, "w")))
        return FALSE;

148 149 150 151
    i = WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, NULL, 0, NULL, NULL);
    comment = malloc(i);
    WideCharToMultiByte(CP_UNIXCP, 0, commentW, -1, comment, i, NULL, NULL);

152 153 154 155 156 157 158 159
    nHeight = pIcon->bmiHeader.biHeight / 2;
    nXORWidthBytes = 4 * ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount / 32)
                          + ((pIcon->bmiHeader.biWidth * pIcon->bmiHeader.biBitCount % 32) > 0));
    nANDWidthBytes = 4 * ((pIcon->bmiHeader.biWidth / 32)
                          + ((pIcon->bmiHeader.biWidth % 32) > 0));
    b8BitColors = pIcon->bmiHeader.biBitCount == 8;
    nColors = pIcon->bmiHeader.biClrUsed ? pIcon->bmiHeader.biClrUsed
        : 1 << pIcon->bmiHeader.biBitCount;
Eric Pouech's avatar
Eric Pouech committed
160
    pXOR = (const BYTE*) pIcon + sizeof (BITMAPINFOHEADER) + (nColors * sizeof (RGBQUAD));
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    pAND = pXOR + nHeight * nXORWidthBytes;

#define MASK(x,y) (pAND[(x) / 8 + (nHeight - (y) - 1) * nANDWidthBytes] & (1 << (7 - (x) % 8)))
#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)

    for (i = 0; i < nHeight; i++) {
        for (j = 0; j < pIcon->bmiHeader.biWidth; j++) {
            if (!aColorUsed[COLOR(j,i)] && !MASK(j,i))
            {
                aColorUsed[COLOR(j,i)] = TRUE;
                nColorsUsed++;
            }
        }
    }

    if (fprintf(fXPMFile, "/* XPM */\n/* %s */\nstatic char *icon[] = {\n", comment) <= 0)
        goto error;
    if (fprintf(fXPMFile, "\"%d %d %d %d\",\n",
                (int) pIcon->bmiHeader.biWidth, nHeight, nColorsUsed + 1, 2) <=0)
        goto error;

    for (i = 0; i < nColors; i++) {
        if (aColorUsed[i])
            if (fprintf(fXPMFile, "\"%.2X c #%.2X%.2X%.2X\",\n", i, pIcon->bmiColors[i].rgbRed,
                        pIcon->bmiColors[i].rgbGreen, pIcon->bmiColors[i].rgbBlue) <= 0)
                goto error;
    }
    if (fprintf(fXPMFile, "\"   c None\"") <= 0)
        goto error;

    for (i = 0; i < nHeight; i++)
    {
        if (fprintf(fXPMFile, ",\n\"") <= 0)
            goto error;
        for (j = 0; j < pIcon->bmiHeader.biWidth; j++)
        {
            if MASK(j,i)
                {
                    if (fprintf(fXPMFile, "  ") <= 0)
                        goto error;
                }
            else
                if (fprintf(fXPMFile, "%.2X", COLOR(j,i)) <= 0)
                    goto error;
        }
        if (fprintf(fXPMFile, "\"") <= 0)
            goto error;
    }
    if (fprintf(fXPMFile, "};\n") <= 0)
        goto error;

#undef MASK
#undef COLOR

215
    free(comment);
216 217 218 219
    fclose(fXPMFile);
    return TRUE;

 error:
220
    free(comment);
221 222 223 224 225
    fclose(fXPMFile);
    unlink( szXPMFileName );
    return FALSE;
}

226
static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
227 228 229 230 231
{
    ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;

    if (!sEnumRes->nIndex--)
    {
232
        *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
233
        return FALSE;
234 235
    }
    else
236
        return TRUE;
237 238
}

239
static BOOL extract_icon32(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
240 241 242
{
    HMODULE hModule;
    HRSRC hResInfo;
243
    LPCWSTR lpName = NULL;
244 245 246 247 248 249 250
    HGLOBAL hResData;
    GRPICONDIR *pIconDir;
    BITMAPINFO *pIcon;
    ENUMRESSTRUCT sEnumRes;
    int nMax = 0;
    int nMaxBits = 0;
    int i;
251
    BOOL ret = FALSE;
252

253
    hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
254
    if (!hModule)
255
    {
256 257
        WINE_ERR("LoadLibraryExW (%s) failed, error %ld\n",
                 wine_dbgstr_w(szFileName), GetLastError());
258
        return FALSE;
259 260 261 262
    }

    if (nIndex < 0)
    {
263 264 265
        hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
        WINE_TRACE("FindResourceW (%s) called, return %p, error %ld\n",
                   wine_dbgstr_w(szFileName), hResInfo, GetLastError());
266 267 268
    }
    else
    {
269
        hResInfo=NULL;
270 271
        sEnumRes.pResInfo = &hResInfo;
        sEnumRes.nIndex = nIndex;
272
        EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON, EnumResNameProc, (LONG_PTR)&sEnumRes);
273 274
    }

275
    if (hResInfo)
276
    {
277
        if ((hResData = LoadResource(hModule, hResInfo)))
278
        {
279 280 281 282
            if ((pIconDir = LockResource(hResData)))
            {
                for (i = 0; i < pIconDir->idCount; i++)
                {
283 284 285 286 287 288 289 290 291 292
		    if ((pIconDir->idEntries[i].wBitCount >= nMaxBits) && (pIconDir->idEntries[i].wBitCount <= 8))
		    {
			nMaxBits = pIconDir->idEntries[i].wBitCount;

			if ((pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth) >= nMax)
			{
			    lpName = MAKEINTRESOURCEW(pIconDir->idEntries[i].nID);
			    nMax = pIconDir->idEntries[i].bHeight * pIconDir->idEntries[i].bWidth;
			}
		    }		    
293 294
                }
            }
295

296 297
            FreeResource(hResData);
        }
298
    }
299
    else
300
    {
301 302 303
        WINE_ERR("ExtractFromEXEDLL failed, error %ld\n", GetLastError());
        FreeLibrary(hModule);
        return FALSE;
304
    }
305 306
 
    if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
307
    {
308 309 310 311 312 313 314
        if ((hResData = LoadResource(hModule, hResInfo)))
        {
            if ((pIcon = LockResource(hResData)))
            {
                if(SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
                    ret = TRUE;
            }
315

316 317
            FreeResource(hResData);
        }
318 319 320
    }

    FreeLibrary(hModule);
321
    return ret;
322 323
}

324
static BOOL ExtractFromEXEDLL(LPCWSTR szFileName, int nIndex, const char *szXPMFileName)
325
{
326 327 328 329
    if (!extract_icon32(szFileName, nIndex, szXPMFileName) /*&&
        !extract_icon16(szFileName, szXPMFileName)*/)
        return FALSE;
    return TRUE;
330 331
}

332
static int ExtractFromICO(LPCWSTR szFileName, const char *szXPMFileName)
333 334 335 336 337 338 339 340 341 342
{
    FILE *fICOFile;
    ICONDIR iconDir;
    ICONDIRENTRY *pIconDirEntry;
    int nMax = 0;
    int nIndex = 0;
    void *pIcon;
    int i;
    char *filename;

343
    filename = wine_get_unix_file_name(szFileName);
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    if (!(fICOFile = fopen(filename, "r")))
        goto error1;

    if (fread(&iconDir, sizeof (ICONDIR), 1, fICOFile) != 1)
        goto error2;
    if ((iconDir.idReserved != 0) || (iconDir.idType != 1))
        goto error2;

    if ((pIconDirEntry = malloc(iconDir.idCount * sizeof (ICONDIRENTRY))) == NULL)
        goto error2;
    if (fread(pIconDirEntry, sizeof (ICONDIRENTRY), iconDir.idCount, fICOFile) != iconDir.idCount)
        goto error3;

    for (i = 0; i < iconDir.idCount; i++)
        if ((pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) > nMax)
        {
            nIndex = i;
            nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
        }
    if ((pIcon = malloc(pIconDirEntry[nIndex].dwBytesInRes)) == NULL)
        goto error3;
    if (fseek(fICOFile, pIconDirEntry[nIndex].dwImageOffset, SEEK_SET))
        goto error4;
    if (fread(pIcon, pIconDirEntry[nIndex].dwBytesInRes, 1, fICOFile) != 1)
        goto error4;

    if(!SaveIconResAsXPM(pIcon, szXPMFileName, szFileName))
        goto error4;

    free(pIcon);
    free(pIconDirEntry);
    fclose(fICOFile);
376
    HeapFree(GetProcessHeap(), 0, filename);
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    return 1;

 error4:
    free(pIcon);
 error3:
    free(pIconDirEntry);
 error2:
    fclose(fICOFile);
 error1:
    HeapFree(GetProcessHeap(), 0, filename);
    return 0;
}

static BOOL create_default_icon( const char *filename, const char* comment )
{
    FILE *fXPM;
393
    unsigned int i;
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

    if (!(fXPM = fopen(filename, "w"))) return FALSE;
    if (fprintf(fXPM, "/* XPM */\n/* %s */\nstatic char * icon[] = {", comment) <= 0)
        goto error;
    for (i = 0; i < sizeof(wine_xpm)/sizeof(wine_xpm[0]); i++) {
        if (fprintf( fXPM, "\n\"%s\",", wine_xpm[i]) <= 0)
            goto error;
    }
    if (fprintf( fXPM, "};\n" ) <=0)
        goto error;
    fclose( fXPM );
    return TRUE;
 error:
    fclose( fXPM );
    unlink( filename );
    return FALSE;

}

static unsigned short crc16(const char* string)
{
    unsigned short crc = 0;
    int i, j, xor_poly;

    for (i = 0; string[i] != 0; i++)
    {
        char c = string[i];
        for (j = 0; j < 8; c >>= 1, j++)
        {
            xor_poly = (c ^ crc) & 1;
            crc >>= 1;
            if (xor_poly)
                crc ^= 0xa001;
        }
    }
    return crc;
}

/* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
433
static char *extract_icon( LPCWSTR path, int index)
434 435 436 437 438 439
{
    int nodefault = 1;
    unsigned short crc;
    char *iconsdir, *ico_path, *ico_name, *xpm_path;
    char* s;
    HKEY hkey;
440
    int n;
441 442

    /* Where should we save the icon? */
443
    WINE_TRACE("path=[%s] index=%d\n", wine_dbgstr_w(path), index);
444
    iconsdir=NULL;  /* Default is no icon */
445 446
    /* @@ Wine registry key: HKCU\Software\Wine\WineMenuBuilder */
    if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\WineMenuBuilder", &hkey ))
447
    {
448 449
        static const WCHAR IconsDirW[] = {'I','c','o','n','s','D','i','r',0};
        LPWSTR iconsdirW;
450
        DWORD size = 0;
451

452
        if (!RegQueryValueExW(hkey, IconsDirW, 0, NULL, NULL, &size))
453
        {
454 455
            iconsdirW = HeapAlloc(GetProcessHeap(), 0, size);
            RegQueryValueExW(hkey, IconsDirW, 0, NULL, (LPBYTE)iconsdirW, &size);
456

457
            if (!(iconsdir = wine_get_unix_file_name(iconsdirW)))
458
            {
459 460 461
                int n = WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, NULL, 0, NULL, NULL);
                iconsdir = HeapAlloc(GetProcessHeap(), 0, n);
                WideCharToMultiByte(CP_UNIXCP, 0, iconsdirW, -1, iconsdir, n, NULL, NULL);
462
            }
463
            HeapFree(GetProcessHeap(), 0, iconsdirW);
464
        }
465 466
        RegCloseKey( hkey );
    }
467 468 469 470 471 472 473 474

    if (!iconsdir)
    {
        WCHAR path[MAX_PATH];

        if (GetTempPathW(MAX_PATH, path)) iconsdir = wine_get_unix_file_name(path);
    }

475 476 477 478
    if (!iconsdir)
        return NULL;  /* No icon created */
    
    if (!*iconsdir)
479
    {
480
        HeapFree(GetProcessHeap(), 0, iconsdir);
481 482 483 484 485 486 487 488 489 490 491
        return NULL;  /* No icon created */
    }

    /* If icon path begins with a '*' then this is a deferred call */
    if (path[0] == '*')
    {
        path++;
        nodefault = 0;
    }

    /* Determine the icon base name */
492 493 494
    n = WideCharToMultiByte(CP_UNIXCP, 0, path, -1, NULL, 0, NULL, NULL);
    ico_path = HeapAlloc(GetProcessHeap(), 0, n);
    WideCharToMultiByte(CP_UNIXCP, 0, path, -1, ico_path, n, NULL, NULL);
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    s=ico_name=ico_path;
    while (*s!='\0') {
        if (*s=='/' || *s=='\\') {
            *s='\\';
            ico_name=s;
        } else {
            *s=tolower(*s);
        }
        s++;
    }
    if (*ico_name=='\\') *ico_name++='\0';
    s=strrchr(ico_name,'.');
    if (s) *s='\0';

    /* Compute the source-path hash */
    crc=crc16(ico_path);

    /* Try to treat the source file as an exe */
    xpm_path=HeapAlloc(GetProcessHeap(), 0, strlen(iconsdir)+1+4+1+strlen(ico_name)+1+12+1+3);
    sprintf(xpm_path,"%s/%04x_%s.%d.xpm",iconsdir,crc,ico_name,index);
    if (ExtractFromEXEDLL( path, index, xpm_path ))
        goto end;

    /* Must be something else, ignore the index in that case */
    sprintf(xpm_path,"%s/%04x_%s.xpm",iconsdir,crc,ico_name);
    if (ExtractFromICO( path, xpm_path))
        goto end;
    if (!nodefault)
523
        if (create_default_icon( xpm_path, ico_path ))
524 525 526 527 528 529
            goto end;

    HeapFree( GetProcessHeap(), 0, xpm_path );
    xpm_path=NULL;

 end:
Francois Gouget's avatar
Francois Gouget committed
530 531
    HeapFree(GetProcessHeap(), 0, iconsdir);
    HeapFree(GetProcessHeap(), 0, ico_path);
532 533 534 535 536 537 538
    return xpm_path;
}

static BOOL DeferToRunOnce(LPWSTR link)
{
    HKEY hkey;
    LONG r, len;
539
    static const WCHAR szRunOnce[] = {
540 541 542 543 544 545
        'S','o','f','t','w','a','r','e','\\',
        'M','i','c','r','o','s','o','f','t','\\',
        'W','i','n','d','o','w','s','\\',
        'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
        'R','u','n','O','n','c','e',0
    };
546
    static const WCHAR szFormat[] = { '%','s',' ','"','%','s','"',0 };
547 548 549 550 551
    LPWSTR buffer;
    WCHAR szExecutable[MAX_PATH];

    WINE_TRACE( "Deferring icon creation to reboot.\n");

552 553
    len = GetModuleFileNameW( 0, szExecutable, MAX_PATH );
    if (!len || len >= MAX_PATH) return FALSE;
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575

    len = ( lstrlenW( link ) + lstrlenW( szExecutable ) + 4)*sizeof(WCHAR);
    buffer = HeapAlloc( GetProcessHeap(), 0, len );
    if( !buffer )
        return FALSE;

    wsprintfW( buffer, szFormat, szExecutable, link );

    r = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szRunOnce, 0,
              NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL);
    if ( r == ERROR_SUCCESS )
    {
        r = RegSetValueExW(hkey, link, 0, REG_SZ,
                   (LPBYTE) buffer, (lstrlenW(buffer) + 1)*sizeof(WCHAR));
        RegCloseKey(hkey);
    }
    HeapFree(GetProcessHeap(), 0, buffer);

    return ! r;
}

/* This escapes \ in filenames */
576
static LPSTR escape(LPCWSTR arg)
577 578
{
    LPSTR narg, x;
579 580
    LPCWSTR esc;
    int len = 0, n;
581

582 583
    esc = arg;
    while((esc = strchrW(esc, '\\')))
584
    {
585 586 587 588 589 590 591
        esc++;
        len++;
    }

    len += WideCharToMultiByte(CP_UNIXCP, 0, arg, -1, NULL, 0, NULL, NULL);
    narg = HeapAlloc(GetProcessHeap(), 0, len);

592 593 594
    x = narg;
    while (*arg)
    {
595 596 597
        n = WideCharToMultiByte(CP_UNIXCP, 0, arg, 1, x, len, NULL, NULL);
        x += n;
        len -= n;
598 599 600 601 602 603 604 605
        if (*arg == '\\')
            *x++='\\'; /* escape \ */
        arg++;
    }
    *x = 0;
    return narg;
}

606 607 608
static int fork_and_wait( const char *linker, const char *link_name, const char *path,
                          int desktop, const char *args, const char *icon_name,
                          const char *workdir, const char *description )
609 610
{
    int pos = 0;
611
    const char *argv[20];
612
    int retcode;
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646

    WINE_TRACE( "linker app='%s' link='%s' mode=%s "
        "path='%s' args='%s' icon='%s' workdir='%s' descr='%s'\n",
        linker, link_name, desktop ? "desktop" : "menu",
        path, args, icon_name, workdir, description  );

    argv[pos++] = linker ;
    argv[pos++] = "--link";
    argv[pos++] = link_name;
    argv[pos++] = "--path";
    argv[pos++] = path;
    argv[pos++] = desktop ? "--desktop" : "--menu";
    if (args && strlen(args))
    {
        argv[pos++] = "--args";
        argv[pos++] = args;
    }
    if (icon_name)
    {
        argv[pos++] = "--icon";
        argv[pos++] = icon_name;
    }
    if (workdir && strlen(workdir))
    {
        argv[pos++] = "--workdir";
        argv[pos++] = workdir;
    }
    if (description && strlen(description))
    {
        argv[pos++] = "--descr";
        argv[pos++] = description;
    }
    argv[pos] = NULL;

647 648 649 650
    retcode=spawnvp( _P_WAIT, linker, argv );
    if (retcode!=0)
        WINE_ERR("%s returned %d\n",linker,retcode);
    return retcode;
651 652 653 654
}

static char *cleanup_link( LPCWSTR link )
{
655
    char *unix_file_name;
656
    char  *p, *link_name;
657 658 659 660 661 662 663 664 665 666 667 668 669

    unix_file_name = wine_get_unix_file_name(link);
    if (!unix_file_name)
    {
        WINE_ERR("target link %s not found\n", wine_dbgstr_w(link));
        return NULL;
    }

    link_name = unix_file_name;
    p = strrchr( link_name, '/' );
    if (p)
        link_name = p + 1;

670 671 672
    p = strrchr( link_name, '.' );
    if (p)
        *p = 0;
673 674 675 676 677 678

    p = HeapAlloc(GetProcessHeap(), 0, strlen(link_name) + 1);
    strcpy(p, link_name);
    HeapFree(GetProcessHeap(), 0, unix_file_name);

    return p;
679 680 681 682 683 684 685 686 687
}

/***********************************************************************
 *
 *           GetLinkLocation
 *
 * returns TRUE if successful
 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP
 */
688
static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc )
689
{
Francois Gouget's avatar
Francois Gouget committed
690 691
    WCHAR filename[MAX_PATH], buffer[MAX_PATH];
    DWORD len, i, r, filelen;
692
    const DWORD locations[] = {
693 694 695
        CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
        CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
        CSIDL_COMMON_STARTMENU };
696

Francois Gouget's avatar
Francois Gouget committed
697 698 699
    WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
    filelen=GetFullPathNameW( linkfile, MAX_PATH, filename, NULL );
    if (filelen==0 || filelen>MAX_PATH)
700 701
        return FALSE;

702 703
    WINE_TRACE("%s\n", wine_dbgstr_w(filename));

704
    for( i=0; i<sizeof(locations)/sizeof(locations[0]); i++ )
705 706 707 708 709
    {
        if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
            continue;

        len = lstrlenW(buffer);
Francois Gouget's avatar
Francois Gouget committed
710
        if (len >= MAX_PATH)
711 712
            continue;

Francois Gouget's avatar
Francois Gouget committed
713 714
        if (len > filelen || filename[len]!='\\')
            continue;
715 716 717
        /* do a lstrcmpinW */
        filename[len] = 0;
        r = lstrcmpiW( filename, buffer );
Francois Gouget's avatar
Francois Gouget committed
718
        filename[len] = '\\';
719 720 721 722 723 724 725 726 727 728 729
        if ( r )
            continue;

        /* return the remainder of the string and link type */
        *loc = locations[i];
        return TRUE;
    }

    return FALSE;
}

730
/* gets the target path directly or through MSI */
731 732
static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
                            LPWSTR szArgs, DWORD argsSize)
733 734 735 736 737 738
{
    IShellLinkDataList *dl = NULL;
    EXP_DARWIN_LINK *dar = NULL;
    HRESULT hr;

    szPath[0] = 0;
739 740 741
    szArgs[0] = 0;

    hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
742
    if (hr == S_OK && szPath[0])
743 744
    {
        IShellLinkW_GetArguments( sl, szArgs, argsSize );
745
        return hr;
746
    }
747 748 749 750 751 752 753 754

    hr = IShellLinkW_QueryInterface( sl, &IID_IShellLinkDataList, (LPVOID*) &dl );
    if (FAILED(hr))
        return hr;

    hr = IShellLinkDataList_CopyDataBlock( dl, EXP_DARWIN_ID_SIG, (LPVOID*) &dar );
    if (SUCCEEDED(hr))
    {
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
        WCHAR* szCmdline;
        DWORD cmdSize;

        cmdSize=0;
        hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, NULL, &cmdSize );
        if (hr == ERROR_SUCCESS)
        {
            cmdSize++;
            szCmdline = HeapAlloc( GetProcessHeap(), 0, cmdSize*sizeof(WCHAR) );
            hr = CommandLineFromMsiDescriptor( dar->szwDarwinID, szCmdline, &cmdSize );
            WINE_TRACE("      command    : %s\n", wine_dbgstr_w(szCmdline));
            if (hr == ERROR_SUCCESS)
            {
                WCHAR *s, *d;
                int bcount, in_quotes;

                /* Extract the application path */
                bcount=0;
                in_quotes=0;
                s=szCmdline;
                d=szPath;
                while (*s)
                {
                    if ((*s==0x0009 || *s==0x0020) && !in_quotes)
                    {
                        /* skip the remaining spaces */
                        do {
                            s++;
                        } while (*s==0x0009 || *s==0x0020);
                        break;
                    }
                    else if (*s==0x005c)
                    {
                        /* '\\' */
                        *d++=*s++;
                        bcount++;
                    }
                    else if (*s==0x0022)
                    {
                        /* '"' */
                        if ((bcount & 1)==0)
                        {
                            /* Preceded by an even number of '\', this is
                             * half that number of '\', plus a quote which
                             * we erase.
                             */
                            d-=bcount/2;
                            in_quotes=!in_quotes;
                            s++;
                        }
                        else
                        {
                            /* Preceded by an odd number of '\', this is
                             * half that number of '\' followed by a '"'
                             */
                            d=d-bcount/2-1;
                            *d++='"';
                            s++;
                        }
                        bcount=0;
                    }
                    else
                    {
                        /* a regular character */
                        *d++=*s++;
                        bcount=0;
                    }
                    if ((d-szPath) == pathSize)
                    {
                        /* Keep processing the path till we get to the
                         * arguments, but 'stand still'
                         */
                        d--;
                    }
                }
                /* Close the application path */
                *d=0;

                lstrcpynW(szArgs, s, argsSize);
            }
            HeapFree( GetProcessHeap(), 0, szCmdline );
        }
837 838 839 840 841 842 843
        LocalFree( dar );
    }

    IShellLinkDataList_Release( dl );
    return hr;
}

844
static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bAgain )
845
{
846 847 848 849
    char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
    char *escaped_path = NULL, *escaped_args = NULL, *escaped_description = NULL;
    WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
    WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH];
850
    int iIconId = 0, r = -1;
851
    DWORD csidl = -1;
852 853 854 855 856 857 858

    if ( !link )
    {
        WINE_ERR("Link name is null\n");
        return FALSE;
    }

859
    if( !GetLinkLocation( link, &csidl ) )
860
    {
Francois Gouget's avatar
Francois Gouget committed
861
        WINE_WARN("Unknown link location '%s'. Ignoring.\n",wine_dbgstr_w(link));
862 863
        return TRUE;
    }
864
    if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
865 866 867 868 869
    {
        WINE_WARN("Not under desktop or start menu. Ignoring.\n");
        return TRUE;
    }

870
    szWorkDir[0] = 0;
871
    IShellLinkW_GetWorkingDirectory( sl, szWorkDir, MAX_PATH );
872
    WINE_TRACE("workdir    : %s\n", wine_dbgstr_w(szWorkDir));
873 874

    szDescription[0] = 0;
875 876
    IShellLinkW_GetDescription( sl, szDescription, INFOTIPSIZE );
    WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
877

878
    get_cmdline( sl, szPath, MAX_PATH, szArgs, INFOTIPSIZE);
879 880
    WINE_TRACE("path       : %s\n", wine_dbgstr_w(szPath));
    WINE_TRACE("args       : %s\n", wine_dbgstr_w(szArgs));
881 882

    szIconPath[0] = 0;
883 884
    IShellLinkW_GetIconLocation( sl, szIconPath, MAX_PATH, &iIconId );
    WINE_TRACE("icon file  : %s\n", wine_dbgstr_w(szIconPath) );
885 886 887 888

    if( !szPath[0] )
    {
        LPITEMIDLIST pidl = NULL;
889
        IShellLinkW_GetIDList( sl, &pidl );
890
        if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
891
            WINE_TRACE("pidl path  : %s\n", wine_dbgstr_w(szPath));
892 893 894 895 896 897 898 899 900 901 902
    }

    /* extract the icon */
    if( szIconPath[0] )
        icon_name = extract_icon( szIconPath , iIconId );
    else
        icon_name = extract_icon( szPath, iIconId );

    /* fail - try once again at reboot time */
    if( !icon_name )
    {
903 904 905 906 907
        if (bAgain)
        {
            WINE_WARN("Unable to extract icon, deferring.\n");
            goto cleanup;
        }
908 909 910 911 912 913
        WINE_ERR("failed to extract icon.\n");
    }

    /* check the path */
    if( szPath[0] )
    {
914 915
        static const WCHAR exeW[] = {'.','e','x','e',0};
        WCHAR *p;
916

917
        /* check for .exe extension */
918 919 920
        if (!(p = strrchrW( szPath, '.' ))) return FALSE;
        if (strchrW( p, '\\' ) || strchrW( p, '/' )) return FALSE;
        if (lstrcmpiW( p, exeW )) return FALSE;
921 922 923

        /* convert app working dir */
        if (szWorkDir[0])
924
            work_dir = wine_get_unix_file_name( szWorkDir );
925 926 927
    }
    else
    {
928 929 930 931
        static const WCHAR startW[] = {
            '\\','c','o','m','m','a','n','d',
            '\\','s','t','a','r','t','.','e','x','e',0};

932
        /* if there's no path... try run the link itself */
933 934 935
        lstrcpynW(szArgs, link, MAX_PATH);
        GetWindowsDirectoryW(szPath, MAX_PATH);
        lstrcatW(szPath, startW);
936 937
    }

938
    link_name = cleanup_link( link );
939 940
    if( !link_name )
    {
941
        WINE_ERR("Couldn't clean up link name %s\n", wine_dbgstr_w(link));
942
        goto cleanup;
943 944 945 946
    }

    /* escape the path and parameters */
    escaped_path = escape(szPath);
947 948
    escaped_args = escape(szArgs);
    escaped_description = escape(szDescription);
949

950
    r = fork_and_wait("wineshelllink", link_name, escaped_path,
951
                      in_desktop_dir(csidl), escaped_args, icon_name,
952
                      work_dir ? work_dir : "", escaped_description);
953

954
cleanup:
955 956 957
    HeapFree( GetProcessHeap(), 0, icon_name );
    HeapFree( GetProcessHeap(), 0, work_dir );
    HeapFree( GetProcessHeap(), 0, link_name );
958 959
    HeapFree( GetProcessHeap(), 0, escaped_args );
    HeapFree( GetProcessHeap(), 0, escaped_path );
960
    HeapFree( GetProcessHeap(), 0, escaped_description );
961 962 963

    if (r)
    {
964
        WINE_ERR("failed to fork and exec wineshelllink\n" );
965 966 967 968 969 970 971
        return FALSE;
    }

    return TRUE;
}


972
static BOOL Process_Link( LPCWSTR linkname, BOOL bAgain )
973
{
974
    IShellLinkW *sl;
975 976 977
    IPersistFile *pf;
    HRESULT r;
    WCHAR fullname[MAX_PATH];
Francois Gouget's avatar
Francois Gouget committed
978 979
    DWORD len;

980 981
    WINE_TRACE("%s, again %d\n", wine_dbgstr_w(linkname), bAgain);

982 983 984 985 986 987
    if( !linkname[0] )
    {
        WINE_ERR("link name missing\n");
        return 1;
    }

Francois Gouget's avatar
Francois Gouget committed
988 989
    len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
    if (len==0 || len>MAX_PATH)
990 991 992 993 994 995 996
    {
        WINE_ERR("couldn't get full path of link file\n");
        return 1;
    }

    r = CoInitialize( NULL );
    if( FAILED( r ) )
997 998
    {
        WINE_ERR("CoInitialize failed\n");
999
        return 1;
1000
    }
1001 1002

    r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1003
                          &IID_IShellLinkW, (LPVOID *) &sl );
1004 1005 1006 1007 1008 1009
    if( FAILED( r ) )
    {
        WINE_ERR("No IID_IShellLink\n");
        return 1;
    }

1010
    r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
1011 1012 1013 1014 1015 1016 1017 1018 1019
    if( FAILED( r ) )
    {
        WINE_ERR("No IID_IPersistFile\n");
        return 1;
    }

    r = IPersistFile_Load( pf, fullname, STGM_READ );
    if( SUCCEEDED( r ) )
    {
1020
        /* If something fails (eg. Couldn't extract icon)
1021 1022
         * defer this menu entry to reboot via runonce
         */
1023
        if( ! InvokeShellLinker( sl, fullname, bAgain ) && bAgain )
1024 1025 1026 1027 1028 1029
            DeferToRunOnce( fullname );
        else
            WINE_TRACE("Success.\n");
    }

    IPersistFile_Release( pf );
1030
    IShellLinkW_Release( sl );
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

    CoUninitialize();

    return !r;
}


static CHAR *next_token( LPSTR *p )
{
    LPSTR token = NULL, t = *p;

    if( !t )
        return NULL;

    while( t && !token )
    {
        switch( *t )
        {
        case ' ':
            t++;
            continue;
        case '"':
            /* unquote the token */
            token = ++t;
            t = strchr( token, '"' );
            if( t )
                 *t++ = 0;
            break;
        case 0:
            t = NULL;
            break;
        default:
            token = t;
            t = strchr( token, ' ' );
            if( t )
                 *t++ = 0;
            break;
        }
    }
    *p = t;
    return token;
}

/***********************************************************************
 *
 *           WinMain
 */
int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
{
    LPSTR token = NULL, p;
    BOOL bAgain = FALSE;
    HANDLE hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
    int ret = 0;

    /* running multiple instances of wineshelllink
       at the same time may be dangerous */
    if( WAIT_OBJECT_0 != WaitForSingleObject( hsem, INFINITE ) )
1088 1089
    {
        CloseHandle(hsem);
1090
        return FALSE;
1091
    }
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107

    for( p = cmdline; p && *p; )
    {
        token = next_token( &p );
	if( !token )
	    break;
        if( !lstrcmpA( token, "-r" ) )
            bAgain = TRUE;
	else if( token[0] == '-' )
	{
	    WINE_ERR( "unknown option %s\n",token);
	}
        else
        {
            WCHAR link[MAX_PATH];

1108
            MultiByteToWideChar( CP_ACP, 0, token, -1, link, sizeof(link)/sizeof(WCHAR) );
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
            if( !Process_Link( link, bAgain ) )
            {
	        WINE_ERR( "failed to build menu item for %s\n",token);
	        ret = 1;
            }
        }
    }

    ReleaseSemaphore( hsem, 1, NULL );
    CloseHandle( hsem );

    return ret;
}