winemenubuilder.c 113 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
 * Copyright 2005 Bill Medland
9
 * Copyright 2008 Damjan Jovanovic
10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * 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
23
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 25
 *
 *
26 27 28 29 30 31 32
 *  This program is used to replicate the Windows desktop and start menu
 * into the native desktop's copies.  Desktop entries are merged directly
 * into the native desktop.  The Windows Start Menu corresponds to a Wine
 * entry within the native "start" menu and replicates the whole tree
 * structure of the Windows Start Menu.  Currently it does not differentiate
 * between the user's desktop/start menu and the "All Users" copies.
 *
33
 *  This program will read a Windows shortcut file using the IShellLink
34
 * interface, then create a KDE/GNOME menu entry for the shortcut.
35
 *
36
 *  winemenubuilder [ -w ] <shortcut.lnk>
37
 *
38 39 40
 *  If the -w parameter is passed, and the shortcut cannot be created,
 * this program will wait for the parent process to finish and then try
 * again. This covers the case when a ShortCut is created before the
41 42
 * executable containing its icon.
 *
43 44 45 46 47 48 49 50 51 52
 * TODO
 *  Handle data lnk files. There is no icon in the file; the icon is in 
 * the handler for the file type (or pointed to by the lnk file).  Also it 
 * might be better to use a native handler (e.g. a native acroread for pdf
 * files).  
 *  Differentiate between the user's entries and the "All Users" entries.
 * If it is possible to add the desktop files to the native system's
 * shared location for an "All Users" entry then do so.  As a suggestion the
 * shared menu Wine base could be writable to the wine group, or a wineadm 
 * group.
53 54
 *  Clean up fd.o menu icons and .directory files when the menu is deleted
 * in Windows.
55 56 57 58 59 60 61 62
 *  Associate applications under HKCR\Applications to open any MIME type
 * (by associating with application/octet-stream, or how?).
 *  Clean up fd.o MIME types when they are deleted in Windows, their icons
 * too. Very hard - once we associate them with fd.o, we can't tell whether
 * they are ours or not, and the extension <-> MIME type mapping isn't
 * one-to-one either.
 *  Wine's HKCR is broken - it doesn't merge HKCU\Software\Classes, so apps
 * that write associations there won't associate (#17019).
63 64 65 66 67 68 69 70 71 72 73 74 75
 */

#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>
76
#ifdef HAVE_FNMATCH_H
77
#include <fnmatch.h>
78
#endif
79

80
#define COBJMACROS
81
#define NONAMELESSUNION
82

83 84 85 86
#include <windows.h>
#include <shlobj.h>
#include <objidl.h>
#include <shlguid.h>
87
#include <appmgmt.h>
88
#include <tlhelp32.h>
89
#include <intshcut.h>
90
#include <shlwapi.h>
91 92
#include <initguid.h>
#include <wincodec.h>
93

94
#include "wine/unicode.h"
95
#include "wine/debug.h"
96
#include "wine/library.h"
97
#include "wine/list.h"
98
#include "wine/rbtree.h"
99 100 101

WINE_DEFAULT_DEBUG_CHANNEL(menubuilder);

102 103 104 105
#define in_desktop_dir(csidl) ((csidl)==CSIDL_DESKTOPDIRECTORY || \
                               (csidl)==CSIDL_COMMON_DESKTOPDIRECTORY)
#define in_startmenu(csidl)   ((csidl)==CSIDL_STARTMENU || \
                               (csidl)==CSIDL_COMMON_STARTMENU)
106

107 108 109
#define IS_OPTION_TRUE(ch) \
    ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
/* 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;

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
typedef struct
{
    WORD offset;
    WORD length;
    WORD flags;
    WORD id;
    WORD handle;
    WORD usage;
} NE_NAMEINFO;

typedef struct
{
    WORD  type_id;
    WORD  count;
    DWORD resloader;
} NE_TYPEINFO;

#define NE_RSCTYPE_ICON        0x8003
#define NE_RSCTYPE_GROUP_ICON  0x800e
172 173 174 175 176 177 178 179 180

#include "poppack.h"

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

181 182 183 184
struct xdg_mime_type
{
    char *mimeType;
    char *glob;
185
    char *lower_glob;
186 187 188
    struct list entry;
};

189 190 191 192 193 194
struct rb_string_entry
{
    char *string;
    struct wine_rb_entry entry;
};

195 196
DEFINE_GUID(CLSID_WICIcnsEncoder, 0x312fb6f1,0xb767,0x409d,0x8a,0x6d,0x0f,0xc1,0x54,0xd4,0xf0,0x5c);

197 198
static char *xdg_config_dir;
static char *xdg_data_dir;
199
static char *xdg_desktop_dir;
200

201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
/* Utility routines */
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;
}

static char *strdupA( const char *str )
{
    char *ret;

    if (!str) return NULL;
    if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
    return ret;
}

static char* heap_printf(const char *format, ...)
{
    va_list args;
    int size = 4096;
    char *buffer, *ret;
    int n;

    while (1)
    {
        buffer = HeapAlloc(GetProcessHeap(), 0, size);
        if (buffer == NULL)
            break;
243
        va_start(args, format);
244
        n = vsnprintf(buffer, size, format, args);
245
        va_end(args);
246 247 248 249 250 251 252 253
        if (n == -1)
            size *= 2;
        else if (n >= size)
            size = n + 1;
        else
            break;
        HeapFree(GetProcessHeap(), 0, buffer);
    }
254

255 256 257 258 259 260
    if (!buffer) return NULL;
    ret = HeapReAlloc(GetProcessHeap(), 0, buffer, strlen(buffer) + 1 );
    if (!ret) ret = buffer;
    return ret;
}

261 262 263 264 265 266 267 268 269 270 271 272 273 274
static int winemenubuilder_rb_string_compare(const void *key, const struct wine_rb_entry *entry)
{
    const struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, const struct rb_string_entry, entry);

    return strcmp((char*)key, t->string);
}

static void winemenubuilder_rb_destroy(struct wine_rb_entry *entry, void *context)
{
    struct rb_string_entry *t = WINE_RB_ENTRY_VALUE(entry, struct rb_string_entry, entry);
    HeapFree(GetProcessHeap(), 0, t->string);
    HeapFree(GetProcessHeap(), 0, t);
}

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
static void write_xml_text(FILE *file, const char *text)
{
    int i;
    for (i = 0; text[i]; i++)
    {
        if (text[i] == '&')
            fputs("&amp;", file);
        else if (text[i] == '<')
            fputs("&lt;", file);
        else if (text[i] == '>')
            fputs("&gt;", file);
        else if (text[i] == '\'')
            fputs("&apos;", file);
        else if (text[i] == '"')
            fputs("&quot;", file);
        else
            fputc(text[i], file);
    }
}

static BOOL create_directories(char *directory)
{
    BOOL ret = TRUE;
    int i;

    for (i = 0; directory[i]; i++)
    {
        if (i > 0 && directory[i] == '/')
        {
            directory[i] = 0;
            mkdir(directory, 0777);
            directory[i] = '/';
        }
    }
    if (mkdir(directory, 0777) && errno != EEXIST)
       ret = FALSE;

    return ret;
}

static char* wchars_to_utf8_chars(LPCWSTR string)
{
    char *ret;
    INT size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL);
    ret = HeapAlloc(GetProcessHeap(), 0, size);
    if (ret)
        WideCharToMultiByte(CP_UTF8, 0, string, -1, ret, size, NULL, NULL);
    return ret;
}

static char* wchars_to_unix_chars(LPCWSTR string)
{
    char *ret;
    INT size = WideCharToMultiByte(CP_UNIXCP, 0, string, -1, NULL, 0, NULL, NULL);
    ret = HeapAlloc(GetProcessHeap(), 0, size);
    if (ret)
        WideCharToMultiByte(CP_UNIXCP, 0, string, -1, ret, size, NULL, NULL);
    return ret;
}

static WCHAR* utf8_chars_to_wchars(LPCSTR string)
{
    WCHAR *ret;
    INT size = MultiByteToWideChar(CP_UTF8, 0, string, -1, NULL, 0);
    ret = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
    if (ret)
        MultiByteToWideChar(CP_UTF8, 0, string, -1, ret, size);
    return ret;
}

345 346 347 348 349 350
/* Icon extraction routines
 *
 * FIXME: should use PrivateExtractIcons and friends
 * FIXME: should not use stdio
 */

351
static HRESULT convert_to_native_icon(IStream *icoFile, int *indices, int numIndices,
352
                                      const CLSID *outputFormat, const char *outputFileName, LPCWSTR commentW)
353
{
354
    WCHAR *dosOutputFileName = NULL;
355 356 357
    IWICImagingFactory *factory = NULL;
    IWICBitmapDecoder *decoder = NULL;
    IWICBitmapEncoder *encoder = NULL;
358
    IWICBitmapScaler *scaler = NULL;
359
    IStream *outputFile = NULL;
360
    int i;
361 362
    HRESULT hr = E_FAIL;

363 364
    dosOutputFileName = wine_get_dos_file_name(outputFileName);
    if (dosOutputFileName == NULL)
365
    {
366
        WINE_ERR("error converting %s to DOS file name\n", outputFileName);
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
        goto end;
    }
    hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
        &IID_IWICImagingFactory, (void**)&factory);
    if (FAILED(hr))
    {
        WINE_ERR("error 0x%08X creating IWICImagingFactory\n", hr);
        goto end;
    }
    hr = IWICImagingFactory_CreateDecoderFromStream(factory, icoFile, NULL,
        WICDecodeMetadataCacheOnDemand, &decoder);
    if (FAILED(hr))
    {
        WINE_ERR("error 0x%08X creating IWICBitmapDecoder\n", hr);
        goto end;
    }
383 384 385 386 387 388 389 390
    if (IsEqualCLSID(outputFormat,&CLSID_WICIcnsEncoder))
    {
        hr = IWICImagingFactory_CreateBitmapScaler(factory, &scaler);
        if (FAILED(hr))
        {
            WINE_WARN("error 0x%08X creating IWICBitmapScaler\n", hr);
        }
    }
391
    hr = CoCreateInstance(outputFormat, NULL, CLSCTX_INPROC_SERVER,
392 393 394 395 396 397
        &IID_IWICBitmapEncoder, (void**)&encoder);
    if (FAILED(hr))
    {
        WINE_ERR("error 0x%08X creating bitmap encoder\n", hr);
        goto end;
    }
398
    hr = SHCreateStreamOnFileW(dosOutputFileName, STGM_CREATE | STGM_WRITE, &outputFile);
399 400
    if (FAILED(hr))
    {
401
        WINE_ERR("error 0x%08X creating output file %s\n", hr, wine_dbgstr_w(dosOutputFileName));
402 403
        goto end;
    }
404
    hr = IWICBitmapEncoder_Initialize(encoder, outputFile, WICBitmapEncoderNoCache);
405 406 407 408 409
    if (FAILED(hr))
    {
        WINE_ERR("error 0x%08X initializing encoder\n", hr);
        goto end;
    }
410

411
    for (i = 0; i < numIndices; i++)
412
    {
413 414 415 416 417 418
        IWICBitmapFrameDecode *sourceFrame = NULL;
        IWICBitmapSource *sourceBitmap = NULL;
        IWICBitmapFrameEncode *dstFrame = NULL;
        IPropertyBag2 *options = NULL;
        UINT width, height;

419
        hr = IWICBitmapDecoder_GetFrame(decoder, indices[i], &sourceFrame);
420 421
        if (FAILED(hr))
        {
422
            WINE_ERR("error 0x%08X getting frame %d\n", hr, indices[i]);
423 424 425 426 427 428 429 430
            goto endloop;
        }
        hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, (IWICBitmapSource*)sourceFrame, &sourceBitmap);
        if (FAILED(hr))
        {
            WINE_ERR("error 0x%08X converting bitmap to 32bppBGRA\n", hr);
            goto endloop;
        }
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
        if ( scaler)
        {
            IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
            if (width == 64) /* Classic Mode */
            {
                hr = IWICBitmapScaler_Initialize( scaler, sourceBitmap, 128, 128,
                                  WICBitmapInterpolationModeNearestNeighbor);
                if (FAILED(hr))
                    WINE_ERR("error 0x%08X scaling bitmap\n", hr);
                else
                {
                    IWICBitmapSource_Release(sourceBitmap);
                    IWICBitmapScaler_QueryInterface(scaler, &IID_IWICBitmapSource, (LPVOID)&sourceBitmap);
                }
            }
        }
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        hr = IWICBitmapEncoder_CreateNewFrame(encoder, &dstFrame, &options);
        if (FAILED(hr))
        {
            WINE_ERR("error 0x%08X creating encoder frame\n", hr);
            goto endloop;
        }
        hr = IWICBitmapFrameEncode_Initialize(dstFrame, options);
        if (FAILED(hr))
        {
            WINE_ERR("error 0x%08X initializing encoder frame\n", hr);
            goto endloop;
        }
        hr = IWICBitmapSource_GetSize(sourceBitmap, &width, &height);
        if (FAILED(hr))
        {
            WINE_ERR("error 0x%08X getting source bitmap size\n", hr);
            goto endloop;
        }
        hr = IWICBitmapFrameEncode_SetSize(dstFrame, width, height);
        if (FAILED(hr))
        {
            WINE_ERR("error 0x%08X setting destination bitmap size\n", hr);
            goto endloop;
        }
        hr = IWICBitmapFrameEncode_SetResolution(dstFrame, 96, 96);
        if (FAILED(hr))
        {
            WINE_ERR("error 0x%08X setting destination bitmap resolution\n", hr);
            goto endloop;
        }
        hr = IWICBitmapFrameEncode_WriteSource(dstFrame, sourceBitmap, NULL);
        if (FAILED(hr))
        {
            WINE_ERR("error 0x%08X copying bitmaps\n", hr);
            goto endloop;
        }
        hr = IWICBitmapFrameEncode_Commit(dstFrame);
        if (FAILED(hr))
        {
            WINE_ERR("error 0x%08X committing frame\n", hr);
            goto endloop;
        }
    endloop:
        if (sourceFrame)
            IWICBitmapFrameDecode_Release(sourceFrame);
        if (sourceBitmap)
            IWICBitmapSource_Release(sourceBitmap);
        if (dstFrame)
            IWICBitmapFrameEncode_Release(dstFrame);
496 497
        if (options)
            IPropertyBag2_Release(options);
498
    }
499 500

    hr = IWICBitmapEncoder_Commit(encoder);
501 502
    if (FAILED(hr))
    {
503
        WINE_ERR("error 0x%08X committing encoder\n", hr);
504 505 506 507
        goto end;
    }

end:
508
    HeapFree(GetProcessHeap(), 0, dosOutputFileName);
509 510 511 512
    if (factory)
        IWICImagingFactory_Release(factory);
    if (decoder)
        IWICBitmapDecoder_Release(decoder);
513 514
    if (scaler)
        IWICBitmapScaler_Release(scaler);
515 516 517 518
    if (encoder)
        IWICBitmapEncoder_Release(encoder);
    if (outputFile)
        IStream_Release(outputFile);
519
    return hr;
520 521
}

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
struct IconData16 {
    BYTE *fileBytes;
    DWORD fileSize;
    NE_TYPEINFO *iconResources;
    WORD alignmentShiftCount;
};

static int populate_module16_icons(struct IconData16 *iconData16, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
{
    int i, j;
    int validEntries = 0;

    for (i = 0; i < grpIconDir->idCount; i++)
    {
        BYTE *iconPtr = (BYTE*)iconData16->iconResources;
        NE_NAMEINFO *matchingIcon = NULL;
        iconPtr += sizeof(NE_TYPEINFO);
        for (j = 0; j < iconData16->iconResources->count; j++)
        {
            NE_NAMEINFO *iconInfo = (NE_NAMEINFO*)iconPtr;
542
            if ((iconPtr + sizeof(NE_NAMEINFO)) > (iconData16->fileBytes + iconData16->fileSize))
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
            {
                WINE_WARN("file too small for icon NE_NAMEINFO\n");
                break;
            }
            if (iconInfo->id == (0x8000 | grpIconDir->idEntries[i].nID))
            {
                matchingIcon = iconInfo;
                break;
            }
            iconPtr += sizeof(NE_NAMEINFO);
        }

        if (matchingIcon == NULL)
            continue;
        if (((matchingIcon->offset << iconData16->alignmentShiftCount) + grpIconDir->idEntries[i].dwBytesInRes) > iconData16->fileSize)
        {
            WINE_WARN("file too small for icon contents\n");
            break;
        }

        iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
        iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
        iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
        iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
        iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
        iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
        iconDirEntries[validEntries].dwBytesInRes = grpIconDir->idEntries[i].dwBytesInRes;
        iconDirEntries[validEntries].dwImageOffset = *iconOffset;
        validEntries++;
        memcpy(&icons[*iconOffset], &iconData16->fileBytes[matchingIcon->offset << iconData16->alignmentShiftCount], grpIconDir->idEntries[i].dwBytesInRes);
        *iconOffset += grpIconDir->idEntries[i].dwBytesInRes;
    }
    return validEntries;
}

static int populate_module_icons(HMODULE hModule, GRPICONDIR *grpIconDir, ICONDIRENTRY *iconDirEntries, BYTE *icons, SIZE_T *iconOffset)
{
    int i;
    int validEntries = 0;

    for (i = 0; i < grpIconDir->idCount; i++)
    {
        HRSRC hResInfo;
        LPCWSTR lpName = MAKEINTRESOURCEW(grpIconDir->idEntries[i].nID);
        if ((hResInfo = FindResourceW(hModule, lpName, (LPCWSTR)RT_ICON)))
        {
            HGLOBAL hResData;
            if ((hResData = LoadResource(hModule, hResInfo)))
            {
                BITMAPINFO *pIcon;
593
                DWORD size = min( grpIconDir->idEntries[i].dwBytesInRes, ((IMAGE_RESOURCE_DATA_ENTRY *)hResInfo)->Size );
594 595 596 597 598 599 600 601
                if ((pIcon = LockResource(hResData)))
                {
                    iconDirEntries[validEntries].bWidth = grpIconDir->idEntries[i].bWidth;
                    iconDirEntries[validEntries].bHeight = grpIconDir->idEntries[i].bHeight;
                    iconDirEntries[validEntries].bColorCount = grpIconDir->idEntries[i].bColorCount;
                    iconDirEntries[validEntries].bReserved = grpIconDir->idEntries[i].bReserved;
                    iconDirEntries[validEntries].wPlanes = grpIconDir->idEntries[i].wPlanes;
                    iconDirEntries[validEntries].wBitCount = grpIconDir->idEntries[i].wBitCount;
602
                    iconDirEntries[validEntries].dwBytesInRes = size;
603 604
                    iconDirEntries[validEntries].dwImageOffset = *iconOffset;
                    validEntries++;
605 606
                    memcpy(&icons[*iconOffset], pIcon, size);
                    *iconOffset += size;
607 608 609 610 611 612 613 614 615
                }
                FreeResource(hResData);
            }
        }
    }
    return validEntries;
}

static IStream *add_module_icons_to_stream(struct IconData16 *iconData16, HMODULE hModule, GRPICONDIR *grpIconDir)
616
{
617 618 619 620
    int i;
    SIZE_T iconsSize = 0;
    BYTE *icons = NULL;
    ICONDIRENTRY *iconDirEntries = NULL;
621 622
    IStream *stream = NULL;
    HRESULT hr = E_FAIL;
623 624 625 626 627 628 629 630 631 632
    ULONG bytesWritten;
    ICONDIR iconDir;
    SIZE_T iconOffset;
    int validEntries = 0;
    LARGE_INTEGER zero;

    for (i = 0; i < grpIconDir->idCount; i++)
        iconsSize += grpIconDir->idEntries[i].dwBytesInRes;
    icons = HeapAlloc(GetProcessHeap(), 0, iconsSize);
    if (icons == NULL)
633 634 635 636 637
    {
        WINE_ERR("out of memory allocating icon\n");
        goto end;
    }

638 639 640 641 642 643 644 645
    iconDirEntries = HeapAlloc(GetProcessHeap(), 0, grpIconDir->idCount*sizeof(ICONDIRENTRY));
    if (iconDirEntries == NULL)
    {
        WINE_ERR("out of memory allocating icon dir entries\n");
        goto end;
    }

    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
646 647
    if (FAILED(hr))
    {
648
        WINE_ERR("error creating icon stream\n");
649 650
        goto end;
    }
651 652

    iconOffset = 0;
653 654 655 656
    if (iconData16)
        validEntries = populate_module16_icons(iconData16, grpIconDir, iconDirEntries, icons, &iconOffset);
    else if (hModule)
        validEntries = populate_module_icons(hModule, grpIconDir, iconDirEntries, icons, &iconOffset);
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

    if (validEntries == 0)
    {
        WINE_ERR("no valid icon entries\n");
        goto end;
    }

    iconDir.idReserved = 0;
    iconDir.idType = 1;
    iconDir.idCount = validEntries;
    hr = IStream_Write(stream, &iconDir, sizeof(iconDir), &bytesWritten);
    if (FAILED(hr) || bytesWritten != sizeof(iconDir))
    {
        WINE_ERR("error 0x%08X writing icon stream\n", hr);
        goto end;
    }
    for (i = 0; i < validEntries; i++)
        iconDirEntries[i].dwImageOffset += sizeof(ICONDIR) + validEntries*sizeof(ICONDIRENTRY);
    hr = IStream_Write(stream, iconDirEntries, validEntries*sizeof(ICONDIRENTRY), &bytesWritten);
    if (FAILED(hr) || bytesWritten != validEntries*sizeof(ICONDIRENTRY))
    {
        WINE_ERR("error 0x%08X writing icon dir entries to stream\n", hr);
        goto end;
    }
    hr = IStream_Write(stream, icons, iconOffset, &bytesWritten);
    if (FAILED(hr) || bytesWritten != iconOffset)
    {
        WINE_ERR("error 0x%08X writing icon images to stream\n", hr);
        goto end;
    }
    zero.QuadPart = 0;
    hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
689 690

end:
691 692
    HeapFree(GetProcessHeap(), 0, icons);
    HeapFree(GetProcessHeap(), 0, iconDirEntries);
693 694
    if (FAILED(hr) && stream != NULL)
    {
695
        IStream_Release(stream);
696 697 698
        stream = NULL;
    }
    return stream;
699 700
}

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 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
static HRESULT open_module16_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
{
    HANDLE hFile = INVALID_HANDLE_VALUE;
    HANDLE hFileMapping = NULL;
    DWORD fileSize;
    BYTE *fileBytes = NULL;
    IMAGE_DOS_HEADER *dosHeader;
    IMAGE_OS2_HEADER *neHeader;
    BYTE *rsrcTab;
    NE_TYPEINFO *iconGroupResources;
    NE_TYPEINFO *iconResources;
    NE_NAMEINFO *iconDirPtr;
    GRPICONDIR *iconDir;
    WORD alignmentShiftCount;
    struct IconData16 iconData16;
    HRESULT hr = E_FAIL;

    hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
        OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        WINE_WARN("opening %s failed with error %d\n", wine_dbgstr_w(szFileName), GetLastError());
        goto end;
    }

    hFileMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
    if (hFileMapping == NULL)
    {
        WINE_WARN("CreateFileMapping failed, error %d\n", GetLastError());
        goto end;
    }

    fileSize = GetFileSize(hFile, NULL);

    fileBytes = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
    if (fileBytes == NULL)
    {
        WINE_WARN("MapViewOfFile failed, error %d\n", GetLastError());
        goto end;
    }

    dosHeader = (IMAGE_DOS_HEADER*)fileBytes;
    if (sizeof(IMAGE_DOS_HEADER) >= fileSize || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
    {
        WINE_WARN("file too small for MZ header\n");
        goto end;
    }

    neHeader = (IMAGE_OS2_HEADER*)(fileBytes + dosHeader->e_lfanew);
    if ((((BYTE*)neHeader) + sizeof(IMAGE_OS2_HEADER)) > (fileBytes + fileSize) ||
        neHeader->ne_magic != IMAGE_OS2_SIGNATURE)
    {
        WINE_WARN("file too small for NE header\n");
        goto end;
    }

    rsrcTab = ((BYTE*)neHeader) + neHeader->ne_rsrctab;
    if ((rsrcTab + 2) > (fileBytes + fileSize))
    {
        WINE_WARN("file too small for resource table\n");
        goto end;
    }

    alignmentShiftCount = *(WORD*)rsrcTab;
    rsrcTab += 2;
    iconGroupResources = NULL;
    iconResources = NULL;
    for (;;)
    {
        NE_TYPEINFO *neTypeInfo = (NE_TYPEINFO*)rsrcTab;
        if ((rsrcTab + sizeof(NE_TYPEINFO)) > (fileBytes + fileSize))
        {
            WINE_WARN("file too small for resource table\n");
            goto end;
        }
        if (neTypeInfo->type_id == 0)
            break;
        else if (neTypeInfo->type_id == NE_RSCTYPE_GROUP_ICON)
            iconGroupResources = neTypeInfo;
        else if (neTypeInfo->type_id == NE_RSCTYPE_ICON)
            iconResources = neTypeInfo;
        rsrcTab += sizeof(NE_TYPEINFO) + neTypeInfo->count*sizeof(NE_NAMEINFO);
    }
    if (iconGroupResources == NULL)
    {
        WINE_WARN("no group icon resource type found\n");
        goto end;
    }
    if (iconResources == NULL)
    {
        WINE_WARN("no icon resource type found\n");
        goto end;
    }

    if (nIndex >= iconGroupResources->count)
    {
        WINE_WARN("icon index out of range\n");
        goto end;
    }

    iconDirPtr = (NE_NAMEINFO*)(((BYTE*)iconGroupResources) + sizeof(NE_TYPEINFO) + nIndex*sizeof(NE_NAMEINFO));
    if ((((BYTE*)iconDirPtr) + sizeof(NE_NAMEINFO)) > (fileBytes + fileSize))
    {
804
        WINE_WARN("file too small for icon group NE_NAMEINFO\n");
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
        goto end;
    }
    iconDir = (GRPICONDIR*)(fileBytes + (iconDirPtr->offset << alignmentShiftCount));
    if ((((BYTE*)iconDir) + sizeof(GRPICONDIR) + iconDir->idCount*sizeof(GRPICONDIRENTRY)) > (fileBytes + fileSize))
    {
        WINE_WARN("file too small for GRPICONDIR\n");
        goto end;
    }

    iconData16.fileBytes = fileBytes;
    iconData16.fileSize = fileSize;
    iconData16.iconResources = iconResources;
    iconData16.alignmentShiftCount = alignmentShiftCount;
    *ppStream = add_module_icons_to_stream(&iconData16, NULL, iconDir);
    if (*ppStream)
        hr = S_OK;

end:
    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);
    if (hFileMapping != NULL)
        CloseHandle(hFileMapping);
    if (fileBytes != NULL)
        UnmapViewOfFile(fileBytes);
    return hr;
}

832
static BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam)
833 834 835 836 837
{
    ENUMRESSTRUCT *sEnumRes = (ENUMRESSTRUCT *) lParam;

    if (!sEnumRes->nIndex--)
    {
838
        *sEnumRes->pResInfo = FindResourceW(hModule, lpszName, (LPCWSTR)RT_GROUP_ICON);
839
        return FALSE;
840 841
    }
    else
842
        return TRUE;
843 844
}

845
static HRESULT open_module_icon(LPCWSTR szFileName, int nIndex, IStream **ppStream)
846 847 848 849 850 851
{
    HMODULE hModule;
    HRSRC hResInfo;
    HGLOBAL hResData;
    GRPICONDIR *pIconDir;
    ENUMRESSTRUCT sEnumRes;
852
    HRESULT hr = E_FAIL;
853

854
    hModule = LoadLibraryExW(szFileName, 0, LOAD_LIBRARY_AS_DATAFILE);
855
    if (!hModule)
856
    {
857 858 859 860 861 862 863 864
        if (GetLastError() == ERROR_BAD_EXE_FORMAT)
            return open_module16_icon(szFileName, nIndex, ppStream);
        else
        {
            WINE_WARN("LoadLibraryExW (%s) failed, error %d\n",
                     wine_dbgstr_w(szFileName), GetLastError());
            return HRESULT_FROM_WIN32(GetLastError());
        }
865 866 867 868
    }

    if (nIndex < 0)
    {
869
        hResInfo = FindResourceW(hModule, MAKEINTRESOURCEW(-nIndex), (LPCWSTR)RT_GROUP_ICON);
870
        WINE_TRACE("FindResourceW (%s) called, return %p, error %d\n",
871
                   wine_dbgstr_w(szFileName), hResInfo, GetLastError());
872 873 874
    }
    else
    {
875
        hResInfo=NULL;
876 877
        sEnumRes.pResInfo = &hResInfo;
        sEnumRes.nIndex = nIndex;
878
        if (!EnumResourceNamesW(hModule, (LPCWSTR)RT_GROUP_ICON,
879
                                EnumResNameProc, (LONG_PTR)&sEnumRes) &&
880
            sEnumRes.nIndex != -1)
881
        {
882
            WINE_TRACE("EnumResourceNamesW failed, error %d\n", GetLastError());
883
        }
884 885
    }

886
    if (hResInfo)
887
    {
888
        if ((hResData = LoadResource(hModule, hResInfo)))
889
        {
890 891
            if ((pIconDir = LockResource(hResData)))
            {
892
                *ppStream = add_module_icons_to_stream(0, hModule, pIconDir);
893 894
                if (*ppStream)
                    hr = S_OK;
895
            }
896

897 898
            FreeResource(hResData);
        }
899
    }
900
    else
901
    {
902
        WINE_WARN("found no icon\n");
903
        FreeLibrary(hModule);
904
        return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
905 906 907
    }

    FreeLibrary(hModule);
908
    return hr;
909 910
}

911
static HRESULT read_ico_direntries(IStream *icoStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
912 913
{
    ICONDIR iconDir;
914
    ULONG bytesRead;
915
    HRESULT hr;
916

917 918 919
    *ppIconDirEntries = NULL;

    hr = IStream_Read(icoStream, &iconDir, sizeof(ICONDIR), &bytesRead);
920
    if (FAILED(hr) || bytesRead != sizeof(ICONDIR) ||
921 922
        (iconDir.idReserved != 0) || (iconDir.idType != 1))
    {
923 924 925
        WINE_WARN("Invalid ico file format (hr=0x%08X, bytesRead=%d)\n", hr, bytesRead);
        hr = E_FAIL;
        goto end;
926
    }
927
    *numEntries = iconDir.idCount;
928

929
    if ((*ppIconDirEntries = HeapAlloc(GetProcessHeap(), 0, sizeof(ICONDIRENTRY)*iconDir.idCount)) == NULL)
930 931 932 933
    {
        hr = E_OUTOFMEMORY;
        goto end;
    }
934
    hr = IStream_Read(icoStream, *ppIconDirEntries, sizeof(ICONDIRENTRY)*iconDir.idCount, &bytesRead);
935 936 937 938 939
    if (FAILED(hr) || bytesRead != sizeof(ICONDIRENTRY)*iconDir.idCount)
    {
        if (SUCCEEDED(hr)) hr = E_FAIL;
        goto end;
    }
940

941 942 943 944 945 946
end:
    if (FAILED(hr))
        HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
    return hr;
}

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
static HRESULT validate_ico(IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
{
    HRESULT hr;

    hr = read_ico_direntries(*ppStream, ppIconDirEntries, numEntries);
    if (SUCCEEDED(hr))
    {
        if (*numEntries)
            return hr;
        HeapFree(GetProcessHeap(), 0, *ppIconDirEntries);
        *ppIconDirEntries = NULL;
    }
    IStream_Release(*ppStream);
    *ppStream = NULL;
    return E_FAIL;
}

static HRESULT write_native_icon(IStream *iconStream, ICONDIRENTRY *pIconDirEntry,
                                 int numEntries, const char *icon_name, LPCWSTR szFileName)
966 967 968 969 970 971 972 973
{
    int nMax = 0, nMaxBits = 0;
    int nIndex = 0;
    int i;
    LARGE_INTEGER position;
    HRESULT hr;

    for (i = 0; i < numEntries; i++)
974 975 976
    {
        WINE_TRACE("[%d]: %d x %d @ %d\n", i, pIconDirEntry[i].bWidth, pIconDirEntry[i].bHeight, pIconDirEntry[i].wBitCount);
        if (pIconDirEntry[i].wBitCount >= nMaxBits &&
977
            (pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth) >= nMax)
978 979 980
        {
            nIndex = i;
            nMax = pIconDirEntry[i].bHeight * pIconDirEntry[i].bWidth;
981
            nMaxBits = pIconDirEntry[i].wBitCount;
982
        }
983 984 985
    }
    WINE_TRACE("Selected: %d\n", nIndex);

986 987
    position.QuadPart = 0;
    hr = IStream_Seek(iconStream, position, STREAM_SEEK_SET, NULL);
988 989
    if (FAILED(hr)) return hr;
    return convert_to_native_icon(iconStream, &nIndex, 1, &CLSID_WICPngEncoder, icon_name, szFileName);
990 991
}

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
static WCHAR* assoc_query(ASSOCSTR assocStr, LPCWSTR name, LPCWSTR extra)
{
    HRESULT hr;
    WCHAR *value = NULL;
    DWORD size = 0;
    hr = AssocQueryStringW(0, assocStr, name, extra, NULL, &size);
    if (SUCCEEDED(hr))
    {
        value = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
        if (value)
        {
            hr = AssocQueryStringW(0, assocStr, name, extra, value, &size);
            if (FAILED(hr))
            {
                HeapFree(GetProcessHeap(), 0, value);
                value = NULL;
            }
        }
    }
    return value;
}

1014
static HRESULT open_file_type_icon(LPCWSTR szFileName, IStream **ppStream)
1015
{
1016
    static const WCHAR openW[] = {'o','p','e','n',0};
1017 1018 1019
    WCHAR *extension;
    WCHAR *icon = NULL;
    WCHAR *comma;
1020
    WCHAR *executable = NULL;
1021
    int index = 0;
1022
    HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
1023 1024 1025 1026 1027 1028

    extension = strrchrW(szFileName, '.');
    if (extension == NULL)
        goto end;

    icon = assoc_query(ASSOCSTR_DEFAULTICON, extension, NULL);
1029 1030 1031 1032 1033 1034 1035 1036
    if (icon)
    {
        comma = strrchrW(icon, ',');
        if (comma)
        {
            *comma = 0;
            index = atoiW(comma + 1);
        }
1037
        hr = open_module_icon(icon, index, ppStream);
1038 1039
    }
    else
1040
    {
1041
        executable = assoc_query(ASSOCSTR_EXECUTABLE, extension, openW);
1042
        if (executable)
1043
            hr = open_module_icon(executable, 0, ppStream);
1044 1045 1046 1047
    }

end:
    HeapFree(GetProcessHeap(), 0, icon);
1048
    HeapFree(GetProcessHeap(), 0, executable);
1049
    return hr;
1050 1051
}

1052
static HRESULT open_default_icon(IStream **ppStream)
1053
{
1054
    static const WCHAR user32W[] = {'u','s','e','r','3','2',0};
1055

1056 1057 1058
    return open_module_icon(user32W, -(INT_PTR)IDI_WINLOGO, ppStream);
}

1059
static HRESULT open_icon(LPCWSTR filename, int index, BOOL bWait, IStream **ppStream, ICONDIRENTRY **ppIconDirEntries, int *numEntries)
1060 1061 1062 1063 1064 1065
{
    HRESULT hr;

    hr = open_module_icon(filename, index, ppStream);
    if (FAILED(hr))
    {
1066 1067 1068 1069 1070 1071 1072 1073
        if(bWait && hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
        {
            WINE_WARN("Can't find file: %s, give a chance to parent process to create it\n",
                                    wine_dbgstr_w(filename));
            return hr;
        }
        else
        {
1074 1075
            /* This might be a raw .ico file */
            hr = SHCreateStreamOnFileW(filename, STGM_READ, ppStream);
1076
        }
1077
    }
1078 1079 1080
    if (SUCCEEDED(hr))
        hr = validate_ico(ppStream, ppIconDirEntries, numEntries);

1081
    if (FAILED(hr))
1082
    {
1083
        hr = open_file_type_icon(filename, ppStream);
1084 1085 1086
        if (SUCCEEDED(hr))
            hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
    }
1087
    if (FAILED(hr) && !bWait)
1088
    {
1089
        hr = open_default_icon(ppStream);
1090 1091 1092
        if (SUCCEEDED(hr))
            hr = validate_ico(ppStream, ppIconDirEntries, numEntries);
    }
1093
    return hr;
1094 1095
}

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
static char* compute_native_identifier(int exeIndex, LPCWSTR icoPathW)
{
    char* nativeIdentifier;
    char *icoPathA;
    unsigned short crc;
    char *basename, *ext;

    icoPathA = wchars_to_utf8_chars(icoPathW);
    if (icoPathA == NULL)
        return NULL;

    crc = crc16(icoPathA);
    basename = strrchr(icoPathA, '\\');
    if (basename == NULL)
        basename = icoPathA;
    else
    {
        *basename = 0;
        basename++;
    }
    ext = strrchr(basename, '.');
    if (ext)
        *ext = 0;

    nativeIdentifier = heap_printf("%04X_%s.%d", crc, basename, exeIndex);
    HeapFree(GetProcessHeap(), 0, icoPathA);
    return nativeIdentifier;
}

1125
#ifdef __APPLE__
1126 1127 1128 1129 1130 1131 1132 1133 1134
#define ICNS_SLOTS 6

static inline int size_to_slot(int size)
{
    switch (size)
    {
        case 16: return 0;
        case 32: return 1;
        case 48: return 2;
1135
        case 64: return -2;  /* Classic Mode */
1136 1137 1138 1139 1140 1141 1142 1143
        case 128: return 3;
        case 256: return 4;
        case 512: return 5;
    }

    return -1;
}

1144 1145
#define CLASSIC_SLOT 3

1146
static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
1147
                                   int numEntries, int exeIndex, LPCWSTR icoPathW,
1148 1149
                                   const char *destFilename, char **nativeIdentifier)
{
1150 1151 1152
    struct {
        int index;
        int maxBits;
1153
        BOOL scaled;
1154 1155 1156
    } best[ICNS_SLOTS];
    int indexes[ICNS_SLOTS];
    int i;
1157
    const char* tmpdir;
1158 1159 1160 1161
    char *icnsPath = NULL;
    LARGE_INTEGER zero;
    HRESULT hr;

1162 1163 1164 1165 1166 1167 1168 1169
    for (i = 0; i < ICNS_SLOTS; i++)
    {
        best[i].index = -1;
        best[i].maxBits = 0;
    }
    for (i = 0; i < numEntries; i++)
    {
        int slot;
1170 1171
        int width = iconDirEntries[i].bWidth ? iconDirEntries[i].bWidth : 256;
        int height = iconDirEntries[i].bHeight ? iconDirEntries[i].bHeight : 256;
1172
        BOOL scaled = FALSE;
1173

1174
        WINE_TRACE("[%d]: %d x %d @ %d\n", i, width, height, iconDirEntries[i].wBitCount);
1175 1176
        if (height != width)
            continue;
1177
        slot = size_to_slot(width);
1178 1179 1180 1181 1182 1183
        if (slot == -2)
        {
            scaled = TRUE;
            slot = CLASSIC_SLOT;
        }
        else if (slot < 0)
1184
            continue;
1185 1186 1187
        if (scaled && best[slot].maxBits && !best[slot].scaled)
            continue; /* don't replace unscaled with scaled */
        if (iconDirEntries[i].wBitCount >= best[slot].maxBits || (!scaled && best[slot].scaled))
1188 1189 1190
        {
            best[slot].index = i;
            best[slot].maxBits = iconDirEntries[i].wBitCount;
1191
            best[slot].scaled = scaled;
1192 1193
        }
    }
1194 1195 1196 1197 1198 1199
    /* remove the scaled icon if a larger unscaled icon exists */
    if (best[CLASSIC_SLOT].scaled)
    {
        for (i = CLASSIC_SLOT+1; i < ICNS_SLOTS; i++)
            if (best[i].index >= 0 && !best[i].scaled)
            {
1200
                best[CLASSIC_SLOT].index = -1;
1201 1202 1203 1204
                break;
            }
    }

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
    numEntries = 0;
    for (i = 0; i < ICNS_SLOTS; i++)
    {
        if (best[i].index >= 0)
        {
            indexes[numEntries] = best[i].index;
            numEntries++;
        }
    }

1215 1216 1217 1218 1219
    if (destFilename)
        *nativeIdentifier = heap_printf("%s", destFilename);
    else
        *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
    if (*nativeIdentifier == NULL)
1220 1221 1222 1223
    {
        hr = E_OUTOFMEMORY;
        goto end;
    }
1224 1225
    if (!(tmpdir = getenv("TMPDIR"))) tmpdir = "/tmp";
    icnsPath = heap_printf("%s/%s.icns", tmpdir, *nativeIdentifier);
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
    if (icnsPath == NULL)
    {
        hr = E_OUTOFMEMORY;
        WINE_WARN("out of memory creating ICNS path\n");
        goto end;
    }
    zero.QuadPart = 0;
    hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
    {
        WINE_WARN("seeking icon stream failed, error 0x%08X\n", hr);
        goto end;
    }
1239
    hr = convert_to_native_icon(icoStream, indexes, numEntries, &CLSID_WICIcnsEncoder,
1240 1241 1242 1243 1244 1245 1246 1247 1248
                                icnsPath, icoPathW);
    if (FAILED(hr))
    {
        WINE_WARN("converting %s to %s failed, error 0x%08X\n",
            wine_dbgstr_w(icoPathW), wine_dbgstr_a(icnsPath), hr);
        goto end;
    }

end:
1249
    HeapFree(GetProcessHeap(), 0, icnsPath);
1250 1251 1252
    return hr;
}
#else
1253 1254 1255 1256
static void refresh_icon_cache(const char *iconsDir)
{
    /* The icon theme spec only requires the mtime on the "toplevel"
     * directory (whatever that is) to be changed for a refresh,
1257 1258
     * but on GNOME you have to create a file in that directory
     * instead. Creating a file also works on KDE, Xfce and LXDE.
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
     */
    char *filename = heap_printf("%s/.wine-refresh-XXXXXX", iconsDir);
    if (filename != NULL)
    {
        int fd = mkstemps(filename, 0);
        if (fd >= 0)
        {
            close(fd);
            unlink(filename);
        }
        HeapFree(GetProcessHeap(), 0, filename);
    }
}

1273 1274
static HRESULT platform_write_icon(IStream *icoStream, ICONDIRENTRY *iconDirEntries,
                                   int numEntries, int exeIndex, LPCWSTR icoPathW,
1275
                                   const char *destFilename, char **nativeIdentifier)
1276
{
1277
    int i;
1278 1279 1280
    char *iconsDir = NULL;
    HRESULT hr = S_OK;
    LARGE_INTEGER zero;
1281

1282
    if (destFilename)
1283
        *nativeIdentifier = heap_printf("%s", destFilename);
1284
    else
1285
        *nativeIdentifier = compute_native_identifier(exeIndex, icoPathW);
1286 1287 1288 1289 1290
    if (*nativeIdentifier == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto end;
    }
1291
    iconsDir = heap_printf("%s/icons/hicolor", xdg_data_dir);
1292
    if (iconsDir == NULL)
1293
    {
1294 1295
        hr = E_OUTOFMEMORY;
        goto end;
1296
    }
1297 1298

    for (i = 0; i < numEntries; i++)
1299
    {
1300
        int bestIndex = i;
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
        int j;
        BOOLEAN duplicate = FALSE;
        int w, h;
        char *iconDir = NULL;
        char *pngPath = NULL;

        WINE_TRACE("[%d]: %d x %d @ %d\n", i, iconDirEntries[i].bWidth,
            iconDirEntries[i].bHeight, iconDirEntries[i].wBitCount);

        for (j = 0; j < i; j++)
        {
            if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
                iconDirEntries[j].bHeight == iconDirEntries[i].bHeight)
            {
                duplicate = TRUE;
                break;
            }
        }
        if (duplicate)
            continue;
1321
        for (j = i + 1; j < numEntries; j++)
1322 1323 1324
        {
            if (iconDirEntries[j].bWidth == iconDirEntries[i].bWidth &&
                iconDirEntries[j].bHeight == iconDirEntries[i].bHeight &&
1325
                iconDirEntries[j].wBitCount >= iconDirEntries[bestIndex].wBitCount)
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
            {
                bestIndex = j;
            }
        }
        WINE_TRACE("Selected: %d\n", bestIndex);

        w = iconDirEntries[bestIndex].bWidth ? iconDirEntries[bestIndex].bWidth : 256;
        h = iconDirEntries[bestIndex].bHeight ? iconDirEntries[bestIndex].bHeight : 256;
        iconDir = heap_printf("%s/%dx%d/apps", iconsDir, w, h);
        if (iconDir == NULL)
        {
            hr = E_OUTOFMEMORY;
            goto endloop;
        }
        create_directories(iconDir);
        pngPath = heap_printf("%s/%s.png", iconDir, *nativeIdentifier);
        if (pngPath == NULL)
        {
            hr = E_OUTOFMEMORY;
            goto endloop;
        }
        zero.QuadPart = 0;
        hr = IStream_Seek(icoStream, zero, STREAM_SEEK_SET, NULL);
        if (FAILED(hr))
            goto endloop;
        hr = convert_to_native_icon(icoStream, &bestIndex, 1, &CLSID_WICPngEncoder,
                                    pngPath, icoPathW);

    endloop:
        HeapFree(GetProcessHeap(), 0, iconDir);
        HeapFree(GetProcessHeap(), 0, pngPath);
1357
    }
1358
    refresh_icon_cache(iconsDir);
1359 1360 1361 1362 1363

end:
    HeapFree(GetProcessHeap(), 0, iconsDir);
    return hr;
}
1364
#endif /* defined(__APPLE__) */
1365 1366 1367 1368 1369

/* extract an icon from an exe or icon file; helper for IPersistFile_fnSave */
static char *extract_icon(LPCWSTR icoPathW, int index, const char *destFilename, BOOL bWait)
{
    IStream *stream = NULL;
1370 1371
    ICONDIRENTRY *pIconDirEntries = NULL;
    int numEntries;
1372 1373 1374 1375
    HRESULT hr;
    char *nativeIdentifier = NULL;

    WINE_TRACE("path=[%s] index=%d destFilename=[%s]\n", wine_dbgstr_w(icoPathW), index, wine_dbgstr_a(destFilename));
1376

1377
    hr = open_icon(icoPathW, index, bWait, &stream, &pIconDirEntries, &numEntries);
1378 1379 1380 1381 1382
    if (FAILED(hr))
    {
        WINE_WARN("opening icon %s index %d failed, hr=0x%08X\n", wine_dbgstr_w(icoPathW), index, hr);
        goto end;
    }
1383
    hr = platform_write_icon(stream, pIconDirEntries, numEntries, index, icoPathW, destFilename, &nativeIdentifier);
1384 1385
    if (FAILED(hr))
        WINE_WARN("writing icon failed, error 0x%08X\n", hr);
1386

1387
end:
1388 1389
    if (stream)
        IStream_Release(stream);
1390
    HeapFree(GetProcessHeap(), 0, pIconDirEntries);
1391 1392 1393 1394 1395 1396
    if (FAILED(hr))
    {
        HeapFree(GetProcessHeap(), 0, nativeIdentifier);
        nativeIdentifier = NULL;
    }
    return nativeIdentifier;
1397 1398
}

1399 1400
static HKEY open_menus_reg_key(void)
{
1401
    static const WCHAR Software_Wine_FileOpenMenuFilesW[] = {
1402 1403
        'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','M','e','n','u','F','i','l','e','s',0};
    HKEY assocKey;
1404
    DWORD ret;
1405
    ret = RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenMenuFilesW, &assocKey);
1406
    if (ret == ERROR_SUCCESS)
1407
        return assocKey;
1408
    SetLastError(ret);
1409 1410 1411
    return NULL;
}

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
static DWORD register_menus_entry(const char *unix_file, const char *windows_file)
{
    WCHAR *unix_fileW;
    WCHAR *windows_fileW;
    INT size;
    DWORD ret;

    size = MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, NULL, 0);
    unix_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
    if (unix_fileW)
    {
        MultiByteToWideChar(CP_UNIXCP, 0, unix_file, -1, unix_fileW, size);
        size = MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, NULL, 0);
        windows_fileW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
        if (windows_fileW)
        {
            HKEY hkey;
            MultiByteToWideChar(CP_UNIXCP, 0, windows_file, -1, windows_fileW, size);
            hkey = open_menus_reg_key();
            if (hkey)
            {
                ret = RegSetValueExW(hkey, unix_fileW, 0, REG_SZ, (const BYTE*)windows_fileW,
                    (strlenW(windows_fileW) + 1) * sizeof(WCHAR));
                RegCloseKey(hkey);
            }
            else
                ret = GetLastError();
            HeapFree(GetProcessHeap(), 0, windows_fileW);
        }
        else
            ret = ERROR_NOT_ENOUGH_MEMORY;
        HeapFree(GetProcessHeap(), 0, unix_fileW);
    }
    else
        ret = ERROR_NOT_ENOUGH_MEMORY;
    return ret;
}

1450 1451
static BOOL write_desktop_entry(const char *unix_link, const char *location, const char *linkname,
                                const char *path, const char *args, const char *descr,
1452
                                const char *workdir, const char *icon, const char *wmclass)
1453 1454 1455
{
    FILE *file;

1456
    WINE_TRACE("(%s,%s,%s,%s,%s,%s,%s,%s,%s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(location),
1457
               wine_dbgstr_a(linkname), wine_dbgstr_a(path), wine_dbgstr_a(args),
1458 1459
               wine_dbgstr_a(descr), wine_dbgstr_a(workdir), wine_dbgstr_a(icon),
               wine_dbgstr_a(wmclass));
1460 1461 1462 1463 1464 1465 1466

    file = fopen(location, "w");
    if (file == NULL)
        return FALSE;

    fprintf(file, "[Desktop Entry]\n");
    fprintf(file, "Name=%s\n", linkname);
1467
    fprintf(file, "Exec=env WINEPREFIX=\"%s\" wine %s %s\n",
1468 1469
            wine_get_config_dir(), path, args);
    fprintf(file, "Type=Application\n");
1470
    fprintf(file, "StartupNotify=true\n");
1471
    if (descr && *descr)
1472
        fprintf(file, "Comment=%s\n", descr);
1473
    if (workdir && *workdir)
1474
        fprintf(file, "Path=%s\n", workdir);
1475
    if (icon && *icon)
1476
        fprintf(file, "Icon=%s\n", icon);
1477
    if (wmclass && *wmclass)
1478
        fprintf(file, "StartupWMClass=%s\n", wmclass);
1479 1480

    fclose(file);
1481 1482 1483

    if (unix_link)
    {
1484 1485
        DWORD ret = register_menus_entry(location, unix_link);
        if (ret != ERROR_SUCCESS)
1486 1487 1488
            return FALSE;
    }

1489 1490 1491
    return TRUE;
}

1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
static BOOL write_directory_entry(const char *directory, const char *location)
{
    FILE *file;

    WINE_TRACE("(%s,%s)\n", wine_dbgstr_a(directory), wine_dbgstr_a(location));

    file = fopen(location, "w");
    if (file == NULL)
        return FALSE;

    fprintf(file, "[Desktop Entry]\n");
    fprintf(file, "Type=Directory\n");
    if (strcmp(directory, "wine") == 0)
    {
        fprintf(file, "Name=Wine\n");
        fprintf(file, "Icon=wine\n");
    }
    else
    {
        fprintf(file, "Name=%s\n", directory);
        fprintf(file, "Icon=folder\n");
    }

    fclose(file);
    return TRUE;
}

1519
static BOOL write_menu_file(const char *unix_link, const char *filename)
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
{
    char *tempfilename;
    FILE *tempfile = NULL;
    char *lastEntry;
    char *name = NULL;
    char *menuPath = NULL;
    int i;
    int count = 0;
    BOOL ret = FALSE;

    WINE_TRACE("(%s)\n", wine_dbgstr_a(filename));

    while (1)
    {
1534
        tempfilename = heap_printf("%s/wine-menu-XXXXXX", xdg_config_dir);
1535 1536
        if (tempfilename)
        {
1537
            int tempfd = mkstemps(tempfilename, 0);
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
            if (tempfd >= 0)
            {
                tempfile = fdopen(tempfd, "w");
                if (tempfile)
                    break;
                close(tempfd);
                goto end;
            }
            else if (errno == EEXIST)
            {
1548
                HeapFree(GetProcessHeap(), 0, tempfilename);
1549 1550
                continue;
            }
1551
            HeapFree(GetProcessHeap(), 0, tempfilename);
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
        }
        return FALSE;
    }

    fprintf(tempfile, "<!DOCTYPE Menu PUBLIC \"-//freedesktop//DTD Menu 1.0//EN\"\n");
    fprintf(tempfile, "\"http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd\">\n");
    fprintf(tempfile, "<Menu>\n");
    fprintf(tempfile, "  <Name>Applications</Name>\n");

    name = HeapAlloc(GetProcessHeap(), 0, lstrlenA(filename) + 1);
    if (name == NULL) goto end;
    lastEntry = name;
    for (i = 0; filename[i]; i++)
    {
        name[i] = filename[i];
        if (filename[i] == '/')
        {
            char *dir_file_name;
            struct stat st;
            name[i] = 0;
            fprintf(tempfile, "  <Menu>\n");
1573 1574 1575 1576 1577 1578
            fprintf(tempfile, "    <Name>%s", count ? "" : "wine-");
            write_xml_text(tempfile, name);
            fprintf(tempfile, "</Name>\n");
            fprintf(tempfile, "    <Directory>%s", count ? "" : "wine-");
            write_xml_text(tempfile, name);
            fprintf(tempfile, ".directory</Directory>\n");
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
            dir_file_name = heap_printf("%s/desktop-directories/%s%s.directory",
                xdg_data_dir, count ? "" : "wine-", name);
            if (dir_file_name)
            {
                if (stat(dir_file_name, &st) != 0 && errno == ENOENT)
                    write_directory_entry(lastEntry, dir_file_name);
                HeapFree(GetProcessHeap(), 0, dir_file_name);
            }
            name[i] = '-';
            lastEntry = &name[i+1];
            ++count;
        }
    }
    name[i] = 0;

    fprintf(tempfile, "    <Include>\n");
1595 1596 1597
    fprintf(tempfile, "      <Filename>");
    write_xml_text(tempfile, name);
    fprintf(tempfile, "</Filename>\n");
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
    fprintf(tempfile, "    </Include>\n");
    for (i = 0; i < count; i++)
         fprintf(tempfile, "  </Menu>\n");
    fprintf(tempfile, "</Menu>\n");

    menuPath = heap_printf("%s/%s", xdg_config_dir, name);
    if (menuPath == NULL) goto end;
    strcpy(menuPath + strlen(menuPath) - strlen(".desktop"), ".menu");
    ret = TRUE;

end:
    if (tempfile)
        fclose(tempfile);
    if (ret)
        ret = (rename(tempfilename, menuPath) == 0);
    if (!ret && tempfilename)
        remove(tempfilename);
1615
    HeapFree(GetProcessHeap(), 0, tempfilename);
1616
    if (ret)
1617
        register_menus_entry(menuPath, unix_link);
1618 1619 1620 1621 1622
    HeapFree(GetProcessHeap(), 0, name);
    HeapFree(GetProcessHeap(), 0, menuPath);
    return ret;
}

1623
static BOOL write_menu_entry(const char *unix_link, const char *link, const char *path, const char *args,
1624
                             const char *descr, const char *workdir, const char *icon, const char *wmclass)
1625 1626 1627 1628 1629 1630 1631
{
    const char *linkname;
    char *desktopPath = NULL;
    char *desktopDir;
    char *filename = NULL;
    BOOL ret = TRUE;

1632
    WINE_TRACE("(%s, %s, %s, %s, %s, %s, %s, %s)\n", wine_dbgstr_a(unix_link), wine_dbgstr_a(link),
1633
               wine_dbgstr_a(path), wine_dbgstr_a(args), wine_dbgstr_a(descr),
1634
               wine_dbgstr_a(workdir), wine_dbgstr_a(icon), wine_dbgstr_a(wmclass));
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657

    linkname = strrchr(link, '/');
    if (linkname == NULL)
        linkname = link;
    else
        ++linkname;

    desktopPath = heap_printf("%s/applications/wine/%s.desktop", xdg_data_dir, link);
    if (!desktopPath)
    {
        WINE_WARN("out of memory creating menu entry\n");
        ret = FALSE;
        goto end;
    }
    desktopDir = strrchr(desktopPath, '/');
    *desktopDir = 0;
    if (!create_directories(desktopPath))
    {
        WINE_WARN("couldn't make parent directories for %s\n", wine_dbgstr_a(desktopPath));
        ret = FALSE;
        goto end;
    }
    *desktopDir = '/';
1658
    if (!write_desktop_entry(unix_link, desktopPath, linkname, path, args, descr, workdir, icon, wmclass))
1659 1660 1661 1662 1663 1664 1665
    {
        WINE_WARN("couldn't make desktop entry %s\n", wine_dbgstr_a(desktopPath));
        ret = FALSE;
        goto end;
    }

    filename = heap_printf("wine/%s.desktop", link);
1666
    if (!filename || !write_menu_file(unix_link, filename))
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
    {
        WINE_WARN("couldn't make menu file %s\n", wine_dbgstr_a(filename));
        ret = FALSE;
    }

end:
    HeapFree(GetProcessHeap(), 0, desktopPath);
    HeapFree(GetProcessHeap(), 0, filename);
    return ret;
}

1678
/* This escapes reserved characters in .desktop files' Exec keys. */
1679
static LPSTR escape(LPCWSTR arg)
1680
{
1681 1682 1683
    int i, j;
    WCHAR *escaped_string;
    char *utf8_string;
1684

1685 1686 1687
    escaped_string = HeapAlloc(GetProcessHeap(), 0, (4 * strlenW(arg) + 1) * sizeof(WCHAR));
    if (escaped_string == NULL) return NULL;
    for (i = j = 0; arg[i]; i++)
1688
    {
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
        switch (arg[i])
        {
        case '\\':
            escaped_string[j++] = '\\';
            escaped_string[j++] = '\\';
            escaped_string[j++] = '\\';
            escaped_string[j++] = '\\';
            break;
        case ' ':
        case '\t':
        case '\n':
        case '"':
        case '\'':
        case '>':
        case '<':
        case '~':
        case '|':
        case '&':
        case ';':
        case '$':
        case '*':
        case '?':
        case '#':
        case '(':
        case ')':
        case '`':
            escaped_string[j++] = '\\';
            escaped_string[j++] = '\\';
            /* fall through */
        default:
            escaped_string[j++] = arg[i];
            break;
        }
1722
    }
1723
    escaped_string[j] = 0;
1724

1725 1726
    utf8_string = wchars_to_utf8_chars(escaped_string);
    if (utf8_string == NULL)
1727
    {
1728 1729
        WINE_ERR("out of memory\n");
        goto end;
1730
    }
1731 1732 1733 1734

end:
    HeapFree(GetProcessHeap(), 0, escaped_string);
    return utf8_string;
1735 1736
}

1737 1738 1739 1740 1741 1742
/* Return a heap-allocated copy of the unix format difference between the two
 * Windows-format paths.
 * locn is the owning location
 * link is within locn
 */
static char *relative_path( LPCWSTR link, LPCWSTR locn )
1743
{
1744 1745
    char *unix_locn, *unix_link;
    char *relative = NULL;
1746

1747 1748 1749
    unix_locn = wine_get_unix_file_name(locn);
    unix_link = wine_get_unix_file_name(link);
    if (unix_locn && unix_link)
1750
    {
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
        size_t len_unix_locn, len_unix_link;
        len_unix_locn = strlen (unix_locn);
        len_unix_link = strlen (unix_link);
        if (len_unix_locn < len_unix_link && memcmp (unix_locn, unix_link, len_unix_locn) == 0 && unix_link[len_unix_locn] == '/')
        {
            size_t len_rel;
            char *p = strrchr (unix_link + len_unix_locn, '/');
            p = strrchr (p, '.');
            if (p)
            {
                *p = '\0';
                len_unix_link = p - unix_link;
            }
            len_rel = len_unix_link - len_unix_locn;
            relative = HeapAlloc(GetProcessHeap(), 0, len_rel);
            if (relative)
            {
                memcpy (relative, unix_link + len_unix_locn + 1, len_rel);
            }
        }
1771
    }
1772 1773 1774 1775 1776
    if (!relative)
        WINE_WARN("Could not separate the relative link path of %s in %s\n", wine_dbgstr_w(link), wine_dbgstr_w(locn));
    HeapFree(GetProcessHeap(), 0, unix_locn);
    HeapFree(GetProcessHeap(), 0, unix_link);
    return relative;
1777 1778 1779 1780 1781 1782 1783
}

/***********************************************************************
 *
 *           GetLinkLocation
 *
 * returns TRUE if successful
1784 1785 1786
 * *loc will contain CS_DESKTOPDIRECTORY, CS_STARTMENU, CS_STARTUP etc.
 * *relative will contain the address of a heap-allocated copy of the portion
 * of the filename that is within the specified location, in unix form
1787
 */
1788
static BOOL GetLinkLocation( LPCWSTR linkfile, DWORD *loc, char **relative )
1789
{
1790
    WCHAR filename[MAX_PATH], shortfilename[MAX_PATH], buffer[MAX_PATH];
Francois Gouget's avatar
Francois Gouget committed
1791
    DWORD len, i, r, filelen;
1792
    const DWORD locations[] = {
1793 1794 1795
        CSIDL_STARTUP, CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU,
        CSIDL_COMMON_STARTUP, CSIDL_COMMON_DESKTOPDIRECTORY,
        CSIDL_COMMON_STARTMENU };
1796

Francois Gouget's avatar
Francois Gouget committed
1797
    WINE_TRACE("%s\n", wine_dbgstr_w(linkfile));
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
    filelen=GetFullPathNameW( linkfile, MAX_PATH, shortfilename, NULL );
    if (filelen==0 || filelen>MAX_PATH)
        return FALSE;

    WINE_TRACE("%s\n", wine_dbgstr_w(shortfilename));

    /* the CSLU Toolkit uses a short path name when creating .lnk files;
     * expand or our hardcoded list won't match.
     */
    filelen=GetLongPathNameW(shortfilename, filename, MAX_PATH);
Francois Gouget's avatar
Francois Gouget committed
1808
    if (filelen==0 || filelen>MAX_PATH)
1809 1810
        return FALSE;

1811 1812
    WINE_TRACE("%s\n", wine_dbgstr_w(filename));

1813
    for( i=0; i<ARRAY_SIZE( locations ); i++ )
1814 1815 1816 1817 1818
    {
        if (!SHGetSpecialFolderPathW( 0, buffer, locations[i], FALSE ))
            continue;

        len = lstrlenW(buffer);
Francois Gouget's avatar
Francois Gouget committed
1819
        if (len >= MAX_PATH)
1820
            continue; /* We've just trashed memory! Hopefully we are OK */
1821

Francois Gouget's avatar
Francois Gouget committed
1822 1823
        if (len > filelen || filename[len]!='\\')
            continue;
1824 1825 1826
        /* do a lstrcmpinW */
        filename[len] = 0;
        r = lstrcmpiW( filename, buffer );
Francois Gouget's avatar
Francois Gouget committed
1827
        filename[len] = '\\';
1828 1829 1830 1831 1832
        if ( r )
            continue;

        /* return the remainder of the string and link type */
        *loc = locations[i];
1833 1834
        *relative = relative_path (filename, buffer);
        return (*relative != NULL);
1835 1836 1837 1838 1839
    }

    return FALSE;
}

1840
/* gets the target path directly or through MSI */
1841 1842
static HRESULT get_cmdline( IShellLinkW *sl, LPWSTR szPath, DWORD pathSize,
                            LPWSTR szArgs, DWORD argsSize)
1843 1844 1845 1846 1847 1848
{
    IShellLinkDataList *dl = NULL;
    EXP_DARWIN_LINK *dar = NULL;
    HRESULT hr;

    szPath[0] = 0;
1849 1850 1851
    szArgs[0] = 0;

    hr = IShellLinkW_GetPath( sl, szPath, pathSize, NULL, SLGP_RAWPATH );
1852
    if (hr == S_OK && szPath[0])
1853 1854
    {
        IShellLinkW_GetArguments( sl, szArgs, argsSize );
1855
        return hr;
1856
    }
1857 1858 1859 1860 1861 1862 1863 1864

    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))
    {
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
        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;
1879 1880
                int bcount = 0;
                BOOL in_quotes = FALSE;
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945

                /* Extract the application path */
                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 );
        }
1946 1947 1948 1949 1950 1951 1952
        LocalFree( dar );
    }

    IShellLinkDataList_Release( dl );
    return hr;
}

1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
static char *slashes_to_minuses(const char *string)
{
    int i;
    char *ret = HeapAlloc(GetProcessHeap(), 0, lstrlenA(string) + 1);
    if (ret)
    {
        for (i = 0; string[i]; i++)
        {
            if (string[i] == '/')
                ret[i] = '-';
            else
                ret[i] = string[i];
        }
        ret[i] = 0;
        return ret;
    }
    return NULL;
}

1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
static BOOL next_line(FILE *file, char **line, int *size)
{
    int pos = 0;
    char *cr;
    if (*line == NULL)
    {
        *size = 4096;
        *line = HeapAlloc(GetProcessHeap(), 0, *size);
    }
    while (*line != NULL)
    {
        if (fgets(&(*line)[pos], *size - pos, file) == NULL)
        {
            HeapFree(GetProcessHeap(), 0, *line);
            *line = NULL;
            if (feof(file))
                return TRUE;
            return FALSE;
        }
        pos = strlen(*line);
        cr = strchr(*line, '\n');
        if (cr == NULL)
        {
            char *line2;
            (*size) *= 2;
            line2 = HeapReAlloc(GetProcessHeap(), 0, *line, *size);
            if (line2)
                *line = line2;
            else
            {
                HeapFree(GetProcessHeap(), 0, *line);
                *line = NULL;
            }
        }
        else
        {
            *cr = 0;
            return TRUE;
        }
    }
    return FALSE;
}

static BOOL add_mimes(const char *xdg_data_dir, struct list *mime_types)
{
    char *globs_filename = NULL;
    BOOL ret = TRUE;
    globs_filename = heap_printf("%s/mime/globs", xdg_data_dir);
    if (globs_filename)
    {
        FILE *globs_file = fopen(globs_filename, "r");
        if (globs_file) /* doesn't have to exist */
        {
            char *line = NULL;
            int size = 0;
            while (ret && (ret = next_line(globs_file, &line, &size)) && line)
            {
                char *pos;
                struct xdg_mime_type *mime_type_entry = NULL;
                if (line[0] != '#' && (pos = strchr(line, ':')))
                {
                    mime_type_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct xdg_mime_type));
                    if (mime_type_entry)
                    {
                        *pos = 0;
2037 2038
                        mime_type_entry->mimeType = strdupA(line);
                        mime_type_entry->glob = strdupA(pos + 1);
2039 2040 2041 2042 2043 2044 2045 2046
                        mime_type_entry->lower_glob = strdupA(pos + 1);
                        if (mime_type_entry->lower_glob)
                        {
                            char *l;
                            for (l = mime_type_entry->lower_glob; *l; l++)
                                *l = tolower(*l);
                        }
                        if (mime_type_entry->mimeType && mime_type_entry->glob && mime_type_entry->lower_glob)
2047 2048 2049 2050 2051
                            list_add_tail(mime_types, &mime_type_entry->entry);
                        else
                        {
                            HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
                            HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2052
                            HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2053 2054 2055
                            HeapFree(GetProcessHeap(), 0, mime_type_entry);
                            ret = FALSE;
                        }
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
                    }
                    else
                        ret = FALSE;
                }
            }
            HeapFree(GetProcessHeap(), 0, line);
            fclose(globs_file);
        }
        HeapFree(GetProcessHeap(), 0, globs_filename);
    }
    else
        ret = FALSE;
    return ret;
}

static void free_native_mime_types(struct list *native_mime_types)
{
    struct xdg_mime_type *mime_type_entry, *mime_type_entry2;

    LIST_FOR_EACH_ENTRY_SAFE(mime_type_entry, mime_type_entry2, native_mime_types, struct xdg_mime_type, entry)
    {
        list_remove(&mime_type_entry->entry);
2078
        HeapFree(GetProcessHeap(), 0, mime_type_entry->glob);
2079
        HeapFree(GetProcessHeap(), 0, mime_type_entry->lower_glob);
2080 2081 2082 2083 2084
        HeapFree(GetProcessHeap(), 0, mime_type_entry->mimeType);
        HeapFree(GetProcessHeap(), 0, mime_type_entry);
    }
}

2085
static BOOL build_native_mime_types(const char *xdg_data_home, struct list *mime_types)
2086 2087 2088 2089 2090 2091 2092 2093
{
    char *xdg_data_dirs;
    BOOL ret;

    xdg_data_dirs = getenv("XDG_DATA_DIRS");
    if (xdg_data_dirs == NULL)
        xdg_data_dirs = heap_printf("/usr/local/share/:/usr/share/");
    else
2094
        xdg_data_dirs = strdupA(xdg_data_dirs);
2095 2096 2097

    if (xdg_data_dirs)
    {
2098 2099
        const char *begin;
        char *end;
2100

2101 2102 2103 2104
        ret = add_mimes(xdg_data_home, mime_types);
        if (ret)
        {
            for (begin = xdg_data_dirs; (end = strchr(begin, ':')); begin = end + 1)
2105
            {
2106 2107 2108 2109 2110
                *end = '\0';
                ret = add_mimes(begin, mime_types);
                *end = ':';
                if (!ret)
                    break;
2111
            }
2112 2113
            if (ret)
                ret = add_mimes(begin, mime_types);
2114 2115 2116 2117 2118
        }
        HeapFree(GetProcessHeap(), 0, xdg_data_dirs);
    }
    else
        ret = FALSE;
2119 2120
    if (!ret)
        free_native_mime_types(mime_types);
2121 2122 2123
    return ret;
}

2124
static BOOL match_glob(struct list *native_mime_types, const char *extension,
2125
                       int ignoreGlobCase, char **match)
2126
{
2127
#ifdef HAVE_FNMATCH
2128 2129 2130 2131 2132 2133 2134
    struct xdg_mime_type *mime_type_entry;
    int matchLength = 0;

    *match = NULL;

    LIST_FOR_EACH_ENTRY(mime_type_entry, native_mime_types, struct xdg_mime_type, entry)
    {
2135 2136
        const char *glob = ignoreGlobCase ? mime_type_entry->lower_glob : mime_type_entry->glob;
        if (fnmatch(glob, extension, 0) == 0)
2137
        {
2138
            if (*match == NULL || matchLength < strlen(glob))
2139 2140
            {
                *match = mime_type_entry->mimeType;
2141
                matchLength = strlen(glob);
2142 2143 2144 2145 2146 2147
            }
        }
    }

    if (*match != NULL)
    {
2148
        *match = strdupA(*match);
2149 2150 2151
        if (*match == NULL)
            return FALSE;
    }
2152 2153 2154
#else
    *match = NULL;
#endif
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
    return TRUE;
}

static BOOL freedesktop_mime_type_for_extension(struct list *native_mime_types,
                                                const char *extensionA,
                                                LPCWSTR extensionW,
                                                char **mime_type)
{
    WCHAR *lower_extensionW;
    INT len;
2165
    BOOL ret = match_glob(native_mime_types, extensionA, 0, mime_type);
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
    if (ret == FALSE || *mime_type != NULL)
        return ret;
    len = strlenW(extensionW);
    lower_extensionW = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
    if (lower_extensionW)
    {
        char *lower_extensionA;
        memcpy(lower_extensionW, extensionW, (len + 1)*sizeof(WCHAR));
        strlwrW(lower_extensionW);
        lower_extensionA = wchars_to_utf8_chars(lower_extensionW);
        if (lower_extensionA)
        {
2178
            ret = match_glob(native_mime_types, lower_extensionA, 1, mime_type);
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
            HeapFree(GetProcessHeap(), 0, lower_extensionA);
        }
        else
        {
            ret = FALSE;
            WINE_FIXME("out of memory\n");
        }
        HeapFree(GetProcessHeap(), 0, lower_extensionW);
    }
    else
    {
        ret = FALSE;
        WINE_FIXME("out of memory\n");
    }
    return ret;
}

2196
static WCHAR* reg_get_valW(HKEY key, LPCWSTR subkey, LPCWSTR name)
2197 2198
{
    DWORD size;
2199
    if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, NULL, &size) == ERROR_SUCCESS)
2200
    {
2201
        WCHAR *ret = HeapAlloc(GetProcessHeap(), 0, size);
2202 2203
        if (ret)
        {
2204
            if (RegGetValueW(key, subkey, name, RRF_RT_REG_SZ, NULL, ret, &size) == ERROR_SUCCESS)
2205 2206
                return ret;
        }
2207
        HeapFree(GetProcessHeap(), 0, ret);
2208 2209 2210 2211
    }
    return NULL;
}

2212
static CHAR* reg_get_val_utf8(HKEY key, LPCWSTR subkey, LPCWSTR name)
2213
{
2214 2215
    WCHAR *valW = reg_get_valW(key, subkey, name);
    if (valW)
2216
    {
2217 2218 2219
        char *val = wchars_to_utf8_chars(valW);
        HeapFree(GetProcessHeap(), 0, valW);
        return val;
2220 2221 2222 2223
    }
    return NULL;
}

2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
static HKEY open_associations_reg_key(void)
{
    static const WCHAR Software_Wine_FileOpenAssociationsW[] = {
        'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\','F','i','l','e','O','p','e','n','A','s','s','o','c','i','a','t','i','o','n','s',0};
    HKEY assocKey;
    if (RegCreateKeyW(HKEY_CURRENT_USER, Software_Wine_FileOpenAssociationsW, &assocKey) == ERROR_SUCCESS)
        return assocKey;
    return NULL;
}

2234
static BOOL has_association_changed(LPCWSTR extensionW, LPCSTR mimeType, LPCWSTR progId,
2235
    LPCSTR appName, LPCSTR openWithIcon)
2236 2237
{
    static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2238 2239
    static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
    static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
2240
    static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
    HKEY assocKey;
    BOOL ret;

    if ((assocKey = open_associations_reg_key()))
    {
        CHAR *valueA;
        WCHAR *value;

        ret = FALSE;

2251
        valueA = reg_get_val_utf8(assocKey, extensionW, MimeTypeW);
2252 2253 2254 2255 2256 2257 2258 2259 2260
        if (!valueA || lstrcmpA(valueA, mimeType))
            ret = TRUE;
        HeapFree(GetProcessHeap(), 0, valueA);

        value = reg_get_valW(assocKey, extensionW, ProgIDW);
        if (!value || strcmpW(value, progId))
            ret = TRUE;
        HeapFree(GetProcessHeap(), 0, value);

2261
        valueA = reg_get_val_utf8(assocKey, extensionW, AppNameW);
2262 2263 2264 2265
        if (!valueA || lstrcmpA(valueA, appName))
            ret = TRUE;
        HeapFree(GetProcessHeap(), 0, valueA);

2266 2267 2268 2269 2270 2271 2272
        valueA = reg_get_val_utf8(assocKey, extensionW, OpenWithIconW);
        if ((openWithIcon && !valueA) ||
            (!openWithIcon && valueA) ||
            (openWithIcon && valueA && lstrcmpA(valueA, openWithIcon)))
            ret = TRUE;
        HeapFree(GetProcessHeap(), 0, valueA);

2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
        RegCloseKey(assocKey);
    }
    else
    {
        WINE_ERR("error opening associations registry key\n");
        ret = FALSE;
    }
    return ret;
}

2283
static void update_association(LPCWSTR extension, LPCSTR mimeType, LPCWSTR progId,
2284
    LPCSTR appName, LPCSTR desktopFile, LPCSTR openWithIcon)
2285 2286
{
    static const WCHAR ProgIDW[] = {'P','r','o','g','I','D',0};
2287 2288 2289
    static const WCHAR MimeTypeW[] = {'M','i','m','e','T','y','p','e',0};
    static const WCHAR AppNameW[] = {'A','p','p','N','a','m','e',0};
    static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2290
    static const WCHAR OpenWithIconW[] = {'O','p','e','n','W','i','t','h','I','c','o','n',0};
2291 2292 2293 2294 2295
    HKEY assocKey = NULL;
    HKEY subkey = NULL;
    WCHAR *mimeTypeW = NULL;
    WCHAR *appNameW = NULL;
    WCHAR *desktopFileW = NULL;
2296
    WCHAR *openWithIconW = NULL;
2297 2298 2299 2300 2301 2302 2303

    assocKey = open_associations_reg_key();
    if (assocKey == NULL)
    {
        WINE_ERR("could not open file associations key\n");
        goto done;
    }
2304

2305
    if (RegCreateKeyW(assocKey, extension, &subkey) != ERROR_SUCCESS)
2306
    {
2307 2308
        WINE_ERR("could not create extension subkey\n");
        goto done;
2309
    }
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331

    mimeTypeW = utf8_chars_to_wchars(mimeType);
    if (mimeTypeW == NULL)
    {
        WINE_ERR("out of memory\n");
        goto done;
    }

    appNameW = utf8_chars_to_wchars(appName);
    if (appNameW == NULL)
    {
        WINE_ERR("out of memory\n");
        goto done;
    }

    desktopFileW = utf8_chars_to_wchars(desktopFile);
    if (desktopFileW == NULL)
    {
        WINE_ERR("out of memory\n");
        goto done;
    }

2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
    if (openWithIcon)
    {
        openWithIconW = utf8_chars_to_wchars(openWithIcon);
        if (openWithIconW == NULL)
        {
            WINE_ERR("out of memory\n");
            goto done;
        }
    }

2342 2343 2344
    RegSetValueExW(subkey, MimeTypeW, 0, REG_SZ, (const BYTE*) mimeTypeW, (lstrlenW(mimeTypeW) + 1) * sizeof(WCHAR));
    RegSetValueExW(subkey, ProgIDW, 0, REG_SZ, (const BYTE*) progId, (lstrlenW(progId) + 1) * sizeof(WCHAR));
    RegSetValueExW(subkey, AppNameW, 0, REG_SZ, (const BYTE*) appNameW, (lstrlenW(appNameW) + 1) * sizeof(WCHAR));
2345
    RegSetValueExW(subkey, DesktopFileW, 0, REG_SZ, (const BYTE*) desktopFileW, (lstrlenW(desktopFileW) + 1) * sizeof(WCHAR));
2346 2347 2348 2349
    if (openWithIcon)
        RegSetValueExW(subkey, OpenWithIconW, 0, REG_SZ, (const BYTE*) openWithIconW, (lstrlenW(openWithIconW) + 1) * sizeof(WCHAR));
    else
        RegDeleteValueW(subkey, OpenWithIconW);
2350 2351 2352 2353 2354 2355 2356

done:
    RegCloseKey(assocKey);
    RegCloseKey(subkey);
    HeapFree(GetProcessHeap(), 0, mimeTypeW);
    HeapFree(GetProcessHeap(), 0, appNameW);
    HeapFree(GetProcessHeap(), 0, desktopFileW);
2357
    HeapFree(GetProcessHeap(), 0, openWithIconW);
2358 2359 2360 2361
}

static BOOL cleanup_associations(void)
{
2362
    static const WCHAR openW[] = {'o','p','e','n',0};
2363
    static const WCHAR DesktopFileW[] = {'D','e','s','k','t','o','p','F','i','l','e',0};
2364 2365 2366 2367 2368 2369
    HKEY assocKey;
    BOOL hasChanged = FALSE;
    if ((assocKey = open_associations_reg_key()))
    {
        int i;
        BOOL done = FALSE;
2370
        for (i = 0; !done;)
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
        {
            WCHAR *extensionW = NULL;
            DWORD size = 1024;
            LSTATUS ret;

            do
            {
                HeapFree(GetProcessHeap(), 0, extensionW);
                extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
                if (extensionW == NULL)
                {
                    WINE_ERR("out of memory\n");
                    ret = ERROR_OUTOFMEMORY;
                    break;
                }
                ret = RegEnumKeyExW(assocKey, i, extensionW, &size, NULL, NULL, NULL, NULL);
                size *= 2;
            } while (ret == ERROR_MORE_DATA);

            if (ret == ERROR_SUCCESS)
            {
                WCHAR *command;
2393
                command = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2394 2395
                if (command == NULL)
                {
2396
                    char *desktopFile = reg_get_val_utf8(assocKey, extensionW, DesktopFileW);
2397 2398
                    if (desktopFile)
                    {
2399
                        WINE_TRACE("removing file type association for %s\n", wine_dbgstr_w(extensionW));
2400 2401 2402 2403 2404 2405
                        remove(desktopFile);
                    }
                    RegDeleteKeyW(assocKey, extensionW);
                    hasChanged = TRUE;
                    HeapFree(GetProcessHeap(), 0, desktopFile);
                }
2406 2407
                else
                    i++;
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
                HeapFree(GetProcessHeap(), 0, command);
            }
            else
            {
                if (ret != ERROR_NO_MORE_ITEMS)
                    WINE_ERR("error %d while reading registry\n", ret);
                done = TRUE;
            }
            HeapFree(GetProcessHeap(), 0, extensionW);
        }
        RegCloseKey(assocKey);
    }
    else
        WINE_ERR("could not open file associations key\n");
    return hasChanged;
}

2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
static BOOL write_freedesktop_mime_type_entry(const char *packages_dir, const char *dot_extension,
                                              const char *mime_type, const char *comment)
{
    BOOL ret = FALSE;
    char *filename;

    WINE_TRACE("writing MIME type %s, extension=%s, comment=%s\n", wine_dbgstr_a(mime_type),
               wine_dbgstr_a(dot_extension), wine_dbgstr_a(comment));

    filename = heap_printf("%s/x-wine-extension-%s.xml", packages_dir, &dot_extension[1]);
    if (filename)
    {
        FILE *packageFile = fopen(filename, "w");
        if (packageFile)
        {
            fprintf(packageFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            fprintf(packageFile, "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n");
2442 2443 2444 2445 2446 2447
            fprintf(packageFile, "  <mime-type type=\"");
            write_xml_text(packageFile, mime_type);
            fprintf(packageFile, "\">\n");
            fprintf(packageFile, "    <glob pattern=\"*");
            write_xml_text(packageFile, dot_extension);
            fprintf(packageFile, "\"/>\n");
2448
            if (comment)
2449 2450 2451 2452 2453
            {
                fprintf(packageFile, "    <comment>");
                write_xml_text(packageFile, comment);
                fprintf(packageFile, "</comment>\n");
            }
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
            fprintf(packageFile, "  </mime-type>\n");
            fprintf(packageFile, "</mime-info>\n");
            ret = TRUE;
            fclose(packageFile);
        }
        else
            WINE_ERR("error writing file %s\n", filename);
        HeapFree(GetProcessHeap(), 0, filename);
    }
    else
        WINE_ERR("out of memory\n");
    return ret;
}

2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
static BOOL is_extension_blacklisted(LPCWSTR extension)
{
    /* These are managed through external tools like wine.desktop, to evade malware created file type associations */
    static const WCHAR comW[] = {'.','c','o','m',0};
    static const WCHAR exeW[] = {'.','e','x','e',0};
    static const WCHAR msiW[] = {'.','m','s','i',0};

    if (!strcmpiW(extension, comW) ||
        !strcmpiW(extension, exeW) ||
        !strcmpiW(extension, msiW))
        return TRUE;
    return FALSE;
}

2482 2483 2484 2485 2486 2487 2488 2489
static const char* get_special_mime_type(LPCWSTR extension)
{
    static const WCHAR lnkW[] = {'.','l','n','k',0};
    if (!strcmpiW(extension, lnkW))
        return "application/x-ms-shortcut";
    return NULL;
}

2490 2491
static BOOL write_freedesktop_association_entry(const char *desktopPath, const char *dot_extension,
                                                const char *friendlyAppName, const char *mimeType,
2492
                                                const char *progId, const char *openWithIcon)
2493 2494 2495 2496
{
    BOOL ret = FALSE;
    FILE *desktop;

2497
    WINE_TRACE("writing association for file type %s, friendlyAppName=%s, MIME type %s, progID=%s, icon=%s to file %s\n",
2498
               wine_dbgstr_a(dot_extension), wine_dbgstr_a(friendlyAppName), wine_dbgstr_a(mimeType),
2499
               wine_dbgstr_a(progId), wine_dbgstr_a(openWithIcon), wine_dbgstr_a(desktopPath));
2500 2501 2502 2503 2504 2505 2506

    desktop = fopen(desktopPath, "w");
    if (desktop)
    {
        fprintf(desktop, "[Desktop Entry]\n");
        fprintf(desktop, "Type=Application\n");
        fprintf(desktop, "Name=%s\n", friendlyAppName);
2507
        fprintf(desktop, "MimeType=%s;\n", mimeType);
2508
        fprintf(desktop, "Exec=env WINEPREFIX=\"%s\" wine start /ProgIDOpen %s %%f\n", wine_get_config_dir(), progId);
2509 2510
        fprintf(desktop, "NoDisplay=true\n");
        fprintf(desktop, "StartupNotify=true\n");
2511 2512
        if (openWithIcon)
            fprintf(desktop, "Icon=%s\n", openWithIcon);
2513 2514 2515 2516 2517 2518 2519 2520
        ret = TRUE;
        fclose(desktop);
    }
    else
        WINE_ERR("error writing association file %s\n", wine_dbgstr_a(desktopPath));
    return ret;
}

2521 2522
static BOOL generate_associations(const char *xdg_data_home, const char *packages_dir, const char *applications_dir)
{
2523
    static const WCHAR openW[] = {'o','p','e','n',0};
2524 2525
    struct wine_rb_tree mimeProgidTree = { winemenubuilder_rb_string_compare };
    struct list nativeMimeTypes = LIST_INIT(nativeMimeTypes);
2526 2527 2528
    LSTATUS ret = 0;
    int i;
    BOOL hasChanged = FALSE;
2529 2530 2531 2532 2533 2534

    if (!build_native_mime_types(xdg_data_home, &nativeMimeTypes))
    {
        WINE_ERR("could not build native MIME types\n");
        return FALSE;
    }
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554

    for (i = 0; ; i++)
    {
        WCHAR *extensionW = NULL;
        DWORD size = 1024;

        do
        {
            HeapFree(GetProcessHeap(), 0, extensionW);
            extensionW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
            if (extensionW == NULL)
            {
                WINE_ERR("out of memory\n");
                ret = ERROR_OUTOFMEMORY;
                break;
            }
            ret = RegEnumKeyExW(HKEY_CLASSES_ROOT, i, extensionW, &size, NULL, NULL, NULL, NULL);
            size *= 2;
        } while (ret == ERROR_MORE_DATA);

2555
        if (ret == ERROR_SUCCESS && extensionW[0] == '.' && !is_extension_blacklisted(extensionW))
2556 2557 2558
        {
            char *extensionA = NULL;
            WCHAR *commandW = NULL;
2559 2560
            WCHAR *executableW = NULL;
            char *openWithIconA = NULL;
2561 2562
            WCHAR *friendlyDocNameW = NULL;
            char *friendlyDocNameA = NULL;
2563 2564
            WCHAR *iconW = NULL;
            char *iconA = NULL;
2565 2566
            WCHAR *contentTypeW = NULL;
            char *mimeTypeA = NULL;
2567 2568 2569 2570
            WCHAR *friendlyAppNameW = NULL;
            char *friendlyAppNameA = NULL;
            WCHAR *progIdW = NULL;
            char *progIdA = NULL;
2571
            char *mimeProgId = NULL;
2572

2573
            extensionA = wchars_to_utf8_chars(strlwrW(extensionW));
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
            if (extensionA == NULL)
            {
                WINE_ERR("out of memory\n");
                goto end;
            }

            friendlyDocNameW = assoc_query(ASSOCSTR_FRIENDLYDOCNAME, extensionW, NULL);
            if (friendlyDocNameW)
            {
                friendlyDocNameA = wchars_to_utf8_chars(friendlyDocNameW);
                if (friendlyDocNameA == NULL)
                {
                    WINE_ERR("out of memory\n");
                    goto end;
                }
            }

2591 2592
            iconW = assoc_query(ASSOCSTR_DEFAULTICON, extensionW, NULL);

2593
            contentTypeW = assoc_query(ASSOCSTR_CONTENTTYPE, extensionW, NULL);
2594 2595
            if (contentTypeW)
                strlwrW(contentTypeW);
2596

2597
            if (!freedesktop_mime_type_for_extension(&nativeMimeTypes, extensionA, extensionW, &mimeTypeA))
2598 2599 2600
                goto end;

            if (mimeTypeA == NULL)
2601
            {
2602
                if (contentTypeW != NULL && strchrW(contentTypeW, '/'))
2603
                    mimeTypeA = wchars_to_utf8_chars(contentTypeW);
2604 2605
                else if ((get_special_mime_type(extensionW)))
                    mimeTypeA = strdupA(get_special_mime_type(extensionW));
2606 2607
                else
                    mimeTypeA = heap_printf("application/x-wine-extension-%s", &extensionA[1]);
2608

2609 2610
                if (mimeTypeA != NULL)
                {
2611
                    /* GNOME seems to ignore the <icon> tag in MIME packages,
2612 2613
                     * and the default name is more intuitive anyway.
                     */
2614
                    if (iconW)
2615 2616 2617 2618
                    {
                        char *flattened_mime = slashes_to_minuses(mimeTypeA);
                        if (flattened_mime)
                        {
2619 2620 2621
                            int index = 0;
                            WCHAR *comma = strrchrW(iconW, ',');
                            if (comma)
2622
                            {
2623 2624
                                *comma = 0;
                                index = atoiW(comma + 1);
2625
                            }
2626
                            iconA = extract_icon(iconW, index, flattened_mime, FALSE);
2627 2628 2629 2630
                            HeapFree(GetProcessHeap(), 0, flattened_mime);
                        }
                    }

2631 2632 2633 2634 2635 2636 2637 2638 2639
                    write_freedesktop_mime_type_entry(packages_dir, extensionA, mimeTypeA, friendlyDocNameA);
                    hasChanged = TRUE;
                }
                else
                {
                    WINE_FIXME("out of memory\n");
                    goto end;
                }
            }
2640

2641
            commandW = assoc_query(ASSOCSTR_COMMAND, extensionW, openW);
2642 2643 2644 2645
            if (commandW == NULL)
                /* no command => no application is associated */
                goto end;

2646 2647 2648 2649
            executableW = assoc_query(ASSOCSTR_EXECUTABLE, extensionW, openW);
            if (executableW)
                openWithIconA = extract_icon(executableW, 0, NULL, FALSE);

2650
            friendlyAppNameW = assoc_query(ASSOCSTR_FRIENDLYAPPNAME, extensionW, openW);
2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
            if (friendlyAppNameW)
            {
                friendlyAppNameA = wchars_to_utf8_chars(friendlyAppNameW);
                if (friendlyAppNameA == NULL)
                {
                    WINE_ERR("out of memory\n");
                    goto end;
                }
            }
            else
            {
                friendlyAppNameA = heap_printf("A Wine application");
                if (friendlyAppNameA == NULL)
                {
                    WINE_ERR("out of memory\n");
                    goto end;
                }
            }

            progIdW = reg_get_valW(HKEY_CLASSES_ROOT, extensionW, NULL);
            if (progIdW)
            {
2673
                progIdA = escape(progIdW);
2674 2675 2676 2677 2678 2679 2680 2681 2682
                if (progIdA == NULL)
                {
                    WINE_ERR("out of memory\n");
                    goto end;
                }
            }
            else
                goto end; /* no progID => not a file type association */

2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
            /* Do not allow duplicate ProgIDs for a MIME type, it causes unnecessary duplication in Open dialogs */
            mimeProgId = heap_printf("%s=>%s", mimeTypeA, progIdA);
            if (mimeProgId)
            {
                struct rb_string_entry *entry;
                if (wine_rb_get(&mimeProgidTree, mimeProgId))
                {
                    HeapFree(GetProcessHeap(), 0, mimeProgId);
                    goto end;
                }
                entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct rb_string_entry));
                if (!entry)
                {
                    WINE_ERR("out of memory allocating rb_string_entry\n");
                    goto end;
                }
                entry->string = mimeProgId;
                if (wine_rb_put(&mimeProgidTree, mimeProgId, &entry->entry))
                {
                    WINE_ERR("error updating rb tree\n");
                    goto end;
                }
            }

2707
            if (has_association_changed(extensionW, mimeTypeA, progIdW, friendlyAppNameA, openWithIconA))
2708 2709 2710 2711
            {
                char *desktopPath = heap_printf("%s/wine-extension-%s.desktop", applications_dir, &extensionA[1]);
                if (desktopPath)
                {
2712
                    if (write_freedesktop_association_entry(desktopPath, extensionA, friendlyAppNameA, mimeTypeA, progIdA, openWithIconA))
2713 2714
                    {
                        hasChanged = TRUE;
2715
                        update_association(extensionW, mimeTypeA, progIdW, friendlyAppNameA, desktopPath, openWithIconA);
2716 2717 2718 2719 2720
                    }
                    HeapFree(GetProcessHeap(), 0, desktopPath);
                }
            }

2721 2722 2723
        end:
            HeapFree(GetProcessHeap(), 0, extensionA);
            HeapFree(GetProcessHeap(), 0, commandW);
2724 2725
            HeapFree(GetProcessHeap(), 0, executableW);
            HeapFree(GetProcessHeap(), 0, openWithIconA);
2726 2727
            HeapFree(GetProcessHeap(), 0, friendlyDocNameW);
            HeapFree(GetProcessHeap(), 0, friendlyDocNameA);
2728 2729
            HeapFree(GetProcessHeap(), 0, iconW);
            HeapFree(GetProcessHeap(), 0, iconA);
2730 2731
            HeapFree(GetProcessHeap(), 0, contentTypeW);
            HeapFree(GetProcessHeap(), 0, mimeTypeA);
2732 2733 2734 2735
            HeapFree(GetProcessHeap(), 0, friendlyAppNameW);
            HeapFree(GetProcessHeap(), 0, friendlyAppNameA);
            HeapFree(GetProcessHeap(), 0, progIdW);
            HeapFree(GetProcessHeap(), 0, progIdA);
2736 2737 2738 2739 2740 2741
        }
        HeapFree(GetProcessHeap(), 0, extensionW);
        if (ret != ERROR_SUCCESS)
            break;
    }

2742
    wine_rb_destroy(&mimeProgidTree, winemenubuilder_rb_destroy, NULL);
2743
    free_native_mime_types(&nativeMimeTypes);
2744
    return hasChanged;
2745 2746
}

2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
static char *get_start_exe_path(void)
 {
    static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
                                   '\\','s','t','a','r','t','.','e','x','e',0};
    WCHAR start_path[MAX_PATH];
    GetWindowsDirectoryW(start_path, MAX_PATH);
    lstrcatW(start_path, startW);
    return escape(start_path);
}

2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
static char* escape_unix_link_arg(LPCSTR unix_link)
{
    char *ret = NULL;
    WCHAR *unix_linkW = utf8_chars_to_wchars(unix_link);
    if (unix_linkW)
    {
        char *escaped_lnk = escape(unix_linkW);
        if (escaped_lnk)
        {
            ret = heap_printf("/Unix %s", escaped_lnk);
            HeapFree(GetProcessHeap(), 0, escaped_lnk);
        }
        HeapFree(GetProcessHeap(), 0, unix_linkW);
    }
    return ret;
}

2774
static BOOL InvokeShellLinker( IShellLinkW *sl, LPCWSTR link, BOOL bWait )
2775
{
2776 2777
    static const WCHAR startW[] = {'\\','c','o','m','m','a','n','d',
                                   '\\','s','t','a','r','t','.','e','x','e',0};
2778
    char *link_name = NULL, *icon_name = NULL, *work_dir = NULL;
2779
    char *escaped_path = NULL, *escaped_args = NULL, *description = NULL;
2780
    char *wmclass = NULL;
2781
    WCHAR szTmp[INFOTIPSIZE];
2782
    WCHAR szDescription[INFOTIPSIZE], szPath[MAX_PATH], szWorkDir[MAX_PATH];
2783
    WCHAR szArgs[INFOTIPSIZE], szIconPath[MAX_PATH], szWMClass[MAX_PATH];
2784
    int iIconId = 0, r = -1;
2785
    DWORD csidl = -1;
2786
    HANDLE hsem = NULL;
2787
    char *unix_link = NULL;
2788
    char *start_path = NULL;
2789 2790 2791 2792 2793 2794 2795

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

2796
    if( !GetLinkLocation( link, &csidl, &link_name ) )
2797
    {
2798
        WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
2799 2800
        return TRUE;
    }
2801
    if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
2802 2803 2804 2805
    {
        WINE_WARN("Not under desktop or start menu. Ignoring.\n");
        return TRUE;
    }
2806
    WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));
2807

2808 2809 2810
    szTmp[0] = 0;
    IShellLinkW_GetWorkingDirectory( sl, szTmp, MAX_PATH );
    ExpandEnvironmentStringsW(szTmp, szWorkDir, MAX_PATH);
2811
    WINE_TRACE("workdir    : %s\n", wine_dbgstr_w(szWorkDir));
2812

2813 2814 2815
    szTmp[0] = 0;
    IShellLinkW_GetDescription( sl, szTmp, INFOTIPSIZE );
    ExpandEnvironmentStringsW(szTmp, szDescription, INFOTIPSIZE);
2816
    WINE_TRACE("description: %s\n", wine_dbgstr_w(szDescription));
2817

2818 2819
    get_cmdline( sl, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
    ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
2820 2821
    WINE_TRACE("path       : %s\n", wine_dbgstr_w(szPath));
    WINE_TRACE("args       : %s\n", wine_dbgstr_w(szArgs));
2822

2823 2824 2825
    szTmp[0] = 0;
    IShellLinkW_GetIconLocation( sl, szTmp, MAX_PATH, &iIconId );
    ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);
2826
    WINE_TRACE("icon file  : %s\n", wine_dbgstr_w(szIconPath) );
2827

2828 2829
    szWMClass[0] = 0;

2830 2831 2832
    if( !szPath[0] )
    {
        LPITEMIDLIST pidl = NULL;
2833
        IShellLinkW_GetIDList( sl, &pidl );
2834
        if( pidl && SHGetPathFromIDListW( pidl, szPath ) )
2835
            WINE_TRACE("pidl path  : %s\n", wine_dbgstr_w(szPath));
2836 2837 2838 2839
    }

    /* extract the icon */
    if( szIconPath[0] )
2840
        icon_name = extract_icon( szIconPath , iIconId, NULL, bWait );
2841
    else
2842
        icon_name = extract_icon( szPath, iIconId, NULL, bWait );
2843

2844
    /* fail - try once again after parent process exit */
2845 2846
    if( !icon_name )
    {
2847
        if (bWait)
2848 2849 2850 2851
        {
            WINE_WARN("Unable to extract icon, deferring.\n");
            goto cleanup;
        }
2852 2853
        WINE_ERR("failed to extract icon from %s\n",
                 wine_dbgstr_w( szIconPath[0] ? szIconPath : szPath ));
2854 2855
    }

2856 2857 2858 2859 2860 2861 2862
    unix_link = wine_get_unix_file_name(link);
    if (unix_link == NULL)
    {
        WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
        goto cleanup;
    }

2863 2864 2865
    /* check the path */
    if( szPath[0] )
    {
2866 2867
        static const WCHAR exeW[] = {'.','e','x','e',0};
        WCHAR *p;
2868

2869
        /* check for .exe extension */
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
        if (!(p = strrchrW( szPath, '.' )) ||
            strchrW( p, '\\' ) || strchrW( p, '/' ) ||
            lstrcmpiW( p, exeW ))
        {
            /* Not .exe - use 'start.exe' to launch this file */
            p = szArgs + lstrlenW(szPath) + 2;
            if (szArgs[0])
            {
                p[0] = ' ';
                memmove( p+1, szArgs, min( (lstrlenW(szArgs) + 1) * sizeof(szArgs[0]),
                                           sizeof(szArgs) - (p + 1 - szArgs) * sizeof(szArgs[0]) ) );
            }
            else
                p[0] = 0;

            szArgs[0] = '"';
            lstrcpyW(szArgs + 1, szPath);
            p[-1] = '"';

            GetWindowsDirectoryW(szPath, MAX_PATH);
            lstrcatW(szPath, startW);
        }
2892 2893 2894 2895 2896 2897 2898 2899
        else
        {
            /* FIXME: Use AppUserModelID if present. */
            WCHAR *p = PathFindFileNameW(szPath);

            lstrcpyW(szWMClass, p);
            CharLowerW(szWMClass);
        }
2900 2901 2902

        /* convert app working dir */
        if (szWorkDir[0])
2903
            work_dir = wine_get_unix_file_name( szWorkDir );
2904 2905 2906 2907
    }
    else
    {
        /* if there's no path... try run the link itself */
2908 2909 2910
        lstrcpynW(szArgs, link, MAX_PATH);
        GetWindowsDirectoryW(szPath, MAX_PATH);
        lstrcatW(szPath, startW);
2911 2912 2913 2914
    }

    /* escape the path and parameters */
    escaped_path = escape(szPath);
2915
    escaped_args = escape(szArgs);
2916
    description = wchars_to_utf8_chars(szDescription);
2917 2918
    wmclass = wchars_to_utf8_chars(szWMClass);
    if (escaped_path == NULL || escaped_args == NULL || description == NULL || wmclass == NULL)
2919 2920 2921 2922
    {
        WINE_ERR("out of memory allocating/escaping parameters\n");
        goto cleanup;
    }
2923

2924 2925 2926 2927 2928 2929 2930
    start_path = get_start_exe_path();
    if (start_path == NULL)
    {
        WINE_ERR("out of memory\n");
        goto cleanup;
    }

2931
    /* building multiple menus concurrently has race conditions */
2932
    hsem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
2933
    if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hsem, FALSE, INFINITE, QS_ALLINPUT ) )
2934 2935 2936 2937 2938
    {
        WINE_ERR("failed wait for semaphore\n");
        goto cleanup;
    }

2939 2940 2941 2942 2943 2944 2945 2946 2947
    if (in_desktop_dir(csidl))
    {
        char *location;
        const char *lastEntry;
        lastEntry = strrchr(link_name, '/');
        if (lastEntry == NULL)
            lastEntry = link_name;
        else
            ++lastEntry;
2948
        location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
2949 2950
        if (location)
        {
2951 2952 2953 2954 2955 2956
            if (csidl == CSIDL_COMMON_DESKTOPDIRECTORY)
            {
                char *link_arg = escape_unix_link_arg(unix_link);
                if (link_arg)
                {
                    r = !write_desktop_entry(unix_link, location, lastEntry,
2957
                        start_path, link_arg, description, work_dir, icon_name, wmclass);
2958 2959 2960 2961
                    HeapFree(GetProcessHeap(), 0, link_arg);
                }
            }
            else
2962
                r = !write_desktop_entry(NULL, location, lastEntry, escaped_path, escaped_args, description, work_dir, icon_name, wmclass);
2963 2964
            if (r == 0)
                chmod(location, 0755);
2965 2966 2967 2968
            HeapFree(GetProcessHeap(), 0, location);
        }
    }
    else
2969
    {
2970 2971
        char *link_arg = escape_unix_link_arg(unix_link);
        if (link_arg)
2972
        {
2973
            r = !write_menu_entry(unix_link, link_name, start_path, link_arg, description, work_dir, icon_name, wmclass);
2974
            HeapFree(GetProcessHeap(), 0, link_arg);
2975 2976
        }
    }
2977

2978 2979
    ReleaseSemaphore( hsem, 1, NULL );

2980
cleanup:
2981
    if (hsem) CloseHandle( hsem );
2982 2983 2984
    HeapFree( GetProcessHeap(), 0, icon_name );
    HeapFree( GetProcessHeap(), 0, work_dir );
    HeapFree( GetProcessHeap(), 0, link_name );
2985 2986
    HeapFree( GetProcessHeap(), 0, escaped_args );
    HeapFree( GetProcessHeap(), 0, escaped_path );
2987
    HeapFree( GetProcessHeap(), 0, description );
2988
    HeapFree( GetProcessHeap(), 0, wmclass );
2989 2990
    HeapFree( GetProcessHeap(), 0, unix_link );
    HeapFree( GetProcessHeap(), 0, start_path );
2991

2992
    if (r && !bWait)
2993
        WINE_ERR("failed to build the menu\n" );
2994

2995
    return ( r == 0 );
2996 2997
}

2998 2999
static BOOL InvokeShellLinkerForURL( IUniformResourceLocatorW *url, LPCWSTR link, BOOL bWait )
{
3000
    char *link_name = NULL, *icon_name = NULL;
3001
    DWORD csidl = -1;
3002
    LPWSTR urlPath = NULL;
3003 3004 3005 3006 3007
    char *escaped_urlPath = NULL;
    HRESULT hr;
    HANDLE hSem = NULL;
    BOOL ret = TRUE;
    int r = -1;
3008
    char *unix_link = NULL;
3009 3010 3011 3012
    IPropertySetStorage *pPropSetStg;
    IPropertyStorage *pPropStg;
    PROPSPEC ps[2];
    PROPVARIANT pv[2];
3013
    char *start_path = NULL;
3014
    BOOL has_icon = FALSE;
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042

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

    if( !GetLinkLocation( link, &csidl, &link_name ) )
    {
        WINE_WARN("Unknown link location %s. Ignoring.\n",wine_dbgstr_w(link));
        return TRUE;
    }
    if (!in_desktop_dir(csidl) && !in_startmenu(csidl))
    {
        WINE_WARN("Not under desktop or start menu. Ignoring.\n");
        ret = TRUE;
        goto cleanup;
    }
    WINE_TRACE("Link       : %s\n", wine_dbgstr_a(link_name));

    hr = url->lpVtbl->GetURL(url, &urlPath);
    if (FAILED(hr))
    {
        ret = TRUE;
        goto cleanup;
    }
    WINE_TRACE("path       : %s\n", wine_dbgstr_w(urlPath));

3043 3044 3045 3046 3047 3048 3049
    unix_link = wine_get_unix_file_name(link);
    if (unix_link == NULL)
    {
        WINE_WARN("couldn't find unix path of %s\n", wine_dbgstr_w(link));
        goto cleanup;
    }

3050
    escaped_urlPath = escape(urlPath);
3051 3052 3053 3054 3055
    if (escaped_urlPath == NULL)
    {
        WINE_ERR("couldn't escape url, out of memory\n");
        goto cleanup;
    }
3056

3057 3058 3059 3060 3061 3062 3063
    start_path = get_start_exe_path();
    if (start_path == NULL)
    {
        WINE_ERR("out of memory\n");
        goto cleanup;
    }

3064
    ps[0].ulKind = PRSPEC_PROPID;
3065
    ps[0].u.propid = PID_IS_ICONFILE;
3066
    ps[1].ulKind = PRSPEC_PROPID;
3067
    ps[1].u.propid = PID_IS_ICONINDEX;
3068 3069 3070 3071 3072 3073 3074 3075 3076 3077

    hr = url->lpVtbl->QueryInterface(url, &IID_IPropertySetStorage, (void **) &pPropSetStg);
    if (SUCCEEDED(hr))
    {
        hr = IPropertySetStorage_Open(pPropSetStg, &FMTID_Intshcut, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
        if (SUCCEEDED(hr))
        {
            hr = IPropertyStorage_ReadMultiple(pPropStg, 2, ps, pv);
            if (SUCCEEDED(hr))
            {
3078
                if (pv[0].vt == VT_LPWSTR && pv[0].u.pwszVal && pv[0].u.pwszVal[0])
3079
                {
3080
                    has_icon = TRUE;
3081
                    icon_name = extract_icon( pv[0].u.pwszVal, pv[1].u.iVal, NULL, bWait );
3082

3083 3084
                    WINE_TRACE("URL icon path: %s icon index: %d icon name: %s\n", wine_dbgstr_w(pv[0].u.pwszVal), pv[1].u.iVal, icon_name);
                }
3085 3086
                PropVariantClear(&pv[0]);
                PropVariantClear(&pv[1]);
3087 3088 3089 3090 3091 3092
            }
            IPropertyStorage_Release(pPropStg);
        }
        IPropertySetStorage_Release(pPropSetStg);
    }

3093
    /* fail - try once again after parent process exit */
3094
    if( has_icon && !icon_name )
3095 3096 3097 3098 3099 3100 3101 3102
    {
        if (bWait)
        {
            WINE_WARN("Unable to extract icon, deferring.\n");
            ret = FALSE;
            goto cleanup;
        }
        WINE_ERR("failed to extract icon from %s\n",
3103
                 wine_dbgstr_w( pv[0].u.pwszVal ));
3104 3105
    }

3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
    hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
    if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
    {
        WINE_ERR("failed wait for semaphore\n");
        goto cleanup;
    }
    if (in_desktop_dir(csidl))
    {
        char *location;
        const char *lastEntry;
        lastEntry = strrchr(link_name, '/');
        if (lastEntry == NULL)
            lastEntry = link_name;
        else
            ++lastEntry;
3121
        location = heap_printf("%s/%s.desktop", xdg_desktop_dir, lastEntry);
3122 3123
        if (location)
        {
3124
            r = !write_desktop_entry(NULL, location, lastEntry, start_path, escaped_urlPath, NULL, NULL, icon_name, NULL);
3125 3126
            if (r == 0)
                chmod(location, 0755);
3127 3128 3129 3130
            HeapFree(GetProcessHeap(), 0, location);
        }
    }
    else
3131
        r = !write_menu_entry(unix_link, link_name, start_path, escaped_urlPath, NULL, NULL, icon_name, NULL);
3132
    ret = (r == 0);
3133 3134 3135 3136 3137
    ReleaseSemaphore(hSem, 1, NULL);

cleanup:
    if (hSem)
        CloseHandle(hSem);
3138
    HeapFree( GetProcessHeap(), 0, icon_name );
3139 3140 3141
    HeapFree(GetProcessHeap(), 0, link_name);
    CoTaskMemFree( urlPath );
    HeapFree(GetProcessHeap(), 0, escaped_urlPath);
3142
    HeapFree(GetProcessHeap(), 0, unix_link);
3143 3144 3145
    return ret;
}

3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
static BOOL WaitForParentProcess( void )
{
    PROCESSENTRY32 procentry;
    HANDLE hsnapshot = NULL, hprocess = NULL;
    DWORD ourpid = GetCurrentProcessId();
    BOOL ret = FALSE, rc;

    WINE_TRACE("Waiting for parent process\n");
    if ((hsnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) ==
        INVALID_HANDLE_VALUE)
    {
        WINE_ERR("CreateToolhelp32Snapshot failed, error %d\n", GetLastError());
        goto done;
    }

    procentry.dwSize = sizeof(PROCESSENTRY32);
    rc = Process32First( hsnapshot, &procentry );
    while (rc)
    {
        if (procentry.th32ProcessID == ourpid) break;
        rc = Process32Next( hsnapshot, &procentry );
    }
    if (!rc)
    {
        WINE_WARN("Unable to find current process id %d when listing processes\n", ourpid);
        goto done;
    }

    if ((hprocess = OpenProcess( SYNCHRONIZE, FALSE, procentry.th32ParentProcessID )) ==
        NULL)
    {
        WINE_WARN("OpenProcess failed pid=%d, error %d\n", procentry.th32ParentProcessID,
                 GetLastError());
        goto done;
    }

3182
    if (MsgWaitForMultipleObjects( 1, &hprocess, FALSE, INFINITE, QS_ALLINPUT ) == WAIT_OBJECT_0)
3183 3184 3185 3186 3187 3188 3189 3190 3191
        ret = TRUE;
    else
        WINE_ERR("Unable to wait for parent process, error %d\n", GetLastError());

done:
    if (hprocess) CloseHandle( hprocess );
    if (hsnapshot) CloseHandle( hsnapshot );
    return ret;
}
3192

3193
static BOOL Process_Link( LPCWSTR linkname, BOOL bWait )
3194
{
3195
    IShellLinkW *sl;
3196 3197 3198
    IPersistFile *pf;
    HRESULT r;
    WCHAR fullname[MAX_PATH];
Francois Gouget's avatar
Francois Gouget committed
3199 3200
    DWORD len;

3201
    WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(linkname), bWait);
3202

3203 3204 3205
    if( !linkname[0] )
    {
        WINE_ERR("link name missing\n");
3206
        return FALSE;
3207 3208
    }

Francois Gouget's avatar
Francois Gouget committed
3209 3210
    len=GetFullPathNameW( linkname, MAX_PATH, fullname, NULL );
    if (len==0 || len>MAX_PATH)
3211 3212
    {
        WINE_ERR("couldn't get full path of link file\n");
3213
        return FALSE;
3214 3215 3216
    }

    r = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
3217
                          &IID_IShellLinkW, (LPVOID *) &sl );
3218 3219 3220
    if( FAILED( r ) )
    {
        WINE_ERR("No IID_IShellLink\n");
3221
        return FALSE;
3222 3223
    }

3224
    r = IShellLinkW_QueryInterface( sl, &IID_IPersistFile, (LPVOID*) &pf );
3225 3226 3227
    if( FAILED( r ) )
    {
        WINE_ERR("No IID_IPersistFile\n");
3228
        return FALSE;
3229 3230 3231 3232 3233
    }

    r = IPersistFile_Load( pf, fullname, STGM_READ );
    if( SUCCEEDED( r ) )
    {
3234
        /* If something fails (eg. Couldn't extract icon)
3235
         * wait for parent process and try again
3236
         */
3237 3238 3239 3240 3241
        if( ! InvokeShellLinker( sl, fullname, bWait ) && bWait )
        {
            WaitForParentProcess();
            InvokeShellLinker( sl, fullname, FALSE );
        }
3242
    }
3243 3244 3245 3246
    else
    {
        WINE_ERR("unable to load %s\n", wine_dbgstr_w(linkname));
    }
3247 3248

    IPersistFile_Release( pf );
3249
    IShellLinkW_Release( sl );
3250 3251 3252 3253

    return !r;
}

3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266
static BOOL Process_URL( LPCWSTR urlname, BOOL bWait )
{
    IUniformResourceLocatorW *url;
    IPersistFile *pf;
    HRESULT r;
    WCHAR fullname[MAX_PATH];
    DWORD len;

    WINE_TRACE("%s, wait %d\n", wine_dbgstr_w(urlname), bWait);

    if( !urlname[0] )
    {
        WINE_ERR("URL name missing\n");
3267
        return FALSE;
3268 3269 3270 3271 3272 3273
    }

    len=GetFullPathNameW( urlname, MAX_PATH, fullname, NULL );
    if (len==0 || len>MAX_PATH)
    {
        WINE_ERR("couldn't get full path of URL file\n");
3274
        return FALSE;
3275 3276 3277 3278 3279 3280 3281
    }

    r = CoCreateInstance( &CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
                          &IID_IUniformResourceLocatorW, (LPVOID *) &url );
    if( FAILED( r ) )
    {
        WINE_ERR("No IID_IUniformResourceLocatorW\n");
3282
        return FALSE;
3283 3284 3285 3286 3287 3288
    }

    r = url->lpVtbl->QueryInterface( url, &IID_IPersistFile, (LPVOID*) &pf );
    if( FAILED( r ) )
    {
        WINE_ERR("No IID_IPersistFile\n");
3289
        return FALSE;
3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308
    }
    r = IPersistFile_Load( pf, fullname, STGM_READ );
    if( SUCCEEDED( r ) )
    {
        /* If something fails (eg. Couldn't extract icon)
         * wait for parent process and try again
         */
        if( ! InvokeShellLinkerForURL( url, fullname, bWait ) && bWait )
        {
            WaitForParentProcess();
            InvokeShellLinkerForURL( url, fullname, FALSE );
        }
    }

    IPersistFile_Release( pf );
    url->lpVtbl->Release( url );

    return !r;
}
3309

3310 3311 3312 3313 3314 3315
static void RefreshFileTypeAssociations(void)
{
    HANDLE hSem = NULL;
    char *mime_dir = NULL;
    char *packages_dir = NULL;
    char *applications_dir = NULL;
3316
    BOOL hasChanged;
3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350

    hSem = CreateSemaphoreA( NULL, 1, 1, "winemenubuilder_semaphore");
    if( WAIT_OBJECT_0 != MsgWaitForMultipleObjects( 1, &hSem, FALSE, INFINITE, QS_ALLINPUT ) )
    {
        WINE_ERR("failed wait for semaphore\n");
        CloseHandle(hSem);
        hSem = NULL;
        goto end;
    }

    mime_dir = heap_printf("%s/mime", xdg_data_dir);
    if (mime_dir == NULL)
    {
        WINE_ERR("out of memory\n");
        goto end;
    }
    create_directories(mime_dir);

    packages_dir = heap_printf("%s/packages", mime_dir);
    if (packages_dir == NULL)
    {
        WINE_ERR("out of memory\n");
        goto end;
    }
    create_directories(packages_dir);

    applications_dir = heap_printf("%s/applications", xdg_data_dir);
    if (applications_dir == NULL)
    {
        WINE_ERR("out of memory\n");
        goto end;
    }
    create_directories(applications_dir);

3351
    hasChanged = generate_associations(xdg_data_dir, packages_dir, applications_dir);
3352
    hasChanged |= cleanup_associations();
3353 3354
    if (hasChanged)
    {
3355
        const char *argv[3];
3356

3357 3358 3359
        argv[0] = "update-mime-database";
        argv[1] = mime_dir;
        argv[2] = NULL;
3360
        _spawnvp( _P_DETACH, argv[0], argv );
3361 3362 3363

        argv[0] = "update-desktop-database";
        argv[1] = applications_dir;
3364
        _spawnvp( _P_DETACH, argv[0], argv );
3365
    }
3366

3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377
end:
    if (hSem)
    {
        ReleaseSemaphore(hSem, 1, NULL);
        CloseHandle(hSem);
    }
    HeapFree(GetProcessHeap(), 0, mime_dir);
    HeapFree(GetProcessHeap(), 0, packages_dir);
    HeapFree(GetProcessHeap(), 0, applications_dir);
}

3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
static void cleanup_menus(void)
{
    HKEY hkey;

    hkey = open_menus_reg_key();
    if (hkey)
    {
        int i;
        LSTATUS lret = ERROR_SUCCESS;
        for (i = 0; lret == ERROR_SUCCESS; )
        {
3389 3390
            WCHAR *value = NULL;
            WCHAR *data = NULL;
3391 3392 3393 3394 3395
            DWORD valueSize = 4096;
            DWORD dataSize = 4096;
            while (1)
            {
                lret = ERROR_OUTOFMEMORY;
3396
                value = HeapAlloc(GetProcessHeap(), 0, valueSize * sizeof(WCHAR));
3397 3398
                if (value == NULL)
                    break;
3399
                data = HeapAlloc(GetProcessHeap(), 0, dataSize * sizeof(WCHAR));
3400 3401
                if (data == NULL)
                    break;
3402
                lret = RegEnumValueW(hkey, i, value, &valueSize, NULL, NULL, (BYTE*)data, &dataSize);
3403
                if (lret != ERROR_MORE_DATA)
3404 3405 3406 3407 3408 3409 3410 3411 3412
                    break;
                valueSize *= 2;
                dataSize *= 2;
                HeapFree(GetProcessHeap(), 0, value);
                HeapFree(GetProcessHeap(), 0, data);
                value = data = NULL;
            }
            if (lret == ERROR_SUCCESS)
            {
3413 3414 3415 3416 3417
                char *unix_file;
                char *windows_file;
                unix_file = wchars_to_unix_chars(value);
                windows_file = wchars_to_unix_chars(data);
                if (unix_file != NULL && windows_file != NULL)
3418
                {
3419 3420 3421 3422 3423 3424 3425 3426 3427
                    struct stat filestats;
                    if (stat(windows_file, &filestats) < 0 && errno == ENOENT)
                    {
                        WINE_TRACE("removing menu related file %s\n", unix_file);
                        remove(unix_file);
                        RegDeleteValueW(hkey, value);
                    }
                    else
                        i++;
3428 3429
                }
                else
3430 3431 3432 3433 3434 3435
                {
                    WINE_ERR("out of memory enumerating menus\n");
                    lret = ERROR_OUTOFMEMORY;
                }
                HeapFree(GetProcessHeap(), 0, unix_file);
                HeapFree(GetProcessHeap(), 0, windows_file);
3436 3437
            }
            else if (lret != ERROR_NO_MORE_ITEMS)
3438
                WINE_ERR("error %d reading registry\n", lret);
3439 3440 3441 3442 3443 3444 3445 3446 3447
            HeapFree(GetProcessHeap(), 0, value);
            HeapFree(GetProcessHeap(), 0, data);
        }
        RegCloseKey(hkey);
    }
    else
        WINE_ERR("error opening registry key, menu cleanup failed\n");
}

3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459
static void thumbnail_lnk(LPCWSTR lnkPath, LPCWSTR outputPath)
{
    char *utf8lnkPath = NULL;
    char *utf8OutputPath = NULL;
    WCHAR *winLnkPath = NULL;
    IShellLinkW *shellLink = NULL;
    IPersistFile *persistFile = NULL;
    WCHAR szTmp[MAX_PATH];
    WCHAR szPath[MAX_PATH];
    WCHAR szArgs[INFOTIPSIZE];
    WCHAR szIconPath[MAX_PATH];
    int iconId;
3460
    IStream *stream = NULL;
3461 3462
    ICONDIRENTRY *pIconDirEntries = NULL;
    int numEntries;
3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523
    HRESULT hr;

    utf8lnkPath = wchars_to_utf8_chars(lnkPath);
    if (utf8lnkPath == NULL)
    {
        WINE_ERR("out of memory converting paths\n");
        goto end;
    }

    utf8OutputPath = wchars_to_utf8_chars(outputPath);
    if (utf8OutputPath == NULL)
    {
        WINE_ERR("out of memory converting paths\n");
        goto end;
    }

    winLnkPath = wine_get_dos_file_name(utf8lnkPath);
    if (winLnkPath == NULL)
    {
        WINE_ERR("could not convert %s to DOS path\n", utf8lnkPath);
        goto end;
    }

    hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                          &IID_IShellLinkW, (LPVOID*)&shellLink);
    if (FAILED(hr))
    {
        WINE_ERR("could not create IShellLinkW, error 0x%08X\n", hr);
        goto end;
    }

    hr = IShellLinkW_QueryInterface(shellLink, &IID_IPersistFile, (LPVOID)&persistFile);
    if (FAILED(hr))
    {
        WINE_ERR("could not query IPersistFile, error 0x%08X\n", hr);
        goto end;
    }

    hr = IPersistFile_Load(persistFile, winLnkPath, STGM_READ);
    if (FAILED(hr))
    {
        WINE_ERR("could not read .lnk, error 0x%08X\n", hr);
        goto end;
    }

    get_cmdline(shellLink, szTmp, MAX_PATH, szArgs, INFOTIPSIZE);
    ExpandEnvironmentStringsW(szTmp, szPath, MAX_PATH);
    szTmp[0] = 0;
    IShellLinkW_GetIconLocation(shellLink, szTmp, MAX_PATH, &iconId);
    ExpandEnvironmentStringsW(szTmp, szIconPath, MAX_PATH);

    if(!szPath[0])
    {
        LPITEMIDLIST pidl = NULL;
        IShellLinkW_GetIDList(shellLink, &pidl);
        if (pidl && SHGetPathFromIDListW(pidl, szPath))
            WINE_TRACE("pidl path  : %s\n", wine_dbgstr_w(szPath));
    }

    if (szIconPath[0])
    {
3524
        hr = open_icon(szIconPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3525
        if (SUCCEEDED(hr))
3526
            hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3527 3528 3529
    }
    else
    {
3530
        hr = open_icon(szPath, iconId, FALSE, &stream, &pIconDirEntries, &numEntries);
3531
        if (SUCCEEDED(hr))
3532
            hr = write_native_icon(stream, pIconDirEntries, numEntries, utf8OutputPath, NULL);
3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
    }

end:
    HeapFree(GetProcessHeap(), 0, utf8lnkPath);
    HeapFree(GetProcessHeap(), 0, utf8OutputPath);
    HeapFree(GetProcessHeap(), 0, winLnkPath);
    if (shellLink != NULL)
        IShellLinkW_Release(shellLink);
    if (persistFile != NULL)
        IPersistFile_Release(persistFile);
3543 3544
    if (stream != NULL)
        IStream_Release(stream);
3545
    HeapFree(GetProcessHeap(), 0, pIconDirEntries);
3546 3547
}

3548
static WCHAR *next_token( LPWSTR *p )
3549
{
3550
    LPWSTR token = NULL, t = *p;
3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564

    if( !t )
        return NULL;

    while( t && !token )
    {
        switch( *t )
        {
        case ' ':
            t++;
            continue;
        case '"':
            /* unquote the token */
            token = ++t;
3565
            t = strchrW( token, '"' );
3566 3567 3568 3569 3570 3571 3572 3573
            if( t )
                 *t++ = 0;
            break;
        case 0:
            t = NULL;
            break;
        default:
            token = t;
3574
            t = strchrW( token, ' ' );
3575 3576 3577 3578 3579 3580 3581 3582 3583
            if( t )
                 *t++ = 0;
            break;
        }
    }
    *p = t;
    return token;
}

3584 3585
static BOOL init_xdg(void)
{
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595
    WCHAR shellDesktopPath[MAX_PATH];
    HRESULT hr = SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, SHGFP_TYPE_CURRENT, shellDesktopPath);
    if (SUCCEEDED(hr))
        xdg_desktop_dir = wine_get_unix_file_name(shellDesktopPath);
    if (xdg_desktop_dir == NULL)
    {
        WINE_ERR("error looking up the desktop directory\n");
        return FALSE;
    }

3596 3597 3598 3599 3600 3601
    if (getenv("XDG_CONFIG_HOME"))
        xdg_config_dir = heap_printf("%s/menus/applications-merged", getenv("XDG_CONFIG_HOME"));
    else
        xdg_config_dir = heap_printf("%s/.config/menus/applications-merged", getenv("HOME"));
    if (xdg_config_dir)
    {
3602
        create_directories(xdg_config_dir);
3603
        if (getenv("XDG_DATA_HOME"))
3604
            xdg_data_dir = strdupA(getenv("XDG_DATA_HOME"));
3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
        else
            xdg_data_dir = heap_printf("%s/.local/share", getenv("HOME"));
        if (xdg_data_dir)
        {
            char *buffer;
            create_directories(xdg_data_dir);
            buffer = heap_printf("%s/desktop-directories", xdg_data_dir);
            if (buffer)
            {
                mkdir(buffer, 0777);
                HeapFree(GetProcessHeap(), 0, buffer);
            }
            return TRUE;
        }
        HeapFree(GetProcessHeap(), 0, xdg_config_dir);
    }
3621
    WINE_ERR("out of memory\n");
3622 3623 3624
    return FALSE;
}

3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
static BOOL associations_enabled(void)
{
    BOOL ret = TRUE;
    HKEY hkey;
    BYTE buf[32];
    DWORD len;

    if ((hkey = open_associations_reg_key()))
    {
        len = sizeof(buf);
        if (!RegQueryValueExA(hkey, "Enable", NULL, NULL, buf, &len))
            ret = IS_OPTION_TRUE(buf[0]);
        RegCloseKey( hkey );
    }

    return ret;
}

3643 3644
/***********************************************************************
 *
3645
 *           wWinMain
3646
 */
3647
int PASCAL wWinMain (HINSTANCE hInstance, HINSTANCE prev, LPWSTR cmdline, int show)
3648
{
3649 3650
    static const WCHAR dash_aW[] = {'-','a',0};
    static const WCHAR dash_rW[] = {'-','r',0};
3651
    static const WCHAR dash_tW[] = {'-','t',0};
3652 3653 3654 3655
    static const WCHAR dash_uW[] = {'-','u',0};
    static const WCHAR dash_wW[] = {'-','w',0};

    LPWSTR token = NULL, p;
3656
    BOOL bWait = FALSE;
3657
    BOOL bURL = FALSE;
3658
    HRESULT hr;
3659 3660
    int ret = 0;

3661 3662
    if (!init_xdg())
        return 1;
3663

3664 3665 3666 3667 3668 3669 3670
    hr = CoInitialize(NULL);
    if (FAILED(hr))
    {
        WINE_ERR("could not initialize COM, error 0x%08X\n", hr);
        return 1;
    }

3671 3672 3673 3674 3675
    for( p = cmdline; p && *p; )
    {
        token = next_token( &p );
	if( !token )
	    break;
3676
        if( !strcmpW( token, dash_aW ) )
3677
        {
3678 3679
            if (associations_enabled())
                RefreshFileTypeAssociations();
3680
            continue;
3681
        }
3682
        if( !strcmpW( token, dash_rW ) )
3683 3684
        {
            cleanup_menus();
3685
            continue;
3686
        }
3687
        if( !strcmpW( token, dash_wW ) )
3688
            bWait = TRUE;
3689
        else if ( !strcmpW( token, dash_uW ) )
3690
            bURL = TRUE;
3691 3692 3693 3694 3695 3696 3697 3698 3699 3700
        else if ( !strcmpW( token, dash_tW ) )
        {
            WCHAR *lnkFile = next_token( &p );
            if (lnkFile)
            {
                 WCHAR *outputFile = next_token( &p );
                 if (outputFile)
                     thumbnail_lnk(lnkFile, outputFile);
            }
        }
3701 3702
	else if( token[0] == '-' )
	{
3703
	    WINE_ERR( "unknown option %s\n", wine_dbgstr_w(token) );
3704 3705 3706
	}
        else
        {
3707
            BOOL bRet;
3708

3709
            if (bURL)
3710
                bRet = Process_URL( token, bWait );
3711
            else
3712
                bRet = Process_Link( token, bWait );
3713
            if (!bRet)
3714
            {
3715
                WINE_ERR( "failed to build menu item for %s\n", wine_dbgstr_w(token) );
3716
                ret = 1;
3717 3718 3719 3720
            }
        }
    }

3721
    CoUninitialize();
3722 3723
    return ret;
}