cursoricon.c 95.5 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3 4
/*
 * Cursor and icon support
 *
 * Copyright 1995 Alexandre Julliard
5 6 7 8 9 10
 * Copyright 1996 Martin Von Loewis
 * Copyright 1997 Alex Korobka
 * Copyright 1998 Turchanov Sergey
 * Copyright 2007 Henri Verbeet
 * Copyright 2009 Vincent Povirk for CodeWeavers
 * Copyright 2016 Dmitry Timoshkov
11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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
24
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Alexandre Julliard's avatar
Alexandre Julliard committed
25 26
 */

27
#include <assert.h>
28
#include <stdarg.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
29 30
#include <string.h>
#include <stdlib.h>
31

32
#include "windef.h"
33
#include "winbase.h"
34
#include "wingdi.h"
35
#include "winerror.h"
36
#include "winnls.h"
37
#include "wine/exception.h"
38
#include "wine/server.h"
39
#include "controls.h"
40
#include "win.h"
41
#include "user_private.h"
42
#include "wine/list.h"
43
#include "wine/debug.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
44

45
WINE_DEFAULT_DEBUG_CHANNEL(cursor);
46 47
WINE_DECLARE_DEBUG_CHANNEL(icon);
WINE_DECLARE_DEBUG_CHANNEL(resource);
48

49 50 51 52 53
#define RIFF_FOURCC( c0, c1, c2, c3 ) \
        ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
        ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
#define PNG_SIGN RIFF_FOURCC(0x89,'P','N','G')

54
static struct list icon_cache = LIST_INIT( icon_cache );
55

56 57 58 59
/**********************************************************************
 * User objects management
 */

60
struct cursoricon_frame
61
{
62 63
    UINT               width;    /* frame-specific width */
    UINT               height;   /* frame-specific height */
64
    UINT               delay;    /* frame-specific delay between this frame and the next (in jiffies) */
65
    HBITMAP            color;    /* color bitmap */
66
    HBITMAP            alpha;    /* pre-multiplied alpha bitmap for 32-bpp icons */
67
    HBITMAP            mask;     /* mask bitmap (followed by color for 1-bpp icons) */
68 69 70 71
};

struct cursoricon_object
{
72
    struct user_object      obj;        /* object header */
73
    struct list             entry;      /* entry in shared icons list */
74
    ULONG_PTR               param;      /* opaque param used by 16-bit code */
75 76
    HMODULE                 module;     /* module for icons loaded from resources */
    LPWSTR                  resname;    /* resource name for icons loaded from resources */
77
    HRSRC                   rsrc;       /* resource for shared icons */
78
    BOOL                    is_icon;    /* whether icon or cursor */
79 80
    BOOL                    is_ani;     /* whether this object is a static cursor or an animated cursor */
    UINT                    delay;      /* delay between this frame and the next (in jiffies) */
81
    POINT                   hotspot;
82 83
};

84
struct static_cursoricon_object
85
{
86 87 88 89 90 91 92 93 94 95 96 97
    struct cursoricon_object shared;
    struct cursoricon_frame  frame;      /* frame-specific icon data */
};

struct animated_cursoricon_object
{
    struct cursoricon_object shared;
    UINT                     num_frames; /* number of frames in the icon/cursor */
    UINT                     num_steps;  /* number of sequence steps in the icon/cursor */
    HICON                    frames[1];  /* list of animated cursor frames */
};

98
static HBITMAP create_color_bitmap( int width, int height )
99
{
100 101 102 103 104
    HDC hdc = get_display_dc();
    HBITMAP ret = CreateCompatibleBitmap( hdc, width, height );
    release_display_dc( hdc );
    return ret;
}
105

106 107 108 109 110 111
static int get_display_bpp(void)
{
    HDC hdc = get_display_dc();
    int ret = GetDeviceCaps( hdc, BITSPIXEL );
    release_display_dc( hdc );
    return ret;
112 113
}

114
static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
115

116 117
static const struct png_funcs *png_funcs;

118 119
static BOOL WINAPI load_libpng( INIT_ONCE *once, void *param, void **context )
{
120
    __wine_init_unix_lib( user32_module, DLL_PROCESS_ATTACH, NULL, &png_funcs );
121 122 123
    return TRUE;
}

124 125
static BOOL have_libpng(void)
{
126
    return InitOnceExecuteOnce( &init_once, load_libpng, NULL, NULL ) && png_funcs;
127 128
}

129
static HICON alloc_icon_handle( BOOL is_ani, UINT num_steps )
130 131 132
{
    struct cursoricon_object *obj;
    int icon_size;
133
    HICON handle;
134 135

    if (is_ani)
136
        icon_size = FIELD_OFFSET( struct animated_cursoricon_object, frames[num_steps] );
137 138 139
    else
        icon_size = sizeof( struct static_cursoricon_object );
    obj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, icon_size );
140
    if (!obj) return NULL;
141

142
    obj->delay = 0;
143 144 145 146 147
    obj->is_ani = is_ani;
    if (is_ani)
    {
        struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;

148 149
        ani_icon_data->num_steps = num_steps;
        ani_icon_data->num_frames = num_steps; /* changed later for some animated cursors */
150
    }
151 152 153 154

    if (!(handle = alloc_user_handle( &obj->obj, USER_ICON )))
        HeapFree( GetProcessHeap(), 0, obj );
    return handle;
155 156
}

157
static struct cursoricon_object *get_icon_ptr( HICON handle )
158 159 160 161 162 163 164
{
    struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
    if (obj == OBJ_OTHER_PROCESS)
    {
        WARN( "icon handle %p from other process\n", handle );
        obj = NULL;
    }
165
    return obj;
166 167
}

168 169
static struct cursoricon_frame *get_icon_frame( struct cursoricon_object *obj, int istep )
{
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    struct static_cursoricon_object *req_frame;

    if (obj->is_ani)
    {
        struct animated_cursoricon_object *ani_icon_data;
        struct cursoricon_object *frameobj;

        ani_icon_data = (struct animated_cursoricon_object *) obj;
        if (!(frameobj = get_icon_ptr( ani_icon_data->frames[istep] )))
            return 0;
        req_frame = (struct static_cursoricon_object *) frameobj;
    }
    else
        req_frame = (struct static_cursoricon_object *) obj;

    return &req_frame->frame;
186 187
}

188
static void release_icon_frame( struct cursoricon_object *obj, struct cursoricon_frame *frame )
189
{
190 191 192 193 194
    if (obj->is_ani)
    {
        struct cursoricon_object *frameobj;

        frameobj = (struct cursoricon_object *) (((char *)frame) - FIELD_OFFSET(struct static_cursoricon_object, frame));
195
        release_user_handle_ptr( frameobj );
196
    }
197 198
}

199 200
static UINT get_icon_steps( struct cursoricon_object *obj )
{
201 202 203 204 205 206 207 208
    if (obj->is_ani)
    {
        struct animated_cursoricon_object *ani_icon_data;

        ani_icon_data = (struct animated_cursoricon_object *) obj;
        return ani_icon_data->num_steps;
    }
    return 1;
209 210
}

211 212 213 214 215 216 217 218
static BOOL free_icon_handle( HICON handle )
{
    struct cursoricon_object *obj = free_user_handle( handle, USER_ICON );

    if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
    else if (obj)
    {
        ULONG_PTR param = obj->param;
219 220
        UINT i;

221 222
        assert( !obj->rsrc );  /* shared icons can't be freed */

223
        if (!obj->is_ani)
224
        {
225
            struct cursoricon_frame *frame = get_icon_frame( obj, 0 );
226 227 228 229

            if (frame->alpha) DeleteObject( frame->alpha );
            if (frame->color) DeleteObject( frame->color );
            DeleteObject( frame->mask );
230
            release_icon_frame( obj, frame );
231
        }
232 233 234 235
        else
        {
            struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
            for (i=0; i<ani_icon_data->num_steps; i++)
            {
                HICON hFrame = ani_icon_data->frames[i];

                if (hFrame)
                {
                    UINT j;

                    free_icon_handle( ani_icon_data->frames[i] );
                    for (j=0; j<ani_icon_data->num_steps; j++)
                    {
                        if (ani_icon_data->frames[j] == hFrame)
                            ani_icon_data->frames[j] = 0;
                    }
                }
            }
252
        }
253
        if (!IS_INTRESOURCE( obj->resname )) HeapFree( GetProcessHeap(), 0, obj->resname );
254 255
        HeapFree( GetProcessHeap(), 0, obj );
        if (wow_handlers.free_icon_param && param) wow_handlers.free_icon_param( param );
256
        USER_Driver->pDestroyCursorIcon( handle );
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        return TRUE;
    }
    return FALSE;
}

ULONG_PTR get_icon_param( HICON handle )
{
    ULONG_PTR ret = 0;
    struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );

    if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
    else if (obj)
    {
        ret = obj->param;
        release_user_handle_ptr( obj );
    }
    return ret;
}

ULONG_PTR set_icon_param( HICON handle, ULONG_PTR param )
{
    ULONG_PTR ret = 0;
    struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );

    if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
    else if (obj)
    {
        ret = obj->param;
        obj->param = param;
        release_user_handle_ptr( obj );
    }
    return ret;
}


292 293 294 295
/***********************************************************************
 *             map_fileW
 *
 * Helper function to map a file to memory:
296
 *  name			-	file name
297
 *  [RETURN] ptr		-	pointer to mapped file
298
 *  [RETURN] filesize           -       pointer size of file to be stored if not NULL
299
 */
300
static const void *map_fileW( LPCWSTR name, LPDWORD filesize )
301 302 303 304 305 306 307 308
{
    HANDLE hFile, hMapping;
    LPVOID ptr = NULL;

    hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
                         OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
    if (hFile != INVALID_HANDLE_VALUE)
    {
309
        hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
310 311 312 313
        if (hMapping)
        {
            ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
            CloseHandle( hMapping );
314 315
            if (filesize)
                *filesize = GetFileSize( hFile, NULL );
316
        }
317
        CloseHandle( hFile );
318 319 320 321 322
    }
    return ptr;
}


323
/***********************************************************************
324
 *          get_dib_image_size
325
 *
326
 * Return the size of a DIB bitmap in bytes.
327
 */
328
static int get_dib_image_size( int width, int height, int depth )
329
{
330
    return (((width * depth + 31) / 8) & ~3) * abs( height );
331 332 333 334 335 336 337 338
}


/***********************************************************************
 *           bitmap_info_size
 *
 * Return the size of the bitmap info structure including color table.
 */
339
int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
340
{
341
    unsigned int colors, size, masks = 0;
342 343 344

    if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
    {
345
        const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
346 347 348 349 350 351 352
        colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
        return sizeof(BITMAPCOREHEADER) + colors *
             ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
    }
    else  /* assume BITMAPINFOHEADER */
    {
        colors = info->bmiHeader.biClrUsed;
353 354
        if (colors > 256) /* buffer overflow otherwise */
                colors = 256;
355 356
        if (!colors && (info->bmiHeader.biBitCount <= 8))
            colors = 1 << info->bmiHeader.biBitCount;
357
        if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
358 359
        size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
        return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
360 361 362 363
    }
}


364 365 366 367 368 369 370
/***********************************************************************
 *             copy_bitmap
 *
 * Helper function to duplicate a bitmap.
 */
static HBITMAP copy_bitmap( HBITMAP bitmap )
{
371 372
    HDC src, dst = 0;
    HBITMAP new_bitmap = 0;
373 374 375 376 377
    BITMAP bmp;

    if (!bitmap) return 0;
    if (!GetObjectW( bitmap, sizeof(bmp), &bmp )) return 0;

378 379 380 381 382 383 384 385 386
    if ((src = CreateCompatibleDC( 0 )) && (dst = CreateCompatibleDC( 0 )))
    {
        SelectObject( src, bitmap );
        if ((new_bitmap = CreateCompatibleBitmap( src, bmp.bmWidth, bmp.bmHeight )))
        {
            SelectObject( dst, new_bitmap );
            BitBlt( dst, 0, 0, bmp.bmWidth, bmp.bmHeight, src, 0, 0, SRCCOPY );
        }
    }
387 388 389 390 391 392
    DeleteDC( dst );
    DeleteDC( src );
    return new_bitmap;
}


393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
/***********************************************************************
 *          is_dib_monochrome
 *
 * Returns whether a DIB can be converted to a monochrome DDB.
 *
 * A DIB can be converted if its color table contains only black and
 * white. Black must be the first color in the color table.
 *
 * Note : If the first color in the color table is white followed by
 *        black, we can't convert it to a monochrome DDB with
 *        SetDIBits, because black and white would be inverted.
 */
static BOOL is_dib_monochrome( const BITMAPINFO* info )
{
    if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
    {
409
        const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
410

411 412
        if (((const BITMAPCOREINFO*)info)->bmciHeader.bcBitCount != 1) return FALSE;

413 414 415 416 417 418 419 420 421 422 423 424 425
        /* Check if the first color is black */
        if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
        {
            rgb++;

            /* Check if the second color is white */
            return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
                 && (rgb->rgbtBlue == 0xff));
        }
        else return FALSE;
    }
    else  /* assume BITMAPINFOHEADER */
    {
Eric Pouech's avatar
Eric Pouech committed
426
        const RGBQUAD *rgb = info->bmiColors;
427

428 429
        if (info->bmiHeader.biBitCount != 1) return FALSE;

430 431 432 433 434 435 436 437 438 439 440 441 442 443
        /* Check if the first color is black */
        if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
            (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
        {
            rgb++;

            /* Check if the second color is white */
            return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
                 && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
        }
        else return FALSE;
    }
}

444 445 446 447
/***********************************************************************
 *           DIB_GetBitmapInfo
 *
 * Get the info from a bitmap header.
448
 * Return 1 for INFOHEADER, 0 for COREHEADER, -1 in case of failure.
449 450 451 452 453 454
 */
static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
                              LONG *height, WORD *bpp, DWORD *compr )
{
    if (header->biSize == sizeof(BITMAPCOREHEADER))
    {
455
        const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
456 457 458 459 460 461
        *width  = core->bcWidth;
        *height = core->bcHeight;
        *bpp    = core->bcBitCount;
        *compr  = 0;
        return 0;
    }
462 463 464
    else if (header->biSize == sizeof(BITMAPINFOHEADER) ||
             header->biSize == sizeof(BITMAPV4HEADER) ||
             header->biSize == sizeof(BITMAPV5HEADER))
465
    {
466 467 468 469 470
        *width  = header->biWidth;
        *height = header->biHeight;
        *bpp    = header->biBitCount;
        *compr  = header->biCompression;
        return 1;
471
    }
472
    WARN("unknown/wrong size (%u) for header\n", header->biSize);
473 474
    return -1;
}
475

476 477 478 479 480
/**********************************************************************
 *              get_icon_size
 */
BOOL get_icon_size( HICON handle, SIZE *size )
{
481
    struct cursoricon_object *info;
482
    struct cursoricon_frame *frame;
483

484
    if (!(info = get_icon_ptr( handle ))) return FALSE;
485 486 487
    frame = get_icon_frame( info, 0 );
    size->cx = frame->width;
    size->cy = frame->height;
488
    release_icon_frame( info, frame);
489
    release_user_handle_ptr( info );
490 491 492
    return TRUE;
}

493 494 495 496
/*
 *  The following macro functions account for the irregularities of
 *   accessing cursor and icon resources in files and resource entries.
 */
497
typedef BOOL (*fnGetCIEntry)( LPCVOID dir, DWORD size, int n,
498 499
                              int *width, int *height, int *bits );

Alexandre Julliard's avatar
Alexandre Julliard committed
500 501 502
/**********************************************************************
 *	    CURSORICON_FindBestIcon
 *
503
 * Find the icon closest to the requested size and bit depth.
Alexandre Julliard's avatar
Alexandre Julliard committed
504
 */
505
static int CURSORICON_FindBestIcon( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
506
                                    int width, int height, int depth, UINT loadflags )
Alexandre Julliard's avatar
Alexandre Julliard committed
507
{
508
    int i, cx, cy, bits, bestEntry = -1;
509 510
    UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
    UINT iTempXDiff, iTempYDiff, iTempColorDiff;
Alexandre Julliard's avatar
Alexandre Julliard committed
511

512 513 514
    /* Find Best Fit */
    iTotalDiff = 0xFFFFFFFF;
    iColorDiff = 0xFFFFFFFF;
515 516 517 518 519 520 521 522 523

    if (loadflags & LR_DEFAULTSIZE)
    {
        if (!width) width = GetSystemMetrics( SM_CXICON );
        if (!height) height = GetSystemMetrics( SM_CYICON );
    }
    else if (!width && !height)
    {
        /* use the size of the first entry */
524
        if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
525 526 527
        iTotalDiff = 0;
    }

528
    for ( i = 0; iTotalDiff && get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
529
    {
530 531
        iTempXDiff = abs(width - cx);
        iTempYDiff = abs(height - cy);
Alexandre Julliard's avatar
Alexandre Julliard committed
532

533
        if(iTotalDiff > (iTempXDiff + iTempYDiff))
Alexandre Julliard's avatar
Alexandre Julliard committed
534
        {
535 536
            iXDiff = iTempXDiff;
            iYDiff = iTempYDiff;
537
            iTotalDiff = iXDiff + iYDiff;
Alexandre Julliard's avatar
Alexandre Julliard committed
538
        }
539
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
540

541
    /* Find Best Colors for Best Fit */
542
    for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
543
    {
544 545
        TRACE("entry %d: %d x %d, %d bpp\n", i, cx, cy, bits);

546
        if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
Alexandre Julliard's avatar
Alexandre Julliard committed
547
        {
548
            iTempColorDiff = abs(depth - bits);
549
            if(iColorDiff > iTempColorDiff)
550
            {
551
                bestEntry = i;
552
                iColorDiff = iTempColorDiff;
553
            }
554 555
        }
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
556 557 558 559

    return bestEntry;
}

560
static BOOL CURSORICON_GetResIconEntry( LPCVOID dir, DWORD size, int n,
561 562
                                        int *width, int *height, int *bits )
{
563 564
    const CURSORICONDIR *resdir = dir;
    const ICONRESDIR *icon;
565 566 567

    if ( resdir->idCount <= n )
        return FALSE;
568 569
    if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
        return FALSE;
570 571
    icon = &resdir->idEntries[n].ResInfo.icon;
    *width = icon->bWidth;
572
    *height = icon->bHeight;
573
    *bits = resdir->idEntries[n].wBitCount;
574
    if (!*width && !*height && have_libpng()) *width = *height = 256;
575 576
    return TRUE;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
577 578 579 580 581

/**********************************************************************
 *	    CURSORICON_FindBestCursor
 *
 * Find the cursor closest to the requested size.
582 583
 *
 * FIXME: parameter 'color' ignored.
Alexandre Julliard's avatar
Alexandre Julliard committed
584
 */
585
static int CURSORICON_FindBestCursor( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
586
                                      int width, int height, int depth, UINT loadflags )
Alexandre Julliard's avatar
Alexandre Julliard committed
587
{
588
    int i, maxwidth, maxheight, maxbits, cx, cy, bits, bestEntry = -1;
Alexandre Julliard's avatar
Alexandre Julliard committed
589

590 591 592 593 594 595 596 597
    if (loadflags & LR_DEFAULTSIZE)
    {
        if (!width) width = GetSystemMetrics( SM_CXCURSOR );
        if (!height) height = GetSystemMetrics( SM_CYCURSOR );
    }
    else if (!width && !height)
    {
        /* use the first entry */
598
        if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
599 600 601
        return 0;
    }

Alexandre Julliard's avatar
Alexandre Julliard committed
602 603
    /* First find the largest one smaller than or equal to the requested size*/

604
    maxwidth = maxheight = maxbits = 0;
605
    for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
606
    {
607 608
        if (cx > width || cy > height) continue;
        if (cx < maxwidth || cy < maxheight) continue;
609
        if (cx == maxwidth && cy == maxheight)
Alexandre Julliard's avatar
Alexandre Julliard committed
610
        {
611 612 613 614 615
            if (loadflags & LR_MONOCHROME)
            {
                if (maxbits && bits >= maxbits) continue;
            }
            else if (bits <= maxbits) continue;
Alexandre Julliard's avatar
Alexandre Julliard committed
616
        }
617 618 619 620
        bestEntry = i;
        maxwidth  = cx;
        maxheight = cy;
        maxbits = bits;
621 622
    }
    if (bestEntry != -1) return bestEntry;
Alexandre Julliard's avatar
Alexandre Julliard committed
623 624 625 626

    /* Now find the smallest one larger than the requested size */

    maxwidth = maxheight = 255;
627
    for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
628
    {
629
        if (cx > maxwidth || cy > maxheight) continue;
630
        if (cx == maxwidth && cy == maxheight)
Alexandre Julliard's avatar
Alexandre Julliard committed
631
        {
632 633 634 635 636
            if (loadflags & LR_MONOCHROME)
            {
                if (maxbits && bits >= maxbits) continue;
            }
            else if (bits <= maxbits) continue;
Alexandre Julliard's avatar
Alexandre Julliard committed
637
        }
638 639 640 641
        bestEntry = i;
        maxwidth  = cx;
        maxheight = cy;
        maxbits = bits;
642
    }
643
    if (bestEntry == -1) bestEntry = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
644 645 646 647

    return bestEntry;
}

648
static BOOL CURSORICON_GetResCursorEntry( LPCVOID dir, DWORD size, int n,
649 650
                                          int *width, int *height, int *bits )
{
651 652
    const CURSORICONDIR *resdir = dir;
    const CURSORDIR *cursor;
653 654 655

    if ( resdir->idCount <= n )
        return FALSE;
656 657
    if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
        return FALSE;
658 659 660 661
    cursor = &resdir->idEntries[n].ResInfo.cursor;
    *width = cursor->wWidth;
    *height = cursor->wHeight;
    *bits = resdir->idEntries[n].wBitCount;
662
    if (*height == *width * 2) *height /= 2;
663 664 665
    return TRUE;
}

666
static const CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( const CURSORICONDIR * dir, DWORD size,
667 668
                                                             int width, int height, int depth,
                                                             UINT loadflags )
669 670 671
{
    int n;

672
    n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetResIconEntry,
673
                                 width, height, depth, loadflags );
674 675 676 677 678
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

679
static const CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( const CURSORICONDIR *dir, DWORD size,
680 681
                                                               int width, int height, int depth,
                                                               UINT loadflags )
682
{
683
    int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetResCursorEntry,
684
                                       width, height, depth, loadflags );
685 686 687 688 689
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

690
static BOOL CURSORICON_GetFileEntry( LPCVOID dir, DWORD size, int n,
691
                                     int *width, int *height, int *bits )
692
{
693 694 695
    const CURSORICONFILEDIR *filedir = dir;
    const CURSORICONFILEDIRENTRY *entry;
    const BITMAPINFOHEADER *info;
696

697 698
    if ( filedir->idCount <= n )
        return FALSE;
699 700
    if ((const char *)&filedir->idEntries[n + 1] - (const char *)dir > size)
        return FALSE;
701
    entry = &filedir->idEntries[n];
702
    if (entry->dwDIBOffset > size - sizeof(info->biSize)) return FALSE;
703
    info = (const BITMAPINFOHEADER *)((const char *)dir + entry->dwDIBOffset);
704 705

    if (info->biSize == PNG_SIGN)
706
    {
707
        if (have_libpng()) return png_funcs->get_png_info(info, size, width, height, bits);
708 709 710
        *width = *height = *bits = 0;
        return TRUE;
    }
711

712 713 714 715 716 717 718 719 720 721 722
    if (info->biSize != sizeof(BITMAPCOREHEADER))
    {
        if ((const char *)(info + 1) - (const char *)dir > size) return FALSE;
        *bits = info->biBitCount;
    }
    else
    {
        const BITMAPCOREHEADER *coreinfo = (const BITMAPCOREHEADER *)((const char *)dir + entry->dwDIBOffset);
        if ((const char *)(coreinfo + 1) - (const char *)dir > size) return FALSE;
        *bits = coreinfo->bcBitCount;
    }
723 724
    *width = entry->bWidth;
    *height = entry->bHeight;
725
    return TRUE;
726
}
Alexandre Julliard's avatar
Alexandre Julliard committed
727

728
static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( const CURSORICONFILEDIR *dir, DWORD size,
729 730
                                                                    int width, int height, int depth,
                                                                    UINT loadflags )
731
{
732
    int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetFileEntry,
733
                                       width, height, depth, loadflags );
734 735 736 737 738
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

739
static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( const CURSORICONFILEDIR *dir, DWORD size,
740 741
                                                                  int width, int height, int depth,
                                                                  UINT loadflags )
742
{
743
    int n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetFileEntry,
744
                                     width, height, depth, loadflags );
745 746 747 748
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}
Alexandre Julliard's avatar
Alexandre Julliard committed
749

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
/***********************************************************************
 *          bmi_has_alpha
 */
static BOOL bmi_has_alpha( const BITMAPINFO *info, const void *bits )
{
    int i;
    BOOL has_alpha = FALSE;
    const unsigned char *ptr = bits;

    if (info->bmiHeader.biBitCount != 32) return FALSE;
    for (i = 0; i < info->bmiHeader.biWidth * abs(info->bmiHeader.biHeight); i++, ptr += 4)
        if ((has_alpha = (ptr[3] != 0))) break;
    return has_alpha;
}

/***********************************************************************
 *          create_alpha_bitmap
 *
 * Create the alpha bitmap for a 32-bpp icon that has an alpha channel.
 */
770
static HBITMAP create_alpha_bitmap( HBITMAP color, const BITMAPINFO *src_info, const void *color_bits )
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
{
    HBITMAP alpha = 0;
    BITMAPINFO *info = NULL;
    BITMAP bm;
    HDC hdc;
    void *bits;
    unsigned char *ptr;
    int i;

    if (!GetObjectW( color, sizeof(bm), &bm )) return 0;
    if (bm.bmBitsPixel != 32) return 0;

    if (!(hdc = CreateCompatibleDC( 0 ))) return 0;
    if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto done;
    info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info->bmiHeader.biWidth = bm.bmWidth;
    info->bmiHeader.biHeight = -bm.bmHeight;
    info->bmiHeader.biPlanes = 1;
    info->bmiHeader.biBitCount = 32;
    info->bmiHeader.biCompression = BI_RGB;
    info->bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
    info->bmiHeader.biXPelsPerMeter = 0;
    info->bmiHeader.biYPelsPerMeter = 0;
    info->bmiHeader.biClrUsed = 0;
    info->bmiHeader.biClrImportant = 0;
    if (!(alpha = CreateDIBSection( hdc, info, DIB_RGB_COLORS, &bits, NULL, 0 ))) goto done;

    if (src_info)
    {
        SelectObject( hdc, alpha );
        StretchDIBits( hdc, 0, 0, bm.bmWidth, bm.bmHeight,
                       0, 0, src_info->bmiHeader.biWidth, src_info->bmiHeader.biHeight,
                       color_bits, src_info, DIB_RGB_COLORS, SRCCOPY );

    }
    else
    {
        GetDIBits( hdc, color, 0, bm.bmHeight, bits, info, DIB_RGB_COLORS );
        if (!bmi_has_alpha( info, bits ))
        {
            DeleteObject( alpha );
            alpha = 0;
            goto done;
        }
    }

    /* pre-multiply by alpha */
    for (i = 0, ptr = bits; i < bm.bmWidth * bm.bmHeight; i++, ptr += 4)
    {
        unsigned int alpha = ptr[3];
        ptr[0] = ptr[0] * alpha / 255;
        ptr[1] = ptr[1] * alpha / 255;
        ptr[2] = ptr[2] * alpha / 255;
    }

done:
    DeleteDC( hdc );
    HeapFree( GetProcessHeap(), 0, info );
    return alpha;
}


833
/***********************************************************************
834
 *          create_icon_from_bmi
835
 *
836
 * Create an icon from its BITMAPINFO.
837
 */
838 839 840
static HICON create_icon_from_bmi( const BITMAPINFO *bmi, DWORD maxsize, HMODULE module, LPCWSTR resname,
                                   HRSRC rsrc, POINT hotspot, BOOL bIcon, INT width, INT height,
                                   UINT cFlag )
841
{
842
    DWORD size, color_size, mask_size;
843
    HBITMAP color = 0, mask = 0, alpha = 0;
844
    const void *color_bits, *mask_bits;
845
    void *alpha_mask_bits = NULL;
846
    BITMAPINFO *bmi_copy;
847
    BOOL ret = FALSE;
848 849
    BOOL do_stretch;
    HICON hObj = 0;
850
    HDC hdc = 0;
851 852 853
    LONG bmi_width, bmi_height;
    WORD bpp;
    DWORD compr;
854

855 856
    /* Check bitmap header */

857 858 859 860
    if (bmi->bmiHeader.biSize == PNG_SIGN)
    {
        BITMAPINFO *bmi_png;

861 862
        if (!have_libpng()) return 0;
        bmi_png = png_funcs->load_png( (const char *)bmi, &maxsize );
863 864 865 866 867 868 869 870 871 872
        if (bmi_png)
        {
            hObj = create_icon_from_bmi( bmi_png, maxsize, module, resname,
                                         rsrc, hotspot, bIcon, width, height, cFlag );
            HeapFree( GetProcessHeap(), 0, bmi_png );
            return hObj;
        }
        return 0;
    }

873 874 875 876 877 878 879 880 881 882
    if (maxsize < sizeof(BITMAPCOREHEADER))
    {
        WARN( "invalid size %u\n", maxsize );
        return 0;
    }
    if (maxsize < bmi->bmiHeader.biSize)
    {
        WARN( "invalid header size %u\n", bmi->bmiHeader.biSize );
        return 0;
    }
883 884
    if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
         (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER)  ||
885 886
         (bmi->bmiHeader.biCompression != BI_RGB &&
          bmi->bmiHeader.biCompression != BI_BITFIELDS)) )
887
    {
888 889 890 891 892
        WARN( "invalid bitmap header %u\n", bmi->bmiHeader.biSize );
        return 0;
    }

    size = bitmap_info_size( bmi, DIB_RGB_COLORS );
893 894 895 896
    DIB_GetBitmapInfo(&bmi->bmiHeader, &bmi_width, &bmi_height, &bpp, &compr);
    color_size = get_dib_image_size( bmi_width, bmi_height / 2,
                                     bpp );
    mask_size = get_dib_image_size( bmi_width, bmi_height / 2, 1 );
897 898 899 900
    if (size > maxsize || color_size > maxsize - size)
    {
        WARN( "truncated file %u < %u+%u+%u\n", maxsize, size, color_size, mask_size );
        return 0;
901
    }
902
    if (mask_size > maxsize - size - color_size) mask_size = 0;  /* no mask */
903 904 905 906 907 908 909 910

    if (cFlag & LR_DEFAULTSIZE)
    {
        if (!width) width = GetSystemMetrics( bIcon ? SM_CXICON : SM_CXCURSOR );
        if (!height) height = GetSystemMetrics( bIcon ? SM_CYICON : SM_CYCURSOR );
    }
    else
    {
911 912
        if (!width) width = bmi_width;
        if (!height) height = bmi_height/2;
913
    }
914 915
    do_stretch = (bmi_height/2 != height) ||
                 (bmi_width != width);
916 917 918 919 920 921 922 923 924

    /* Scale the hotspot */
    if (bIcon)
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
    }
    else if (do_stretch)
    {
925 926
        hotspot.x = (hotspot.x * width) / bmi_width;
        hotspot.y = (hotspot.y * height) / (bmi_height / 2);
927 928 929 930
    }

    if (!(bmi_copy = HeapAlloc( GetProcessHeap(), 0, max( size, FIELD_OFFSET( BITMAPINFO, bmiColors[2] )))))
        return 0;
931 932
    if (!(hdc = CreateCompatibleDC( 0 ))) goto done;

933
    memcpy( bmi_copy, bmi, size );
934 935 936 937 938
    if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
        bmi_copy->bmiHeader.biHeight /= 2;
    else
        ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcHeight /= 2;
    bmi_height /= 2;
939

940
    color_bits = (const char*)bmi + size;
941
    mask_bits = (const char*)color_bits + color_size;
942

943
    alpha = 0;
944
    if (is_dib_monochrome( bmi ))
945
    {
946 947
        if (!(mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
        color = 0;
948 949

        /* copy color data into second half of mask bitmap */
950
        SelectObject( hdc, mask );
951
        StretchDIBits( hdc, 0, height, width, height,
952
                       0, 0, bmi_width, bmi_height,
953
                       color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
954 955 956
    }
    else
    {
957
        if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
958
        if (!(color = create_color_bitmap( width, height )))
959
        {
960
            DeleteObject( mask );
961 962
            goto done;
        }
963
        SelectObject( hdc, color );
964
        StretchDIBits( hdc, 0, 0, width, height,
965
                       0, 0, bmi_width, bmi_height,
966
                       color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
967

968
        if (bmi_has_alpha( bmi_copy, color_bits ))
969
        {
970
            alpha = create_alpha_bitmap( color, bmi_copy, color_bits );
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
            if (!mask_size)  /* generate mask from alpha */
            {
                LONG x, y, dst_stride = ((bmi_width + 31) / 8) & ~3;

                if ((alpha_mask_bits = heap_calloc( bmi_height, dst_stride )))
                {
                    static const unsigned char masks[] = { 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 };
                    const DWORD *src = color_bits;
                    unsigned char *dst = alpha_mask_bits;

                    for (y = 0; y < bmi_height; y++, src += bmi_width, dst += dst_stride)
                        for (x = 0; x < bmi_width; x++)
                            if (src[x] >> 24 != 0xff) dst[x >> 3] |= masks[x & 7];

                    mask_bits = alpha_mask_bits;
                    mask_size = bmi_height * dst_stride;
                }
            }
        }
990

991
        /* convert info to monochrome to copy the mask */
992
        if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
993
        {
994
            RGBQUAD *rgb = bmi_copy->bmiColors;
995

996
            bmi_copy->bmiHeader.biBitCount = 1;
997
            bmi_copy->bmiHeader.biClrUsed = bmi_copy->bmiHeader.biClrImportant = 2;
998 999 1000 1001 1002 1003
            rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
            rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
            rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
        }
        else
        {
1004
            RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)bmi_copy) + 1);
1005

1006
            ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcBitCount = 1;
1007 1008 1009 1010 1011
            rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
            rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
        }
    }

1012 1013 1014 1015
    if (mask_size)
    {
        SelectObject( hdc, mask );
        StretchDIBits( hdc, 0, 0, width, height,
1016
                       0, 0, bmi_width, bmi_height,
1017 1018
                       mask_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
    }
1019 1020 1021 1022
    ret = TRUE;

done:
    DeleteDC( hdc );
1023
    HeapFree( GetProcessHeap(), 0, bmi_copy );
1024
    HeapFree( GetProcessHeap(), 0, alpha_mask_bits );
1025

1026
    if (ret)
1027
        hObj = alloc_icon_handle( FALSE, 0 );
Alexandre Julliard's avatar
Alexandre Julliard committed
1028
    if (hObj)
Alexandre Julliard's avatar
Alexandre Julliard committed
1029
    {
1030
        struct cursoricon_object *info = get_icon_ptr( hObj );
1031
        struct cursoricon_frame *frame;
Alexandre Julliard's avatar
Alexandre Julliard committed
1032

1033
        info->is_icon = bIcon;
1034
        info->module  = module;
1035
        info->hotspot = hotspot;
1036 1037 1038 1039 1040 1041 1042
        frame = get_icon_frame( info, 0 );
        frame->delay  = ~0;
        frame->width  = width;
        frame->height = height;
        frame->color  = color;
        frame->mask   = mask;
        frame->alpha  = alpha;
1043
        release_icon_frame( info, frame );
1044 1045
        if (!IS_INTRESOURCE(resname))
        {
1046 1047
            info->resname = HeapAlloc( GetProcessHeap(), 0, (lstrlenW(resname) + 1) * sizeof(WCHAR) );
            if (info->resname) lstrcpyW( info->resname, resname );
1048 1049 1050
        }
        else info->resname = MAKEINTRESOURCEW( LOWORD(resname) );

1051 1052 1053 1054 1055
        if (module && (cFlag & LR_SHARED))
        {
            info->rsrc = rsrc;
            list_add_head( &icon_cache, &info->entry );
        }
1056
        release_user_handle_ptr( info );
Alexandre Julliard's avatar
Alexandre Julliard committed
1057
    }
1058 1059 1060
    else
    {
        DeleteObject( color );
1061
        DeleteObject( alpha );
1062 1063
        DeleteObject( mask );
    }
1064
    return hObj;
Alexandre Julliard's avatar
Alexandre Julliard committed
1065 1066 1067
}


1068 1069 1070 1071 1072 1073 1074 1075 1076
/**********************************************************************
 *          .ANI cursor support
 */
#define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
#define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
#define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
#define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
#define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
#define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
1077
#define ANI_rate_ID RIFF_FOURCC('r', 'a', 't', 'e')
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 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 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

#define ANI_FLAG_ICON       0x1
#define ANI_FLAG_SEQUENCE   0x2

typedef struct {
    DWORD header_size;
    DWORD num_frames;
    DWORD num_steps;
    DWORD width;
    DWORD height;
    DWORD bpp;
    DWORD num_planes;
    DWORD display_rate;
    DWORD flags;
} ani_header;

typedef struct {
    DWORD           data_size;
    const unsigned char   *data;
} riff_chunk_t;

static void dump_ani_header( const ani_header *header )
{
    TRACE("     header size: %d\n", header->header_size);
    TRACE("          frames: %d\n", header->num_frames);
    TRACE("           steps: %d\n", header->num_steps);
    TRACE("           width: %d\n", header->width);
    TRACE("          height: %d\n", header->height);
    TRACE("             bpp: %d\n", header->bpp);
    TRACE("          planes: %d\n", header->num_planes);
    TRACE("    display rate: %d\n", header->display_rate);
    TRACE("           flags: 0x%08x\n", header->flags);
}


/*
 * RIFF:
 * DWORD "RIFF"
 * DWORD size
 * DWORD riff_id
 * BYTE[] data
 *
 * LIST:
 * DWORD "LIST"
 * DWORD size
 * DWORD list_id
 * BYTE[] data
 *
 * CHUNK:
 * DWORD chunk_id
 * DWORD size
 * BYTE[] data
 */
static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
{
    const unsigned char *ptr = parent_chunk->data;
    const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));

    if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);

    while (ptr < end)
    {
1140 1141
        if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
                || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1142 1143
        {
            ptr += sizeof(DWORD);
1144
            chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1145 1146 1147 1148 1149 1150 1151 1152
            ptr += sizeof(DWORD);
            if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
            chunk->data = ptr;

            return;
        }

        ptr += sizeof(DWORD);
1153 1154
        if (ptr >= end)
            break;
1155
        ptr += (*(const DWORD *)ptr + 1) & ~1;
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        ptr += sizeof(DWORD);
    }
}


/*
 * .ANI layout:
 *
 * RIFF:'ACON'                  RIFF chunk
 *     |- CHUNK:'anih'          Header
 *     |- CHUNK:'seq '          Sequence information (optional)
 *     \- LIST:'fram'           Frame list
 *            |- CHUNK:icon     Cursor frames
 *            |- CHUNK:icon
 *            |- ...
 *            \- CHUNK:icon
 */
1173
static HCURSOR CURSORICON_CreateIconFromANI( const BYTE *bits, DWORD bits_size, INT width, INT height,
1174
                                             INT depth, BOOL is_icon, UINT loadflags )
1175
{
1176
    struct animated_cursoricon_object *ani_icon_data;
1177
    struct cursoricon_object *info;
1178
    DWORD *frame_rates = NULL;
1179
    DWORD *frame_seq = NULL;
1180
    ani_header header;
1181
    BOOL use_seq = FALSE;
1182
    HCURSOR cursor;
1183 1184
    UINT i;
    BOOL error = FALSE;
1185
    HICON *frames;
1186 1187 1188 1189 1190

    riff_chunk_t root_chunk = { bits_size, bits };
    riff_chunk_t ACON_chunk = {0};
    riff_chunk_t anih_chunk = {0};
    riff_chunk_t fram_chunk = {0};
1191
    riff_chunk_t rate_chunk = {0};
1192
    riff_chunk_t seq_chunk = {0};
1193
    const unsigned char *icon_chunk;
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    const unsigned char *icon_data;

    TRACE("bits %p, bits_size %d\n", bits, bits_size);

    riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
    if (!ACON_chunk.data)
    {
        ERR("Failed to get root chunk.\n");
        return 0;
    }

    riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
    if (!anih_chunk.data)
    {
        ERR("Failed to get 'anih' chunk.\n");
        return 0;
    }
    memcpy( &header, anih_chunk.data, sizeof(header) );
    dump_ani_header( &header );

1214 1215 1216 1217 1218 1219 1220
    if (!(header.flags & ANI_FLAG_ICON))
    {
        FIXME("Raw animated icon/cursor data is not currently supported.\n");
        return 0;
    }

    if (header.flags & ANI_FLAG_SEQUENCE)
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    {
        riff_find_chunk( ANI_seq__ID, 0, &ACON_chunk, &seq_chunk );
        if (seq_chunk.data)
        {
            frame_seq = (DWORD *) seq_chunk.data;
            use_seq = TRUE;
        }
        else
        {
            FIXME("Sequence data expected but not found, assuming steps == frames.\n");
            header.num_steps = header.num_frames;
        }
    }
1234 1235

    riff_find_chunk( ANI_rate_ID, 0, &ACON_chunk, &rate_chunk );
1236
    if (rate_chunk.data)
1237
        frame_rates = (DWORD *) rate_chunk.data;
1238

1239 1240 1241 1242 1243 1244 1245
    riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
    if (!fram_chunk.data)
    {
        ERR("Failed to get icon list.\n");
        return 0;
    }

1246
    cursor = alloc_icon_handle( TRUE, header.num_steps );
1247
    if (!cursor) return 0;
1248
    frames = HeapAlloc( GetProcessHeap(), 0, sizeof(*frames) * header.num_frames );
1249 1250 1251 1252 1253
    if (!frames)
    {
        free_icon_handle( cursor );
        return 0;
    }
1254

1255
    info = get_icon_ptr( cursor );
1256
    ani_icon_data = (struct animated_cursoricon_object *) info;
1257
    info->is_icon = is_icon;
1258
    ani_icon_data->num_frames = header.num_frames;
1259

1260 1261
    /* The .ANI stores the display rate in jiffies (1/60s) */
    info->delay = header.display_rate;
1262

1263 1264 1265
    icon_chunk = fram_chunk.data;
    icon_data = fram_chunk.data + (2 * sizeof(DWORD));
    for (i=0; i<header.num_frames; i++)
1266
    {
1267 1268
        const DWORD chunk_size = *(const DWORD *)(icon_chunk + sizeof(DWORD));
        const CURSORICONFILEDIRENTRY *entry;
1269
        INT frameWidth, frameHeight;
1270
        const BITMAPINFO *bmi;
1271

1272
        entry = CURSORICON_FindBestIconFile((const CURSORICONFILEDIR *) icon_data,
1273
                                            bits + bits_size - icon_data,
1274
                                            width, height, depth, loadflags );
1275 1276 1277 1278 1279

        info->hotspot.x = entry->xHotspot;
        info->hotspot.y = entry->yHotspot;
        if (!header.width || !header.height)
        {
1280 1281
            frameWidth = entry->bWidth;
            frameHeight = entry->bHeight;
1282
        }
1283
        else
1284 1285 1286 1287
        {
            frameWidth = header.width;
            frameHeight = header.height;
        }
1288

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
        frames[i] = NULL;
        if (entry->dwDIBOffset < bits + bits_size - icon_data)
        {
            bmi = (const BITMAPINFO *) (icon_data + entry->dwDIBOffset);
            /* Grab a frame from the animation */
            frames[i] = create_icon_from_bmi( bmi, bits + bits_size - (const BYTE *)bmi,
                                              NULL, NULL, NULL, info->hotspot,
                                              is_icon, frameWidth, frameHeight, loadflags );
        }

1299
        if (!frames[i])
1300 1301 1302 1303 1304 1305
        {
            FIXME_(cursor)("failed to convert animated cursor frame.\n");
            error = TRUE;
            if (i == 0)
            {
                FIXME_(cursor)("Completely failed to create animated cursor!\n");
1306
                ani_icon_data->num_frames = 0;
1307
                release_user_handle_ptr( info );
1308
                free_icon_handle( cursor );
1309
                HeapFree( GetProcessHeap(), 0, frames );
1310 1311 1312 1313
                return 0;
            }
            break;
        }
1314

1315 1316 1317 1318
        /* Advance to the next chunk */
        icon_chunk += chunk_size + (2 * sizeof(DWORD));
        icon_data = icon_chunk + (2 * sizeof(DWORD));
    }
1319

1320 1321 1322 1323
    /* There was an error but we at least decoded the first frame, so just use that frame */
    if (error)
    {
        FIXME_(cursor)("Error creating animated cursor, only using first frame!\n");
1324 1325
        for (i=1; i<ani_icon_data->num_frames; i++)
            free_icon_handle( ani_icon_data->frames[i] );
1326
        use_seq = FALSE;
1327
        info->delay = 0;
1328 1329
        ani_icon_data->num_steps = 1;
        ani_icon_data->num_frames = 1;
1330
    }
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348

    /* Setup the animated frames in the correct sequence */
    for (i=0; i<ani_icon_data->num_steps; i++)
    {
        DWORD frame_id = use_seq ? frame_seq[i] : i;
        struct cursoricon_frame *frame;

        if (frame_id >= ani_icon_data->num_frames)
        {
            frame_id = ani_icon_data->num_frames-1;
            ERR_(cursor)("Sequence indicates frame past end of list, corrupt?\n");
        }
        ani_icon_data->frames[i] = frames[frame_id];
        frame = get_icon_frame( info, i );
        if (frame_rates)
            frame->delay = frame_rates[i];
        else
            frame->delay = ~0;
1349
        release_icon_frame( info, frame );
1350 1351 1352
    }

    HeapFree( GetProcessHeap(), 0, frames );
1353
    release_user_handle_ptr( info );
1354 1355 1356 1357 1358

    return cursor;
}


1359 1360 1361
/**********************************************************************
 *		CreateIconFromResourceEx (USER32.@)
 *
1362
 * FIXME: Convert to mono when cFlag is LR_MONOCHROME.
1363 1364 1365 1366 1367 1368
 */
HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
                                       BOOL bIcon, DWORD dwVersion,
                                       INT width, INT height,
                                       UINT cFlag )
{
1369
    POINT hotspot;
1370
    const BITMAPINFO *bmi;
1371 1372 1373

    TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s %s\n",
                   bits, cbSize, dwVersion, width, height,
1374
                   bIcon ? "icon" : "cursor", (cFlag & LR_MONOCHROME) ? "mono" : "" );
1375

1376 1377
    if (!bits) return 0;

1378 1379 1380 1381 1382 1383
    if (dwVersion == 0x00020000)
    {
        FIXME_(cursor)("\t2.xx resources are not supported\n");
        return 0;
    }

1384 1385
    /* Check if the resource is an animated icon/cursor */
    if (!memcmp(bits, "RIFF", 4))
1386 1387
        return CURSORICON_CreateIconFromANI( bits, cbSize, width, height,
                                             0 /* default depth */, bIcon, cFlag );
1388

1389
    if (bIcon)
1390 1391 1392
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
1393
        bmi = (BITMAPINFO *)bits;
1394
    }
1395 1396
    else /* get the hotspot */
    {
1397
        const SHORT *pt = (const SHORT *)bits;
1398 1399
        hotspot.x = pt[0];
        hotspot.y = pt[1];
1400
        bmi = (const BITMAPINFO *)(pt + 2);
1401
        cbSize -= 2 * sizeof(*pt);
1402 1403
    }

1404
    return create_icon_from_bmi( bmi, cbSize, NULL, NULL, NULL, hotspot, bIcon, width, height, cFlag );
1405 1406 1407
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1408
/**********************************************************************
1409
 *		CreateIconFromResource (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1410
 */
1411 1412
HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
                                           BOOL bIcon, DWORD dwVersion)
Alexandre Julliard's avatar
Alexandre Julliard committed
1413
{
1414
    return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
Alexandre Julliard's avatar
Alexandre Julliard committed
1415 1416 1417
}


1418
static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1419
                             INT width, INT height, INT depth,
1420 1421
                             BOOL fCursor, UINT loadflags)
{
1422 1423
    const CURSORICONFILEDIRENTRY *entry;
    const CURSORICONFILEDIR *dir;
1424 1425
    DWORD filesize = 0;
    HICON hIcon = 0;
1426
    const BYTE *bits;
1427
    POINT hotspot;
1428 1429 1430 1431 1432 1433 1434

    TRACE("loading %s\n", debugstr_w( filename ));

    bits = map_fileW( filename, &filesize );
    if (!bits)
        return hIcon;

1435 1436 1437
    /* Check for .ani. */
    if (memcmp( bits, "RIFF", 4 ) == 0)
    {
1438
        hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height, depth, !fCursor, loadflags );
1439 1440 1441
        goto end;
    }

1442
    dir = (const CURSORICONFILEDIR*) bits;
1443
    if ( filesize < FIELD_OFFSET( CURSORICONFILEDIR, idEntries[dir->idCount] ))
1444 1445 1446
        goto end;

    if ( fCursor )
1447
        entry = CURSORICON_FindBestCursorFile( dir, filesize, width, height, depth, loadflags );
1448
    else
1449
        entry = CURSORICON_FindBestIconFile( dir, filesize, width, height, depth, loadflags );
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

    if ( !entry )
        goto end;

    /* check that we don't run off the end of the file */
    if ( entry->dwDIBOffset > filesize )
        goto end;
    if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
        goto end;

1460 1461
    hotspot.x = entry->xHotspot;
    hotspot.y = entry->yHotspot;
1462
    hIcon = create_icon_from_bmi( (const BITMAPINFO *)&bits[entry->dwDIBOffset], filesize - entry->dwDIBOffset,
1463
                                  NULL, NULL, NULL, hotspot, !fCursor, width, height, loadflags );
1464 1465 1466 1467 1468 1469
end:
    TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
    UnmapViewOfFile( bits );
    return hIcon;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1470
/**********************************************************************
1471
 *          CURSORICON_Load
Alexandre Julliard's avatar
Alexandre Julliard committed
1472
 *
1473
 * Load a cursor or icon from resource or file.
Alexandre Julliard's avatar
Alexandre Julliard committed
1474
 */
1475
static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1476
                             INT width, INT height, INT depth,
1477
                             BOOL fCursor, UINT loadflags)
Alexandre Julliard's avatar
Alexandre Julliard committed
1478
{
1479 1480
    HANDLE handle = 0;
    HICON hIcon = 0;
1481
    HRSRC hRsrc;
1482
    DWORD size;
1483 1484
    const CURSORICONDIR *dir;
    const CURSORICONDIRENTRY *dirEntry;
1485
    const BYTE *bits;
1486
    WORD wResId;
1487
    POINT hotspot;
1488

1489 1490
    TRACE("%p, %s, %dx%d, depth %d, fCursor %d, flags 0x%04x\n",
          hInstance, debugstr_w(name), width, height, depth, fCursor, loadflags);
1491

1492
    if ( loadflags & LR_LOADFROMFILE )    /* Load from file */
1493
        return CURSORICON_LoadFromFile( name, width, height, depth, fCursor, loadflags );
Alexandre Julliard's avatar
Alexandre Julliard committed
1494

1495
    if (!hInstance) hInstance = user32_module;  /* Load OEM cursor/icon */
1496

1497
    /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1498
    if ((ULONG_PTR)hInstance >> 16 == 0) loadflags &= ~LR_SHARED;
Alexandre Julliard's avatar
Alexandre Julliard committed
1499

1500
    /* Get directory resource ID */
Alexandre Julliard's avatar
Alexandre Julliard committed
1501

1502 1503
    if (!(hRsrc = FindResourceW( hInstance, name,
                                 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1504 1505 1506 1507 1508 1509 1510 1511 1512
    {
        /* try animated resource */
        if (!(hRsrc = FindResourceW( hInstance, name,
                                    (LPWSTR)(fCursor ? RT_ANICURSOR : RT_ANIICON) ))) return 0;
        if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
        bits = LockResource( handle );
        return CURSORICON_CreateIconFromANI( bits, SizeofResource( hInstance, handle ),
                                             width, height, depth, !fCursor, loadflags );
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
1513

1514
    /* Find the best entry in the directory */
1515

1516
    if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1517
    if (!(dir = LockResource( handle ))) return 0;
1518
    size = SizeofResource( hInstance, hRsrc );
1519
    if (fCursor)
1520
        dirEntry = CURSORICON_FindBestCursorRes( dir, size, width, height, depth, loadflags );
1521
    else
1522
        dirEntry = CURSORICON_FindBestIconRes( dir, size, width, height, depth, loadflags );
1523 1524 1525
    if (!dirEntry) return 0;
    wResId = dirEntry->wResId;
    FreeResource( handle );
1526

1527
    /* Load the resource */
1528

1529 1530
    if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
                                (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1531

1532
    /* If shared icon, check whether it was already loaded */
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
    if (loadflags & LR_SHARED)
    {
        struct cursoricon_object *ptr;

        USER_Lock();
        LIST_FOR_EACH_ENTRY( ptr, &icon_cache, struct cursoricon_object, entry )
        {
            if (ptr->module != hInstance) continue;
            if (ptr->rsrc != hRsrc) continue;
            hIcon = ptr->obj.handle;
            break;
        }
        USER_Unlock();
        if (hIcon) return hIcon;
    }
1548

1549
    if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1550
    size = SizeofResource( hInstance, hRsrc );
1551
    bits = LockResource( handle );
1552 1553 1554 1555 1556 1557 1558 1559

    if (!fCursor)
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
    }
    else /* get the hotspot */
    {
1560
        const SHORT *pt = (const SHORT *)bits;
1561 1562 1563
        hotspot.x = pt[0];
        hotspot.y = pt[1];
        bits += 2 * sizeof(SHORT);
1564
        size -= 2 * sizeof(SHORT);
1565
    }
1566
    hIcon = create_icon_from_bmi( (const BITMAPINFO *)bits, size, hInstance, name, hRsrc,
1567
                                  hotspot, !fCursor, width, height, loadflags );
1568
    FreeResource( handle );
1569
    return hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1570 1571
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1572

Alexandre Julliard's avatar
Alexandre Julliard committed
1573
/***********************************************************************
1574
 *		CreateCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1575
 */
1576 1577 1578
HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
                                 INT xHotSpot, INT yHotSpot,
                                 INT nWidth, INT nHeight,
Alexandre Julliard's avatar
Alexandre Julliard committed
1579
                                 LPCVOID lpANDbits, LPCVOID lpXORbits )
Alexandre Julliard's avatar
Alexandre Julliard committed
1580
{
1581 1582
    ICONINFO info;
    HCURSOR hCursor;
Alexandre Julliard's avatar
Alexandre Julliard committed
1583

1584
    TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
Alexandre Julliard's avatar
Alexandre Julliard committed
1585
                    nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1586

1587 1588 1589 1590 1591 1592 1593 1594 1595
    info.fIcon = FALSE;
    info.xHotspot = xHotSpot;
    info.yHotspot = yHotSpot;
    info.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
    info.hbmColor = CreateBitmap( nWidth, nHeight, 1, 1, lpXORbits );
    hCursor = CreateIconIndirect( &info );
    DeleteObject( info.hbmMask );
    DeleteObject( info.hbmColor );
    return hCursor;
Alexandre Julliard's avatar
Alexandre Julliard committed
1596 1597 1598
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1599
/***********************************************************************
1600
 *		CreateIcon (USER32.@)
1601
 *
1602 1603 1604
 *  Creates an icon based on the specified bitmaps. The bitmaps must be
 *  provided in a device dependent format and will be resized to
 *  (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1605
 *  depth. The provided bitmaps must be top-down bitmaps.
1606
 *  Although Windows does not support 15bpp(*) this API must support it
1607 1608
 *  for Winelib applications.
 *
1609
 *  (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1610 1611
 *      format!
 *
1612 1613 1614 1615
 * RETURNS
 *  Success: handle to an icon
 *  Failure: NULL
 *
1616
 * FIXME: Do we need to resize the bitmaps?
Alexandre Julliard's avatar
Alexandre Julliard committed
1617
 */
1618
HICON WINAPI CreateIcon(
1619
    HINSTANCE hInstance,  /* [in] the application's hInstance */
1620 1621 1622 1623 1624 1625
    INT       nWidth,     /* [in] the width of the provided bitmaps */
    INT       nHeight,    /* [in] the height of the provided bitmaps */
    BYTE      bPlanes,    /* [in] the number of planes in the provided bitmaps */
    BYTE      bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
    LPCVOID   lpANDbits,  /* [in] a monochrome bitmap representing the icon's mask */
    LPCVOID   lpXORbits)  /* [in] the icon's 'color' bitmap */
Alexandre Julliard's avatar
Alexandre Julliard committed
1626
{
1627
    ICONINFO iinfo;
1628
    HICON hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1629

1630 1631
    TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
                 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1632

1633
    iinfo.fIcon = TRUE;
1634 1635
    iinfo.xHotspot = nWidth / 2;
    iinfo.yHotspot = nHeight / 2;
1636 1637 1638 1639 1640 1641 1642
    iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
    iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );

    hIcon = CreateIconIndirect( &iinfo );

    DeleteObject( iinfo.hbmMask );
    DeleteObject( iinfo.hbmColor );
1643 1644

    return hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1645 1646 1647 1648
}


/***********************************************************************
1649
 *		CopyIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1650
 */
1651
HICON WINAPI CopyIcon( HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1652
{
1653
    struct cursoricon_object *ptrOld, *ptrNew;
1654
    HICON hNew;
1655

1656 1657 1658 1659 1660
    if (!(ptrOld = get_icon_ptr( hIcon )))
    {
        SetLastError( ERROR_INVALID_CURSOR_HANDLE );
        return 0;
    }
1661
    if ((hNew = alloc_icon_handle( FALSE, 0 )))
1662
    {
1663 1664
        struct cursoricon_frame *frameOld, *frameNew;

1665
        ptrNew = get_icon_ptr( hNew );
1666 1667
        ptrNew->is_icon = ptrOld->is_icon;
        ptrNew->hotspot = ptrOld->hotspot;
1668 1669
        if (!(frameOld = get_icon_frame( ptrOld, 0 )))
        {
1670
            release_user_handle_ptr( ptrOld );
1671 1672 1673 1674 1675
            SetLastError( ERROR_INVALID_CURSOR_HANDLE );
            return 0;
        }
        if (!(frameNew = get_icon_frame( ptrNew, 0 )))
        {
1676
            release_icon_frame( ptrOld, frameOld );
1677
            release_user_handle_ptr( ptrOld );
1678 1679 1680 1681 1682 1683 1684 1685 1686
            SetLastError( ERROR_INVALID_CURSOR_HANDLE );
            return 0;
        }
        frameNew->delay  = 0;
        frameNew->width  = frameOld->width;
        frameNew->height = frameOld->height;
        frameNew->mask   = copy_bitmap( frameOld->mask );
        frameNew->color  = copy_bitmap( frameOld->color );
        frameNew->alpha  = copy_bitmap( frameOld->alpha );
1687 1688
        release_icon_frame( ptrOld, frameOld );
        release_icon_frame( ptrNew, frameNew );
1689
        release_user_handle_ptr( ptrNew );
1690
    }
1691
    release_user_handle_ptr( ptrOld );
1692
    return hNew;
Alexandre Julliard's avatar
Alexandre Julliard committed
1693
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1694 1695


Alexandre Julliard's avatar
Alexandre Julliard committed
1696
/***********************************************************************
1697
 *		DestroyIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1698
 */
1699
BOOL WINAPI DestroyIcon( HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1700
{
1701 1702 1703
    BOOL ret = FALSE;
    struct cursoricon_object *obj = get_icon_ptr( hIcon );

1704 1705
    TRACE_(icon)("%p\n", hIcon );

1706 1707 1708
    if (obj)
    {
        BOOL shared = (obj->rsrc != NULL);
1709
        release_user_handle_ptr( obj );
1710 1711 1712 1713
        ret = (GetCursor() != hIcon);
        if (!shared) free_icon_handle( hIcon );
    }
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1714 1715
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1716 1717

/***********************************************************************
1718
 *		DestroyCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1719
 */
1720
BOOL WINAPI DestroyCursor( HCURSOR hCursor )
Alexandre Julliard's avatar
Alexandre Julliard committed
1721
{
1722
    return DestroyIcon( hCursor );
Alexandre Julliard's avatar
Alexandre Julliard committed
1723 1724
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1725
/***********************************************************************
1726
 *		DrawIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1727
 */
1728
BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1729
{
1730
    return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1731 1732
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1733
/***********************************************************************
1734
 *		SetCursor (USER32.@)
1735 1736 1737 1738
 *
 * Set the cursor shape.
 *
 * RETURNS
Alexandre Julliard's avatar
Alexandre Julliard committed
1739
 *	A handle to the previous cursor shape.
Alexandre Julliard's avatar
Alexandre Julliard committed
1740
 */
1741
HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1742
{
1743
    struct cursoricon_object *obj;
1744
    HCURSOR hOldCursor;
1745 1746
    int show_count;
    BOOL ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1747

1748
    TRACE("%p\n", hCursor);
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762

    SERVER_START_REQ( set_cursor )
    {
        req->flags = SET_CURSOR_HANDLE;
        req->handle = wine_server_user_handle( hCursor );
        if ((ret = !wine_server_call_err( req )))
        {
            hOldCursor = wine_server_ptr_handle( reply->prev_handle );
            show_count = reply->prev_count;
        }
    }
    SERVER_END_REQ;

    if (!ret) return 0;
1763
    USER_Driver->pSetCursor( show_count >= 0 ? hCursor : 0 );
1764 1765

    if (!(obj = get_icon_ptr( hOldCursor ))) return 0;
1766
    release_user_handle_ptr( obj );
Alexandre Julliard's avatar
Alexandre Julliard committed
1767 1768 1769
    return hOldCursor;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1770
/***********************************************************************
1771
 *		ShowCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1772
 */
1773
INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
Alexandre Julliard's avatar
Alexandre Julliard committed
1774
{
1775 1776
    HCURSOR cursor;
    int increment = bShow ? 1 : -1;
1777
    int count;
1778

1779 1780 1781 1782 1783 1784
    SERVER_START_REQ( set_cursor )
    {
        req->flags = SET_CURSOR_COUNT;
        req->show_count = increment;
        wine_server_call( req );
        cursor = wine_server_ptr_handle( reply->prev_handle );
1785
        count = reply->prev_count + increment;
1786 1787 1788
    }
    SERVER_END_REQ;

1789
    TRACE("%d, count=%d\n", bShow, count );
Alexandre Julliard's avatar
Alexandre Julliard committed
1790

1791 1792
    if (bShow && !count) USER_Driver->pSetCursor( cursor );
    else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
1793

1794
    return count;
Alexandre Julliard's avatar
Alexandre Julliard committed
1795 1796
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1797
/***********************************************************************
1798
 *		GetCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1799
 */
1800
HCURSOR WINAPI GetCursor(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
1801
{
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
    HCURSOR ret;

    SERVER_START_REQ( set_cursor )
    {
        req->flags = 0;
        wine_server_call( req );
        ret = wine_server_ptr_handle( reply->prev_handle );
    }
    SERVER_END_REQ;
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1812 1813 1814 1815
}


/***********************************************************************
1816
 *		ClipCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1817
 */
1818
BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
Alexandre Julliard's avatar
Alexandre Julliard committed
1819
{
1820
    UINT dpi;
1821 1822
    BOOL ret;
    RECT new_rect;
1823

1824
    TRACE( "Clipping to %s\n", wine_dbgstr_rect(rect) );
1825

1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
    if (rect)
    {
        if (rect->left > rect->right || rect->top > rect->bottom) return FALSE;
        if ((dpi = get_thread_dpi()))
        {
            new_rect = map_dpi_rect( *rect, dpi,
                                     get_monitor_dpi( MonitorFromRect( rect, MONITOR_DEFAULTTOPRIMARY )));
            rect = &new_rect;
        }
    }
1836

1837 1838
    SERVER_START_REQ( set_cursor )
    {
1839
        req->clip_msg = WM_WINE_CLIPCURSOR;
1840 1841
        if (rect)
        {
1842
            req->flags       = SET_CURSOR_CLIP;
1843 1844 1845 1846 1847
            req->clip.left   = rect->left;
            req->clip.top    = rect->top;
            req->clip.right  = rect->right;
            req->clip.bottom = rect->bottom;
        }
1848 1849
        else req->flags = SET_CURSOR_NOCLIP;

1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
        if ((ret = !wine_server_call( req )))
        {
            new_rect.left   = reply->new_clip.left;
            new_rect.top    = reply->new_clip.top;
            new_rect.right  = reply->new_clip.right;
            new_rect.bottom = reply->new_clip.bottom;
        }
    }
    SERVER_END_REQ;
    if (ret) USER_Driver->pClipCursor( &new_rect );
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1861 1862 1863 1864
}


/***********************************************************************
1865
 *		GetClipCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1866
 */
1867
BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
Alexandre Julliard's avatar
Alexandre Julliard committed
1868
{
1869 1870
    DPI_AWARENESS_CONTEXT context;
    UINT dpi;
1871
    BOOL ret;
1872

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
    if (!rect) return FALSE;

    SERVER_START_REQ( set_cursor )
    {
        req->flags = 0;
        if ((ret = !wine_server_call( req )))
        {
            rect->left   = reply->new_clip.left;
            rect->top    = reply->new_clip.top;
            rect->right  = reply->new_clip.right;
            rect->bottom = reply->new_clip.bottom;
        }
    }
    SERVER_END_REQ;
1887 1888 1889 1890 1891 1892 1893

    if (ret && (dpi = get_thread_dpi()))
    {
        context = SetThreadDpiAwarenessContext( DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE );
        *rect = map_dpi_rect( *rect, get_monitor_dpi( MonitorFromRect( rect, MONITOR_DEFAULTTOPRIMARY )), dpi );
        SetThreadDpiAwarenessContext( context );
    }
1894
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1895 1896
}

1897 1898 1899 1900 1901 1902

/***********************************************************************
 *		SetSystemCursor (USER32.@)
 */
BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
{
1903
    FIXME("(%p,%08x),stub!\n",  hcur, id);
1904 1905 1906 1907
    return TRUE;
}


1908 1909 1910 1911 1912
/**********************************************************************
 *		LookupIconIdFromDirectoryEx (USER32.@)
 */
INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
             INT width, INT height, UINT cFlag )
Alexandre Julliard's avatar
Alexandre Julliard committed
1913
{
1914
    const CURSORICONDIR *dir = (const CURSORICONDIR*)xdir;
1915
    UINT retVal = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
1916 1917
    if( dir && !dir->idReserved && (dir->idType & 3) )
    {
1918
        const CURSORICONDIRENTRY* entry;
1919
        int depth = (cFlag & LR_MONOCHROME) ? 1 : get_display_bpp();
1920 1921

        if( bIcon )
1922
            entry = CURSORICON_FindBestIconRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
1923
        else
1924
            entry = CURSORICON_FindBestCursorRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
1925

1926
        if( entry ) retVal = entry->wResId;
Alexandre Julliard's avatar
Alexandre Julliard committed
1927
    }
1928
    else WARN_(cursor)("invalid resource directory\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
1929 1930 1931
    return retVal;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1932
/**********************************************************************
1933
 *              LookupIconIdFromDirectory (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1934
 */
1935
INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1936
{
1937
    return LookupIconIdFromDirectoryEx( dir, bIcon, 0, 0, bIcon ? 0 : LR_MONOCHROME );
Alexandre Julliard's avatar
Alexandre Julliard committed
1938 1939
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1940
/***********************************************************************
1941
 *              LoadCursorW (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1942
 */
1943
HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1944
{
1945 1946
    TRACE("%p, %s\n", hInstance, debugstr_w(name));

1947
    return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1948
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1949 1950 1951
}

/***********************************************************************
1952
 *		LoadCursorA (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1953
 */
1954
HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1955
{
1956 1957
    TRACE("%p, %s\n", hInstance, debugstr_a(name));

1958
    return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1959
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1960
}
1961

Alexandre Julliard's avatar
Alexandre Julliard committed
1962
/***********************************************************************
1963 1964
 *		LoadCursorFromFileW (USER32.@)
 */
1965
HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1966
{
1967 1968
    TRACE("%s\n", debugstr_w(name));

1969
    return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1970
                       LR_LOADFROMFILE | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1971
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1972

Alexandre Julliard's avatar
Alexandre Julliard committed
1973
/***********************************************************************
1974 1975
 *		LoadCursorFromFileA (USER32.@)
 */
1976
HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1977
{
1978 1979
    TRACE("%s\n", debugstr_a(name));

1980
    return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1981
                       LR_LOADFROMFILE | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1982
}
1983

Alexandre Julliard's avatar
Alexandre Julliard committed
1984
/***********************************************************************
1985
 *		LoadIconW (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1986
 */
1987
HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1988
{
1989 1990
    TRACE("%p, %s\n", hInstance, debugstr_w(name));

1991
    return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1992
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1993 1994 1995
}

/***********************************************************************
1996
 *              LoadIconA (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1997
 */
1998
HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1999
{
2000 2001
    TRACE("%p, %s\n", hInstance, debugstr_a(name));

2002
    return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
2003
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
2004
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2005

2006 2007
/**********************************************************************
 *              GetCursorFrameInfo (USER32.@)
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
 *
 * NOTES
 *    So far no use has been found for the second parameter, it is currently presumed
 *    that this parameter is reserved for future use.
 *
 * PARAMS
 *    hCursor      [I] Handle to cursor for which to retrieve information
 *    reserved     [I] No purpose has been found for this parameter (may be NULL)
 *    istep        [I] The step of the cursor for which to retrieve information
 *    rate_jiffies [O] Pointer to DWORD that receives the frame-specific delay (cannot be NULL)
 *    num_steps    [O] Pointer to DWORD that receives the number of steps in the cursor (cannot be NULL)
 *
 * RETURNS
 *    Success: Handle to a frame of the cursor (specified by istep)
 *    Failure: NULL cursor (0)
2023
 */
2024
HCURSOR WINAPI GetCursorFrameInfo(HCURSOR hCursor, DWORD reserved, DWORD istep, DWORD *rate_jiffies, DWORD *num_steps)
2025 2026 2027
{
    struct cursoricon_object *ptr;
    HCURSOR ret = 0;
2028
    UINT icon_steps;
2029

2030
    if (rate_jiffies == NULL || num_steps == NULL) return 0;
2031 2032 2033

    if (!(ptr = get_icon_ptr( hCursor ))) return 0;

2034 2035 2036
    TRACE("%p => %d %d %p %p\n", hCursor, reserved, istep, rate_jiffies, num_steps);
    if (reserved != 0)
        FIXME("Second parameter non-zero (%d), please report this!\n", reserved);
2037

2038 2039
    icon_steps = get_icon_steps(ptr);
    if (istep < icon_steps || !ptr->is_ani)
2040
    {
2041 2042 2043 2044 2045 2046 2047 2048 2049
        struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) ptr;
        UINT icon_frames = 1;

        if (ptr->is_ani)
            icon_frames = ani_icon_data->num_frames;
        if (ptr->is_ani && icon_frames > 1)
            ret = ani_icon_data->frames[istep];
        else
            ret = hCursor;
2050
        if (icon_frames == 1)
2051 2052
        {
            *rate_jiffies = 0;
2053
            *num_steps = 1;
2054
        }
2055 2056 2057 2058 2059 2060
        else if (icon_steps == 1)
        {
            *num_steps = ~0;
            *rate_jiffies = ptr->delay;
        }
        else if (istep < icon_steps)
2061
        {
2062 2063
            struct cursoricon_frame *frame;

2064
            *num_steps = icon_steps;
2065
            frame = get_icon_frame( ptr, istep );
2066
            if (get_icon_steps(ptr) == 1)
2067 2068
                *num_steps = ~0;
            else
2069
                *num_steps = get_icon_steps(ptr);
2070
            /* If this specific frame does not have a delay then use the global delay */
2071
            if (frame->delay == ~0)
2072 2073
                *rate_jiffies = ptr->delay;
            else
2074
                *rate_jiffies = frame->delay;
2075
            release_icon_frame( ptr, frame );
2076 2077 2078
        }
    }

2079
    release_user_handle_ptr( ptr );
2080 2081 2082 2083

    return ret;
}

2084
/**********************************************************************
2085
 *              GetIconInfo (USER32.@)
2086
 */
2087 2088
BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
{
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
    ICONINFOEXW infoW;

    infoW.cbSize = sizeof(infoW);
    if (!GetIconInfoExW( hIcon, &infoW )) return FALSE;
    iconinfo->fIcon    = infoW.fIcon;
    iconinfo->xHotspot = infoW.xHotspot;
    iconinfo->yHotspot = infoW.yHotspot;
    iconinfo->hbmColor = infoW.hbmColor;
    iconinfo->hbmMask  = infoW.hbmMask;
    return TRUE;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2100

2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
/**********************************************************************
 *              GetIconInfoExA (USER32.@)
 */
BOOL WINAPI GetIconInfoExA( HICON icon, ICONINFOEXA *info )
{
    ICONINFOEXW infoW;

    if (info->cbSize != sizeof(*info))
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return FALSE;
    }
    infoW.cbSize = sizeof(infoW);
    if (!GetIconInfoExW( icon, &infoW )) return FALSE;
    info->fIcon    = infoW.fIcon;
    info->xHotspot = infoW.xHotspot;
    info->yHotspot = infoW.yHotspot;
    info->hbmColor = infoW.hbmColor;
    info->hbmMask  = infoW.hbmMask;
    info->wResID   = infoW.wResID;
    WideCharToMultiByte( CP_ACP, 0, infoW.szModName, -1, info->szModName, MAX_PATH, NULL, NULL );
    WideCharToMultiByte( CP_ACP, 0, infoW.szResName, -1, info->szResName, MAX_PATH, NULL, NULL );
    return TRUE;
}
2125

2126 2127 2128 2129 2130
/**********************************************************************
 *              GetIconInfoExW (USER32.@)
 */
BOOL WINAPI GetIconInfoExW( HICON icon, ICONINFOEXW *info )
{
2131
    struct cursoricon_frame *frame;
2132
    struct cursoricon_object *ptr;
2133
    HMODULE module;
2134
    BOOL ret = TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2135

2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
    if (info->cbSize != sizeof(*info))
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return FALSE;
    }
    if (!(ptr = get_icon_ptr( icon )))
    {
        SetLastError( ERROR_INVALID_CURSOR_HANDLE );
        return FALSE;
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
2146

2147 2148 2149
    frame = get_icon_frame( ptr, 0 );
    if (!frame)
    {
2150
        release_user_handle_ptr( ptr );
2151 2152 2153 2154 2155
        SetLastError( ERROR_INVALID_CURSOR_HANDLE );
        return FALSE;
    }

    TRACE("%p => %dx%d\n", icon, frame->width, frame->height);
2156 2157 2158 2159

    info->fIcon        = ptr->is_icon;
    info->xHotspot     = ptr->hotspot.x;
    info->yHotspot     = ptr->hotspot.y;
2160 2161
    info->hbmColor     = copy_bitmap( frame->color );
    info->hbmMask      = copy_bitmap( frame->mask );
2162 2163 2164 2165 2166 2167 2168 2169
    info->wResID       = 0;
    info->szModName[0] = 0;
    info->szResName[0] = 0;
    if (ptr->module)
    {
        if (IS_INTRESOURCE( ptr->resname )) info->wResID = LOWORD( ptr->resname );
        else lstrcpynW( info->szResName, ptr->resname, MAX_PATH );
    }
2170
    if (!info->hbmMask || (!info->hbmColor && frame->color))
2171 2172 2173 2174 2175
    {
        DeleteObject( info->hbmMask );
        DeleteObject( info->hbmColor );
        ret = FALSE;
    }
2176
    module = ptr->module;
2177
    release_icon_frame( ptr, frame );
2178
    release_user_handle_ptr( ptr );
2179
    if (ret && module) GetModuleFileNameW( module, info->szModName, MAX_PATH );
2180
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
2181 2182
}

2183 2184 2185 2186 2187 2188 2189
/* copy an icon bitmap, even when it can't be selected into a DC */
/* helper for CreateIconIndirect */
static void stretch_blt_icon( HDC hdc_dst, int dst_x, int dst_y, int dst_width, int dst_height,
                              HBITMAP src, int width, int height )
{
    HDC hdc = CreateCompatibleDC( 0 );

2190
    if (!SelectObject( hdc, src ))  /* do it the hard way */
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
    {
        BITMAPINFO *info;
        void *bits;

        if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) return;
        info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
        info->bmiHeader.biWidth = width;
        info->bmiHeader.biHeight = height;
        info->bmiHeader.biPlanes = GetDeviceCaps( hdc_dst, PLANES );
        info->bmiHeader.biBitCount = GetDeviceCaps( hdc_dst, BITSPIXEL );
        info->bmiHeader.biCompression = BI_RGB;
2202
        info->bmiHeader.biSizeImage = get_dib_image_size( width, height, info->bmiHeader.biBitCount );
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
        info->bmiHeader.biXPelsPerMeter = 0;
        info->bmiHeader.biYPelsPerMeter = 0;
        info->bmiHeader.biClrUsed = 0;
        info->bmiHeader.biClrImportant = 0;
        bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
        if (bits && GetDIBits( hdc, src, 0, height, bits, info, DIB_RGB_COLORS ))
            StretchDIBits( hdc_dst, dst_x, dst_y, dst_width, dst_height,
                           0, 0, width, height, bits, info, DIB_RGB_COLORS, SRCCOPY );

        HeapFree( GetProcessHeap(), 0, bits );
        HeapFree( GetProcessHeap(), 0, info );
    }
    else StretchBlt( hdc_dst, dst_x, dst_y, dst_width, dst_height, hdc, 0, 0, width, height, SRCCOPY );

    DeleteDC( hdc );
}

Alexandre Julliard's avatar
Alexandre Julliard committed
2220
/**********************************************************************
2221
 *		CreateIconIndirect (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
2222
 */
2223
HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
2224
{
2225
    BITMAP bmpXor, bmpAnd;
2226
    HICON hObj;
2227
    HBITMAP color = 0, mask;
2228
    int width, height;
2229
    HDC hdc;
Alexandre Julliard's avatar
Alexandre Julliard committed
2230

2231 2232 2233 2234
    TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
           iconinfo->hbmColor, iconinfo->hbmMask,
           iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);

2235 2236
    if (!iconinfo->hbmMask) return 0;

2237 2238 2239 2240 2241
    GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
    TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
           bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
           bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);

2242 2243
    if (iconinfo->hbmColor)
    {
2244
        GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2245
        TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2246 2247
               bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
               bmpXor.bmPlanes, bmpXor.bmBitsPixel);
2248

2249 2250
        width = bmpXor.bmWidth;
        height = bmpXor.bmHeight;
2251
        if (bmpXor.bmPlanes * bmpXor.bmBitsPixel != 1 || bmpAnd.bmPlanes * bmpAnd.bmBitsPixel != 1)
2252
        {
2253
            color = create_color_bitmap( width, height );
2254 2255 2256
            mask = CreateBitmap( width, height, 1, 1, NULL );
        }
        else mask = CreateBitmap( width, height * 2, 1, 1, NULL );
2257
    }
2258 2259 2260 2261 2262 2263 2264
    else
    {
        width = bmpAnd.bmWidth;
        height = bmpAnd.bmHeight;
        mask = CreateBitmap( width, height, 1, 1, NULL );
    }

2265 2266 2267
    hdc = CreateCompatibleDC( 0 );
    SelectObject( hdc, mask );
    stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
2268 2269 2270

    if (color)
    {
2271 2272
        SelectObject( hdc, color );
        stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
2273 2274 2275
    }
    else if (iconinfo->hbmColor)
    {
2276
        stretch_blt_icon( hdc, 0, height, width, height, iconinfo->hbmColor, width, height );
2277
    }
2278 2279
    else height /= 2;

2280
    DeleteDC( hdc );
Alexandre Julliard's avatar
Alexandre Julliard committed
2281

2282
    hObj = alloc_icon_handle( FALSE, 0 );
Alexandre Julliard's avatar
Alexandre Julliard committed
2283 2284
    if (hObj)
    {
2285
        struct cursoricon_object *info = get_icon_ptr( hObj );
2286
        struct cursoricon_frame *frame;
2287

2288
        info->is_icon = iconinfo->fIcon;
2289 2290 2291 2292 2293 2294
        frame = get_icon_frame( info, 0 );
        frame->delay  = ~0;
        frame->width  = width;
        frame->height = height;
        frame->color  = color;
        frame->mask   = mask;
2295
        frame->alpha  = create_alpha_bitmap( iconinfo->hbmColor, NULL, NULL );
2296
        release_icon_frame( info, frame );
2297
        if (info->is_icon)
2298
        {
2299 2300
            info->hotspot.x = width / 2;
            info->hotspot.y = height / 2;
2301 2302 2303
        }
        else
        {
2304 2305
            info->hotspot.x = iconinfo->xHotspot;
            info->hotspot.y = iconinfo->yHotspot;
2306 2307
        }

2308
        release_user_handle_ptr( info );
Alexandre Julliard's avatar
Alexandre Julliard committed
2309
    }
2310
    return hObj;
Alexandre Julliard's avatar
Alexandre Julliard committed
2311
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2312

Alexandre Julliard's avatar
Alexandre Julliard committed
2313
/******************************************************************************
2314
 *		DrawIconEx (USER32.@) Draws an icon or cursor on device context
Alexandre Julliard's avatar
Alexandre Julliard committed
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
 *
 * NOTES
 *    Why is this using SM_CXICON instead of SM_CXCURSOR?
 *
 * PARAMS
 *    hdc     [I] Handle to device context
 *    x0      [I] X coordinate of upper left corner
 *    y0      [I] Y coordinate of upper left corner
 *    hIcon   [I] Handle to icon to draw
 *    cxWidth [I] Width of icon
 *    cyWidth [I] Height of icon
 *    istep   [I] Index of frame in animated cursor
 *    hbr     [I] Handle to background brush
 *    flags   [I] Icon-drawing flags
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
 */
2334
BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2335
                            INT cxWidth, INT cyWidth, UINT istep,
2336
                            HBRUSH hbr, UINT flags )
Alexandre Julliard's avatar
Alexandre Julliard committed
2337
{
2338
    struct cursoricon_frame *frame;
2339
    struct cursoricon_object *ptr;
2340
    HDC hdc_dest, hMemDC;
2341
    BOOL result = FALSE, DoOffscreen;
2342 2343 2344
    HBITMAP hB_off = 0;
    COLORREF oldFg, oldBg;
    INT x, y, nStretchMode;
2345

2346 2347
    TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
                 hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
Alexandre Julliard's avatar
Alexandre Julliard committed
2348

2349
    if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2350
    if (istep >= get_icon_steps( ptr ))
2351
    {
2352
        TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
2353
        release_user_handle_ptr( ptr );
2354 2355
        return FALSE;
    }
2356 2357 2358
    if (!(frame = get_icon_frame( ptr, istep )))
    {
        FIXME_(icon)("Error retrieving icon frame %d\n", istep);
2359
        release_user_handle_ptr( ptr );
2360 2361
        return FALSE;
    }
2362
    if (!(hMemDC = CreateCompatibleDC( hdc )))
2363
    {
2364
        release_icon_frame( ptr, frame );
2365
        release_user_handle_ptr( ptr );
2366 2367
        return FALSE;
    }
2368

2369 2370
    if (flags & DI_NOMIRROR)
        FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
2371

2372 2373
    /* Calculate the size of the destination image.  */
    if (cxWidth == 0)
2374
    {
2375 2376 2377
        if (flags & DI_DEFAULTSIZE)
            cxWidth = GetSystemMetrics (SM_CXICON);
        else
2378
            cxWidth = frame->width;
2379
    }
2380
    if (cyWidth == 0)
2381
    {
2382 2383 2384
        if (flags & DI_DEFAULTSIZE)
            cyWidth = GetSystemMetrics (SM_CYICON);
        else
2385
            cyWidth = frame->height;
2386
    }
2387

2388 2389
    DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);

2390
    if (DoOffscreen) {
2391 2392
        RECT r;

2393
        SetRect(&r, 0, 0, cxWidth, cxWidth);
2394

2395
        if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
2396 2397 2398
        if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
        {
            DeleteDC( hdc_dest );
2399
            goto failed;
2400
        }
2401 2402 2403
        SelectObject(hdc_dest, hB_off);
        FillRect(hdc_dest, &r, hbr);
        x = y = 0;
2404
    }
2405
    else
Alexandre Julliard's avatar
Alexandre Julliard committed
2406
    {
2407 2408 2409 2410
        hdc_dest = hdc;
        x = x0;
        y = y0;
    }
2411

2412
    nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2413

2414 2415
    oldFg = SetTextColor( hdc, RGB(0,0,0) );
    oldBg = SetBkColor( hdc, RGB(255,255,255) );
2416

2417
    if (frame->alpha && (flags & DI_IMAGE))
2418
    {
2419
        BOOL alpha_blend = TRUE;
2420

2421 2422 2423 2424
        if (GetObjectType( hdc_dest ) == OBJ_MEMDC)
        {
            BITMAP bm;
            HBITMAP bmp = GetCurrentObject( hdc_dest, OBJ_BITMAP );
2425
            alpha_blend = GetObjectW( bmp, sizeof(bm), &bm ) && bm.bmBitsPixel > 8;
2426
        }
2427
        if (alpha_blend)
2428 2429
        {
            BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2430
            SelectObject( hMemDC, frame->alpha );
2431
            if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
2432 2433
                               0, 0, frame->width, frame->height,
                               pixelblend )) goto done;
2434
        }
2435 2436 2437
    }

    if (flags & DI_MASK)
2438
    {
2439
        DWORD rop = (flags & DI_IMAGE) ? SRCAND : SRCCOPY;
2440
        SelectObject( hMemDC, frame->mask );
2441
        StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2442
                    hMemDC, 0, 0, frame->width, frame->height, rop );
2443
    }
2444

2445 2446
    if (flags & DI_IMAGE)
    {
2447
        if (frame->color)
2448 2449
        {
            DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2450
            SelectObject( hMemDC, frame->color );
2451
            StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2452
                        hMemDC, 0, 0, frame->width, frame->height, rop );
2453 2454 2455 2456
        }
        else
        {
            DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2457
            SelectObject( hMemDC, frame->mask );
2458
            StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2459 2460
                        hMemDC, 0, frame->height, frame->width,
                        frame->height, rop );
2461
        }
Alexandre Julliard's avatar
Alexandre Julliard committed
2462
    }
2463

2464
done:
2465 2466 2467 2468 2469 2470 2471
    if (DoOffscreen) BitBlt( hdc, x0, y0, cxWidth, cyWidth, hdc_dest, 0, 0, SRCCOPY );

    SetTextColor( hdc, oldFg );
    SetBkColor( hdc, oldBg );
    SetStretchBltMode (hdc, nStretchMode);
    result = TRUE;
    if (hdc_dest != hdc) DeleteDC( hdc_dest );
2472
    if (hB_off) DeleteObject(hB_off);
2473
failed:
2474
    DeleteDC( hMemDC );
2475
    release_icon_frame( ptr, frame );
2476
    release_user_handle_ptr( ptr );
Alexandre Julliard's avatar
Alexandre Julliard committed
2477 2478
    return result;
}
2479

2480 2481 2482 2483 2484 2485 2486 2487
/***********************************************************************
 *           DIB_FixColorsToLoadflags
 *
 * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
 * are in loadflags
 */
static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
{
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
    int colors;
    COLORREF c_W, c_S, c_F, c_L, c_C;
    int incr,i;
    RGBQUAD *ptr;
    int bitmap_type;
    LONG width;
    LONG height;
    WORD bpp;
    DWORD compr;

    if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
    {
        WARN_(resource)("Invalid bitmap\n");
        return;
    }

    if (bpp > 8) return;

    if (bitmap_type == 0) /* BITMAPCOREHEADER */
    {
        incr = 3;
        colors = 1 << bpp;
    }
    else
    {
        incr = 4;
        colors = bmi->bmiHeader.biClrUsed;
        if (colors > 256) colors = 256;
        if (!colors && (bpp <= 8)) colors = 1 << bpp;
    }

    c_W = GetSysColor(COLOR_WINDOW);
    c_S = GetSysColor(COLOR_3DSHADOW);
    c_F = GetSysColor(COLOR_3DFACE);
    c_L = GetSysColor(COLOR_3DLIGHT);

    if (loadflags & LR_LOADTRANSPARENT) {
        switch (bpp) {
        case 1: pix = pix >> 7; break;
        case 4: pix = pix >> 4; break;
        case 8: break;
        default:
            WARN_(resource)("(%d): Unsupported depth\n", bpp);
            return;
        }
        if (pix >= colors) {
            WARN_(resource)("pixel has color index greater than biClrUsed!\n");
            return;
        }
        if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
        ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
        ptr->rgbBlue = GetBValue(c_W);
        ptr->rgbGreen = GetGValue(c_W);
        ptr->rgbRed = GetRValue(c_W);
2542
    }
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
    if (loadflags & LR_LOADMAP3DCOLORS)
        for (i=0; i<colors; i++) {
            ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
            c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
            if (c_C == RGB(128, 128, 128)) {
                ptr->rgbRed = GetRValue(c_S);
                ptr->rgbGreen = GetGValue(c_S);
                ptr->rgbBlue = GetBValue(c_S);
            } else if (c_C == RGB(192, 192, 192)) {
                ptr->rgbRed = GetRValue(c_F);
                ptr->rgbGreen = GetGValue(c_F);
                ptr->rgbBlue = GetBValue(c_F);
            } else if (c_C == RGB(223, 223, 223)) {
                ptr->rgbRed = GetRValue(c_L);
                ptr->rgbGreen = GetGValue(c_L);
                ptr->rgbBlue = GetBValue(c_L);
            }
        }
2561 2562 2563
}


2564 2565 2566
/**********************************************************************
 *       BITMAP_Load
 */
2567 2568
static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
                            INT desiredx, INT desiredy, UINT loadflags )
2569
{
2570
    HBITMAP hbitmap = 0, orig_bm;
2571 2572
    HRSRC hRsrc;
    HGLOBAL handle;
2573
    const char *ptr = NULL;
2574
    BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2575
    int size;
2576 2577 2578 2579
    BYTE pix;
    char *bits;
    LONG width, height, new_width, new_height;
    WORD bpp_dummy;
2580
    DWORD compr_dummy, offbits = 0;
2581 2582
    INT bm_type;
    HDC screen_mem_dc = NULL;
2583

2584 2585
    if (!(loadflags & LR_LOADFROMFILE))
    {
2586 2587 2588 2589 2590
        if (!instance)
        {
            /* OEM bitmap: try to load the resource from user32.dll */
            instance = user32_module;
        }
2591

2592 2593
        if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
        if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2594

2595
        if ((info = LockResource( handle )) == NULL) return 0;
2596 2597 2598
    }
    else
    {
2599 2600
        BITMAPFILEHEADER * bmfh;

2601
        if (!(ptr = map_fileW( name, NULL ))) return 0;
2602
        info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2603
        bmfh = (BITMAPFILEHEADER *)ptr;
2604
        if (bmfh->bfType != 0x4d42 /* 'BM' */)
2605 2606
        {
            WARN("Invalid/unsupported bitmap format!\n");
2607
            goto end;
2608
        }
2609
        if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2610
    }
2611

2612 2613 2614 2615 2616 2617 2618 2619
    bm_type = DIB_GetBitmapInfo( &info->bmiHeader, &width, &height,
                                 &bpp_dummy, &compr_dummy);
    if (bm_type == -1)
    {
        WARN("Invalid bitmap format!\n");
        goto end;
    }

2620
    size = bitmap_info_size(info, DIB_RGB_COLORS);
2621 2622
    fix_info = HeapAlloc(GetProcessHeap(), 0, size);
    scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2623

2624 2625
    if (!fix_info || !scaled_info) goto end;
    memcpy(fix_info, info, size);
2626

2627 2628
    pix = *((LPBYTE)info + size);
    DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2629

2630
    memcpy(scaled_info, fix_info, size);
2631

2632 2633 2634 2635
    if(desiredx != 0)
        new_width = desiredx;
    else
        new_width = width;
2636

2637 2638 2639 2640
    if(desiredy != 0)
        new_height = height > 0 ? desiredy : -desiredy;
    else
        new_height = height;
2641

2642 2643 2644 2645 2646 2647 2648 2649
    if(bm_type == 0)
    {
        BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
        core->bcWidth = new_width;
        core->bcHeight = new_height;
    }
    else
    {
2650 2651 2652 2653 2654 2655
        /* Some sanity checks for BITMAPINFO (not applicable to BITMAPCOREINFO) */
        if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
            WARN("Broken BitmapInfoHeader!\n");
            goto end;
        }

2656 2657 2658 2659 2660 2661
        scaled_info->bmiHeader.biWidth = new_width;
        scaled_info->bmiHeader.biHeight = new_height;
    }

    if (new_height < 0) new_height = -new_height;

2662
    if (!(screen_mem_dc = CreateCompatibleDC( 0 ))) goto end;
2663

2664
    bits = (char *)info + (offbits ? offbits : size);
2665

2666 2667 2668
    if (loadflags & LR_CREATEDIBSECTION)
    {
        scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2669
        hbitmap = CreateDIBSection(0, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2670 2671 2672 2673 2674 2675
    }
    else
    {
        if (is_dib_monochrome(fix_info))
            hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
        else
2676
            hbitmap = create_color_bitmap(new_width, new_height);
2677
    }
2678

2679
    orig_bm = SelectObject(screen_mem_dc, hbitmap);
2680 2681
    if (info->bmiHeader.biBitCount > 1)
        SetStretchBltMode(screen_mem_dc, HALFTONE);
2682 2683 2684 2685 2686 2687 2688
    StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
    SelectObject(screen_mem_dc, orig_bm);

end:
    if (screen_mem_dc) DeleteDC(screen_mem_dc);
    HeapFree(GetProcessHeap(), 0, scaled_info);
    HeapFree(GetProcessHeap(), 0, fix_info);
2689
    if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2690

2691 2692 2693 2694
    return hbitmap;
}

/**********************************************************************
2695
 *		LoadImageA (USER32.@)
2696
 *
2697
 * See LoadImageW.
2698 2699 2700 2701 2702 2703 2704
 */
HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
                              INT desiredx, INT desiredy, UINT loadflags)
{
    HANDLE res;
    LPWSTR u_name;

2705
    if (IS_INTRESOURCE(name))
2706
        return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2707

2708
    __TRY {
2709 2710 2711
        DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
        u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2712
    }
2713
    __EXCEPT_PAGE_FAULT {
2714 2715
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
2716 2717
    }
    __ENDTRY
2718
    res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2719
    HeapFree(GetProcessHeap(), 0, u_name);
2720 2721 2722 2723 2724
    return res;
}


/******************************************************************************
2725
 *		LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738
 *
 * PARAMS
 *    hinst     [I] Handle of instance that contains image
 *    name      [I] Name of image
 *    type      [I] Type of image
 *    desiredx  [I] Desired width
 *    desiredy  [I] Desired height
 *    loadflags [I] Load flags
 *
 * RETURNS
 *    Success: Handle to newly loaded image
 *    Failure: NULL
 *
2739
 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2740 2741 2742 2743
 */
HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
                INT desiredx, INT desiredy, UINT loadflags )
{
2744
    int depth;
2745
    WCHAR path[MAX_PATH];
2746

2747 2748 2749
    TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
                     hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);

2750 2751 2752 2753 2754 2755
    if (loadflags & LR_LOADFROMFILE)
    {
        loadflags &= ~LR_SHARED;
        /* relative paths are not only relative to the current working directory */
        if (SearchPathW(NULL, name, NULL, ARRAY_SIZE(path), path, NULL)) name = path;
    }
2756 2757
    switch (type) {
    case IMAGE_BITMAP:
2758
        return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2759 2760

    case IMAGE_ICON:
2761 2762
    case IMAGE_CURSOR:
        depth = 1;
2763
        if (!(loadflags & LR_MONOCHROME)) depth = get_display_bpp();
2764
        return CURSORICON_Load(hinst, name, desiredx, desiredy, depth, (type == IMAGE_CURSOR), loadflags);
2765 2766 2767 2768 2769
    }
    return 0;
}

/******************************************************************************
2770
 *		CopyImage (USER32.@) Creates new image and copies attributes to it
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
 *
 * PARAMS
 *    hnd      [I] Handle to image to copy
 *    type     [I] Type of image to copy
 *    desiredx [I] Desired width of new image
 *    desiredy [I] Desired height of new image
 *    flags    [I] Copy flags
 *
 * RETURNS
 *    Success: Handle to newly created image
 *    Failure: NULL
 *
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
 * BUGS
 *    Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
 *    all other versions (95/2000/XP have been tested) ignore it.
 *
 * NOTES
 *    If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
 *    a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
 *    the copy will have the same depth as the screen.
 *    The content of the image will only be copied if the bit depth of the
 *    original image is compatible with the bit depth of the screen, or
 *    if the source is a DIB section.
 *    The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
2795
 */
2796
HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2797 2798
                             INT desiredy, UINT flags )
{
2799 2800 2801
    TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
          hnd, type, desiredx, desiredy, flags);

2802 2803
    switch (type)
    {
2804
        case IMAGE_BITMAP:
2805
        {
2806 2807 2808 2809
            HBITMAP res = NULL;
            DIBSECTION ds;
            int objSize;
            BITMAPINFO * bi;
2810

2811 2812 2813 2814 2815
            objSize = GetObjectW( hnd, sizeof(ds), &ds );
            if (!objSize) return 0;
            if ((desiredx < 0) || (desiredy < 0)) return 0;

            if (flags & LR_COPYFROMRESOURCE)
2816
            {
2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
                FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
            }

            if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
            if (desiredy == 0) desiredy = ds.dsBm.bmHeight;

            /* Allocate memory for a BITMAPINFOHEADER structure and a
               color table. The maximum number of colors in a color table
               is 256 which corresponds to a bitmap with depth 8.
               Bitmaps with higher depths don't have color tables. */
            bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
            if (!bi) return 0;

            bi->bmiHeader.biSize        = sizeof(bi->bmiHeader);
            bi->bmiHeader.biPlanes      = ds.dsBm.bmPlanes;
            bi->bmiHeader.biBitCount    = ds.dsBm.bmBitsPixel;
            bi->bmiHeader.biCompression = BI_RGB;

            if (flags & LR_CREATEDIBSECTION)
            {
                /* Create a DIB section. LR_MONOCHROME is ignored */
                void * bits;
                HDC dc = CreateCompatibleDC(NULL);

                if (objSize == sizeof(DIBSECTION))
                {
                    /* The source bitmap is a DIB.
                       Get its attributes to create an exact copy */
                    memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
                }

                bi->bmiHeader.biWidth  = desiredx;
                bi->bmiHeader.biHeight = desiredy;
2850 2851 2852

                /* Get the color table or the color masks */
                GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867

                res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
                DeleteDC(dc);
            }
            else
            {
                /* Create a device-dependent bitmap */

                BOOL monochrome = (flags & LR_MONOCHROME);

                if (objSize == sizeof(DIBSECTION))
                {
                    /* The source bitmap is a DIB section.
                       Get its attributes */
                    HDC dc = CreateCompatibleDC(NULL);
2868 2869
                    bi->bmiHeader.biWidth  = ds.dsBm.bmWidth;
                    bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
                    GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
                    DeleteDC(dc);

                    if (!monochrome && ds.dsBm.bmBitsPixel == 1)
                    {
                        /* Look if the colors of the DIB are black and white */

                        monochrome = 
                              (bi->bmiColors[0].rgbRed == 0xff
                            && bi->bmiColors[0].rgbGreen == 0xff
                            && bi->bmiColors[0].rgbBlue == 0xff
                            && bi->bmiColors[0].rgbReserved == 0
                            && bi->bmiColors[1].rgbRed == 0
                            && bi->bmiColors[1].rgbGreen == 0
                            && bi->bmiColors[1].rgbBlue == 0
                            && bi->bmiColors[1].rgbReserved == 0)
                            ||
                              (bi->bmiColors[0].rgbRed == 0
                            && bi->bmiColors[0].rgbGreen == 0
                            && bi->bmiColors[0].rgbBlue == 0
                            && bi->bmiColors[0].rgbReserved == 0
                            && bi->bmiColors[1].rgbRed == 0xff
                            && bi->bmiColors[1].rgbGreen == 0xff
                            && bi->bmiColors[1].rgbBlue == 0xff
                            && bi->bmiColors[1].rgbReserved == 0);
                    }
                }
                else if (!monochrome)
                {
                    monochrome = ds.dsBm.bmBitsPixel == 1;
                }

                if (monochrome)
                    res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
                else
2905
                    res = create_color_bitmap(desiredx, desiredy);
2906 2907 2908 2909 2910 2911
            }

            if (res)
            {
                /* Only copy the bitmap if it's a DIB section or if it's
                   compatible to the screen */
2912 2913 2914
                if (objSize == sizeof(DIBSECTION) ||
                    ds.dsBm.bmBitsPixel == 1 ||
                    ds.dsBm.bmBitsPixel == get_display_bpp())
2915 2916 2917 2918 2919 2920 2921 2922
                {
                    /* The source bitmap may already be selected in a device context,
                       use GetDIBits/StretchDIBits and not StretchBlt  */

                    HDC dc;
                    void * bits;

                    dc = CreateCompatibleDC(NULL);
2923 2924
                    if (ds.dsBm.bmBitsPixel > 1)
                        SetStretchBltMode(dc, HALFTONE);
2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959

                    bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
                    bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
                    bi->bmiHeader.biSizeImage = 0;
                    bi->bmiHeader.biClrUsed = 0;
                    bi->bmiHeader.biClrImportant = 0;

                    /* Fill in biSizeImage */
                    GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
                    bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);

                    if (bits)
                    {
                        HBITMAP oldBmp;

                        /* Get the image bits of the source bitmap */
                        GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);

                        /* Copy it to the destination bitmap */
                        oldBmp = SelectObject(dc, res);
                        StretchDIBits(dc, 0, 0, desiredx, desiredy,
                                      0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
                                      bits, bi, DIB_RGB_COLORS, SRCCOPY);
                        SelectObject(dc, oldBmp);

                        HeapFree(GetProcessHeap(), 0, bits);
                    }

                    DeleteDC(dc);
                }

                if (flags & LR_COPYDELETEORG)
                {
                    DeleteObject(hnd);
                }
2960
            }
2961
            HeapFree(GetProcessHeap(), 0, bi);
2962
            return res;
2963
        }
2964 2965
        case IMAGE_ICON:
        case IMAGE_CURSOR:
2966 2967 2968
        {
            struct cursoricon_object *icon;
            HICON res = 0;
2969
            int depth = (flags & LR_MONOCHROME) ? 1 : get_display_bpp();
2970 2971 2972 2973 2974 2975 2976 2977 2978

            if (flags & LR_DEFAULTSIZE)
            {
                if (!desiredx) desiredx = GetSystemMetrics( type == IMAGE_ICON ? SM_CXICON : SM_CXCURSOR );
                if (!desiredy) desiredy = GetSystemMetrics( type == IMAGE_ICON ? SM_CYICON : SM_CYCURSOR );
            }

            if (!(icon = get_icon_ptr( hnd ))) return 0;

2979
            if (icon->rsrc && (flags & LR_COPYFROMRESOURCE))
2980
                res = CURSORICON_Load( icon->module, icon->resname, desiredx, desiredy, depth,
2981
                                       !icon->is_icon, flags );
2982 2983
            else
                res = CopyIcon( hnd ); /* FIXME: change size if necessary */
2984
            release_user_handle_ptr( icon );
2985 2986 2987 2988

            if (res && (flags & LR_COPYDELETEORG)) DeleteObject( hnd );
            return res;
        }
2989 2990 2991 2992 2993 2994
    }
    return 0;
}


/******************************************************************************
2995
 *		LoadBitmapW (USER32.@) Loads bitmap from the executable file
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
 *
 * RETURNS
 *    Success: Handle to specified bitmap
 *    Failure: NULL
 */
HBITMAP WINAPI LoadBitmapW(
    HINSTANCE instance, /* [in] Handle to application instance */
    LPCWSTR name)         /* [in] Address of bitmap resource name */
{
    return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
}

/**********************************************************************
3009
 *		LoadBitmapA (USER32.@)
3010 3011
 *
 * See LoadBitmapW.
3012 3013 3014 3015 3016
 */
HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
{
    return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );
}