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

Steven Edwards's avatar
Steven Edwards committed
25 26 27
#include "config.h"
#include "wine/port.h"

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

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

47
WINE_DEFAULT_DEBUG_CHANNEL(cursor);
48 49
WINE_DECLARE_DEBUG_CHANNEL(icon);
WINE_DECLARE_DEBUG_CHANNEL(resource);
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include "pshpack1.h"

typedef struct {
    BYTE bWidth;
    BYTE bHeight;
    BYTE bColorCount;
    BYTE bReserved;
    WORD xHotspot;
    WORD yHotspot;
    DWORD dwDIBSize;
    DWORD dwDIBOffset;
} CURSORICONFILEDIRENTRY;

typedef struct
{
    WORD                idReserved;
    WORD                idType;
    WORD                idCount;
    CURSORICONFILEDIRENTRY  idEntries[1];
} CURSORICONFILEDIR;

#include "poppack.h"

74
static HDC screen_dc;
75

76 77
static const WCHAR DISPLAYW[] = {'D','I','S','P','L','A','Y',0};

78
static struct list icon_cache = LIST_INIT( icon_cache );
79

80 81 82 83
/**********************************************************************
 * User objects management
 */

84
struct cursoricon_frame
85
{
86 87
    UINT               width;    /* frame-specific width */
    UINT               height;   /* frame-specific height */
88
    UINT               delay;    /* frame-specific delay between this frame and the next (in jiffies) */
89
    HBITMAP            color;    /* color bitmap */
90
    HBITMAP            alpha;    /* pre-multiplied alpha bitmap for 32-bpp icons */
91
    HBITMAP            mask;     /* mask bitmap (followed by color for 1-bpp icons) */
92 93 94 95
};

struct cursoricon_object
{
96
    struct user_object      obj;        /* object header */
97
    struct list             entry;      /* entry in shared icons list */
98
    ULONG_PTR               param;      /* opaque param used by 16-bit code */
99 100
    HMODULE                 module;     /* module for icons loaded from resources */
    LPWSTR                  resname;    /* resource name for icons loaded from resources */
101
    HRSRC                   rsrc;       /* resource for shared icons */
102
    BOOL                    is_icon;    /* whether icon or cursor */
103 104
    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) */
105
    POINT                   hotspot;
106 107
};

108
struct static_cursoricon_object
109
{
110 111 112 113 114 115 116 117 118 119 120 121
    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 */
};

122
static HICON alloc_icon_handle( BOOL is_ani, UINT num_steps )
123 124 125
{
    struct cursoricon_object *obj;
    int icon_size;
126
    HICON handle;
127 128

    if (is_ani)
129
        icon_size = FIELD_OFFSET( struct animated_cursoricon_object, frames[num_steps] );
130 131 132
    else
        icon_size = sizeof( struct static_cursoricon_object );
    obj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, icon_size );
133
    if (!obj) return NULL;
134

135
    obj->delay = 0;
136 137 138 139 140
    obj->is_ani = is_ani;
    if (is_ani)
    {
        struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;

141 142
        ani_icon_data->num_steps = num_steps;
        ani_icon_data->num_frames = num_steps; /* changed later for some animated cursors */
143
    }
144 145 146 147

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

150
static struct cursoricon_object *get_icon_ptr( HICON handle )
151 152 153 154 155 156 157
{
    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;
    }
158
    return obj;
159 160
}

161
static void release_icon_ptr( HICON handle, struct cursoricon_object *ptr )
162
{
163
    release_user_handle_ptr( ptr );
164 165
}

166 167
static struct cursoricon_frame *get_icon_frame( struct cursoricon_object *obj, int istep )
{
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    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;
184 185 186 187
}

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

        ani_icon_data = (struct animated_cursoricon_object *) obj;
        frameobj = (struct cursoricon_object *) (((char *)frame) - FIELD_OFFSET(struct static_cursoricon_object, frame));
        release_icon_ptr( ani_icon_data->frames[istep], frameobj );
    }
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 230

            if (frame->alpha) DeleteObject( frame->alpha );
            if (frame->color) DeleteObject( frame->color );
            DeleteObject( frame->mask );
            release_icon_frame( obj, 0, 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 339 340
}


/***********************************************************************
 *           bitmap_info_size
 *
 * Return the size of the bitmap info structure including color table.
 */
static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
{
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 409 410
/***********************************************************************
 *          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.biBitCount != 1) return FALSE;

    if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
    {
411
        const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
412

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 430 431 432 433 434 435 436 437 438 439 440 441

        /* 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;
    }
}

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

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

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

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

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

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

    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 */
522
        if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
523 524 525
        iTotalDiff = 0;
    }

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

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

539
    /* Find Best Colors for Best Fit */
540
    for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
541
    {
542
        if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
Alexandre Julliard's avatar
Alexandre Julliard committed
543
        {
544
            iTempColorDiff = abs(depth - bits);
545
            if(iColorDiff > iTempColorDiff)
546
            {
547
                bestEntry = i;
548
                iColorDiff = iTempColorDiff;
549
            }
550 551
        }
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
552 553 554 555

    return bestEntry;
}

556
static BOOL CURSORICON_GetResIconEntry( LPCVOID dir, DWORD size, int n,
557 558
                                        int *width, int *height, int *bits )
{
559 560
    const CURSORICONDIR *resdir = dir;
    const ICONRESDIR *icon;
561 562 563

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

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

585 586 587 588 589 590 591 592
    if (loadflags & LR_DEFAULTSIZE)
    {
        if (!width) width = GetSystemMetrics( SM_CXCURSOR );
        if (!height) height = GetSystemMetrics( SM_CYCURSOR );
    }
    else if (!width && !height)
    {
        /* use the first entry */
593
        if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
594 595 596
        return 0;
    }

597 598 599 600
    /* Double height to account for AND and XOR masks */

    height *= 2;

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

    maxwidth = maxheight = 0;
604
    for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
605 606
    {
        if ((cx <= width) && (cy <= height) &&
607
            (cx > maxwidth) && (cy > maxheight))
Alexandre Julliard's avatar
Alexandre Julliard committed
608
        {
609 610 611
            bestEntry = i;
            maxwidth  = cx;
            maxheight = cy;
Alexandre Julliard's avatar
Alexandre Julliard committed
612
        }
613 614
    }
    if (bestEntry != -1) return bestEntry;
Alexandre Julliard's avatar
Alexandre Julliard committed
615 616 617 618

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

    maxwidth = maxheight = 255;
619
    for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
620
    {
621
        if (((cx < maxwidth) && (cy < maxheight)) || (bestEntry == -1))
Alexandre Julliard's avatar
Alexandre Julliard committed
622
        {
623 624 625
            bestEntry = i;
            maxwidth  = cx;
            maxheight = cy;
Alexandre Julliard's avatar
Alexandre Julliard committed
626
        }
627
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
628 629 630 631

    return bestEntry;
}

632
static BOOL CURSORICON_GetResCursorEntry( LPCVOID dir, DWORD size, int n,
633 634
                                          int *width, int *height, int *bits )
{
635 636
    const CURSORICONDIR *resdir = dir;
    const CURSORDIR *cursor;
637 638 639

    if ( resdir->idCount <= n )
        return FALSE;
640 641
    if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
        return FALSE;
642 643 644 645 646 647 648
    cursor = &resdir->idEntries[n].ResInfo.cursor;
    *width = cursor->wWidth;
    *height = cursor->wHeight;
    *bits = resdir->idEntries[n].wBitCount;
    return TRUE;
}

649
static const CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( const CURSORICONDIR * dir, DWORD size,
650 651
                                                             int width, int height, int depth,
                                                             UINT loadflags )
652 653 654
{
    int n;

655
    n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetResIconEntry,
656
                                 width, height, depth, loadflags );
657 658 659 660 661
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

662
static const CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( const CURSORICONDIR *dir, DWORD size,
663 664
                                                               int width, int height, int depth,
                                                               UINT loadflags )
665
{
666
    int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetResCursorEntry,
667
                                       width, height, depth, loadflags );
668 669 670 671 672
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

673
static BOOL CURSORICON_GetFileEntry( LPCVOID dir, DWORD size, int n,
674
                                     int *width, int *height, int *bits )
675
{
676 677 678
    const CURSORICONFILEDIR *filedir = dir;
    const CURSORICONFILEDIRENTRY *entry;
    const BITMAPINFOHEADER *info;
679

680 681
    if ( filedir->idCount <= n )
        return FALSE;
682 683
    if ((const char *)&filedir->idEntries[n + 1] - (const char *)dir > size)
        return FALSE;
684
    entry = &filedir->idEntries[n];
685
    info = (const BITMAPINFOHEADER *)((const char *)dir + entry->dwDIBOffset);
686
    if ((const char *)(info + 1) - (const char *)dir > size) return FALSE;
687 688
    *width = entry->bWidth;
    *height = entry->bHeight;
689
    *bits = info->biBitCount;
690
    return TRUE;
691
}
Alexandre Julliard's avatar
Alexandre Julliard committed
692

693
static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( const CURSORICONFILEDIR *dir, DWORD size,
694 695
                                                                    int width, int height, int depth,
                                                                    UINT loadflags )
696
{
697
    int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetFileEntry,
698
                                       width, height, depth, loadflags );
699 700 701 702 703
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

704
static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( const CURSORICONFILEDIR *dir, DWORD size,
705 706
                                                                  int width, int height, int depth,
                                                                  UINT loadflags )
707
{
708
    int n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetFileEntry,
709
                                     width, height, depth, loadflags );
710 711 712 713
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}
Alexandre Julliard's avatar
Alexandre Julliard committed
714

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
/***********************************************************************
 *          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.
 */
static HBITMAP create_alpha_bitmap( HBITMAP color, HBITMAP mask,
                                    const BITMAPINFO *src_info, const void *color_bits )
{
    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;
}


799
/***********************************************************************
800
 *          create_icon_from_bmi
801
 *
802
 * Create an icon from its BITMAPINFO.
803
 */
804 805 806
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 )
807
{
808
    DWORD size, color_size, mask_size;
809
    HBITMAP color = 0, mask = 0, alpha = 0;
810
    const void *color_bits, *mask_bits;
811
    BITMAPINFO *bmi_copy;
812
    BOOL ret = FALSE;
813 814
    BOOL do_stretch;
    HICON hObj = 0;
815 816
    HDC hdc = 0;

817 818
    /* Check bitmap header */

819 820 821 822 823 824 825 826 827 828
    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;
    }
829 830
    if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
         (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER)  ||
831 832
         (bmi->bmiHeader.biCompression != BI_RGB &&
          bmi->bmiHeader.biCompression != BI_BITFIELDS)) )
833
    {
834 835 836 837 838 839 840 841 842 843 844 845
        WARN( "invalid bitmap header %u\n", bmi->bmiHeader.biSize );
        return 0;
    }

    size = bitmap_info_size( bmi, DIB_RGB_COLORS );
    color_size = get_dib_image_size( bmi->bmiHeader.biWidth, bmi->bmiHeader.biHeight / 2,
                                     bmi->bmiHeader.biBitCount );
    mask_size = get_dib_image_size( bmi->bmiHeader.biWidth, bmi->bmiHeader.biHeight / 2, 1 );
    if (size > maxsize || color_size > maxsize - size)
    {
        WARN( "truncated file %u < %u+%u+%u\n", maxsize, size, color_size, mask_size );
        return 0;
846
    }
847
    if (mask_size > maxsize - size - color_size) mask_size = 0;  /* no mask */
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

    if (cFlag & LR_DEFAULTSIZE)
    {
        if (!width) width = GetSystemMetrics( bIcon ? SM_CXICON : SM_CXCURSOR );
        if (!height) height = GetSystemMetrics( bIcon ? SM_CYICON : SM_CYCURSOR );
    }
    else
    {
        if (!width) width = bmi->bmiHeader.biWidth;
        if (!height) height = bmi->bmiHeader.biHeight/2;
    }
    do_stretch = (bmi->bmiHeader.biHeight/2 != height) ||
                 (bmi->bmiHeader.biWidth != width);

    /* Scale the hotspot */
    if (bIcon)
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
    }
    else if (do_stretch)
    {
        hotspot.x = (hotspot.x * width) / bmi->bmiHeader.biWidth;
        hotspot.y = (hotspot.y * height) / (bmi->bmiHeader.biHeight / 2);
    }

    if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
    if (!screen_dc) return 0;

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

881 882
    memcpy( bmi_copy, bmi, size );
    bmi_copy->bmiHeader.biHeight /= 2;
883

884
    color_bits = (const char*)bmi + size;
885
    mask_bits = (const char*)color_bits + color_size;
886

887
    alpha = 0;
888
    if (is_dib_monochrome( bmi ))
889
    {
890 891
        if (!(mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
        color = 0;
892 893

        /* copy color data into second half of mask bitmap */
894
        SelectObject( hdc, mask );
895
        StretchDIBits( hdc, 0, height, width, height,
896 897
                       0, 0, bmi_copy->bmiHeader.biWidth, bmi_copy->bmiHeader.biHeight,
                       color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
898 899 900
    }
    else
    {
901 902
        if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
        if (!(color = CreateBitmap( width, height, GetDeviceCaps( screen_dc, PLANES ),
903 904
                                     GetDeviceCaps( screen_dc, BITSPIXEL ), NULL )))
        {
905
            DeleteObject( mask );
906 907
            goto done;
        }
908
        SelectObject( hdc, color );
909
        StretchDIBits( hdc, 0, 0, width, height,
910 911
                       0, 0, bmi_copy->bmiHeader.biWidth, bmi_copy->bmiHeader.biHeight,
                       color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
912

913 914
        if (bmi_has_alpha( bmi_copy, color_bits ))
            alpha = create_alpha_bitmap( color, mask, bmi_copy, color_bits );
915

916
        /* convert info to monochrome to copy the mask */
917 918
        bmi_copy->bmiHeader.biBitCount = 1;
        if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
919
        {
920
            RGBQUAD *rgb = bmi_copy->bmiColors;
921

922
            bmi_copy->bmiHeader.biClrUsed = bmi_copy->bmiHeader.biClrImportant = 2;
923 924 925 926 927 928
            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
        {
929
            RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)bmi_copy) + 1);
930 931 932 933 934 935

            rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
            rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
        }
    }

936 937 938 939 940 941 942
    if (mask_size)
    {
        SelectObject( hdc, mask );
        StretchDIBits( hdc, 0, 0, width, height,
                       0, 0, bmi_copy->bmiHeader.biWidth, bmi_copy->bmiHeader.biHeight,
                       mask_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
    }
943 944 945 946
    ret = TRUE;

done:
    DeleteDC( hdc );
947
    HeapFree( GetProcessHeap(), 0, bmi_copy );
948

949 950
    if (ret)
        hObj = alloc_icon_handle( FALSE, 1 );
Alexandre Julliard's avatar
Alexandre Julliard committed
951
    if (hObj)
Alexandre Julliard's avatar
Alexandre Julliard committed
952
    {
953
        struct cursoricon_object *info = get_icon_ptr( hObj );
954
        struct cursoricon_frame *frame;
Alexandre Julliard's avatar
Alexandre Julliard committed
955

956
        info->is_icon = bIcon;
957
        info->module  = module;
958
        info->hotspot = hotspot;
959 960 961 962 963 964 965 966
        frame = get_icon_frame( info, 0 );
        frame->delay  = ~0;
        frame->width  = width;
        frame->height = height;
        frame->color  = color;
        frame->mask   = mask;
        frame->alpha  = alpha;
        release_icon_frame( info, 0, frame );
967 968 969 970 971 972 973
        if (!IS_INTRESOURCE(resname))
        {
            info->resname = HeapAlloc( GetProcessHeap(), 0, (strlenW(resname) + 1) * sizeof(WCHAR) );
            if (info->resname) strcpyW( info->resname, resname );
        }
        else info->resname = MAKEINTRESOURCEW( LOWORD(resname) );

974 975 976 977 978
        if (module && (cFlag & LR_SHARED))
        {
            info->rsrc = rsrc;
            list_add_head( &icon_cache, &info->entry );
        }
979
        release_icon_ptr( hObj, info );
Alexandre Julliard's avatar
Alexandre Julliard committed
980
    }
981 982 983
    else
    {
        DeleteObject( color );
984
        DeleteObject( alpha );
985 986
        DeleteObject( mask );
    }
987
    return hObj;
Alexandre Julliard's avatar
Alexandre Julliard committed
988 989 990
}


991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
/**********************************************************************
 *          .ANI cursor support
 */
#define RIFF_FOURCC( c0, c1, c2, c3 ) \
        ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
        ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )

#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')
1004
#define ANI_rate_ID RIFF_FOURCC('r', 'a', 't', 'e')
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

#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)
    {
1067 1068
        if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
                || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1069 1070
        {
            ptr += sizeof(DWORD);
1071
            chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1072 1073 1074 1075 1076 1077 1078 1079
            ptr += sizeof(DWORD);
            if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
            chunk->data = ptr;

            return;
        }

        ptr += sizeof(DWORD);
1080
        ptr += (*(const DWORD *)ptr + 1) & ~1;
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
        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
 */
1098
static HCURSOR CURSORICON_CreateIconFromANI( const BYTE *bits, DWORD bits_size, INT width, INT height,
1099
                                             INT depth, BOOL is_icon, UINT loadflags )
1100
{
1101
    struct animated_cursoricon_object *ani_icon_data;
1102
    struct cursoricon_object *info;
1103
    DWORD *frame_rates = NULL;
1104
    DWORD *frame_seq = NULL;
1105
    ani_header header = {0};
1106
    BOOL use_seq = FALSE;
1107
    HCURSOR cursor = 0;
1108 1109
    UINT i;
    BOOL error = FALSE;
1110
    HICON *frames;
1111 1112 1113 1114 1115

    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};
1116
    riff_chunk_t rate_chunk = {0};
1117
    riff_chunk_t seq_chunk = {0};
1118
    const unsigned char *icon_chunk;
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    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 );

1139 1140 1141 1142 1143 1144 1145
    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)
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    {
        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;
        }
    }
1159 1160

    riff_find_chunk( ANI_rate_ID, 0, &ACON_chunk, &rate_chunk );
1161
    if (rate_chunk.data)
1162
        frame_rates = (DWORD *) rate_chunk.data;
1163

1164 1165 1166 1167 1168 1169 1170
    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;
    }

1171
    cursor = alloc_icon_handle( TRUE, header.num_steps );
1172
    if (!cursor) return 0;
1173
    frames = HeapAlloc( GetProcessHeap(), 0, sizeof(*frames) * header.num_frames );
1174 1175 1176 1177 1178
    if (!frames)
    {
        free_icon_handle( cursor );
        return 0;
    }
1179

1180
    info = get_icon_ptr( cursor );
1181
    ani_icon_data = (struct animated_cursoricon_object *) info;
1182
    info->is_icon = is_icon;
1183
    ani_icon_data->num_frames = header.num_frames;
1184

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

1188 1189 1190
    icon_chunk = fram_chunk.data;
    icon_data = fram_chunk.data + (2 * sizeof(DWORD));
    for (i=0; i<header.num_frames; i++)
1191
    {
1192 1193
        const DWORD chunk_size = *(const DWORD *)(icon_chunk + sizeof(DWORD));
        const CURSORICONFILEDIRENTRY *entry;
1194
        INT frameWidth, frameHeight;
1195
        const BITMAPINFO *bmi;
1196

1197
        entry = CURSORICON_FindBestIconFile((const CURSORICONFILEDIR *) icon_data,
1198
                                            bits + bits_size - icon_data,
1199
                                            width, height, depth, loadflags );
1200 1201 1202 1203 1204

        info->hotspot.x = entry->xHotspot;
        info->hotspot.y = entry->yHotspot;
        if (!header.width || !header.height)
        {
1205 1206
            frameWidth = entry->bWidth;
            frameHeight = entry->bHeight;
1207
        }
1208
        else
1209 1210 1211 1212
        {
            frameWidth = header.width;
            frameHeight = header.height;
        }
1213

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        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 );
        }

1224
        if (!frames[i])
1225 1226 1227 1228 1229 1230
        {
            FIXME_(cursor)("failed to convert animated cursor frame.\n");
            error = TRUE;
            if (i == 0)
            {
                FIXME_(cursor)("Completely failed to create animated cursor!\n");
1231
                ani_icon_data->num_frames = 0;
1232 1233
                release_icon_ptr( cursor, info );
                free_icon_handle( cursor );
1234
                HeapFree( GetProcessHeap(), 0, frames );
1235 1236 1237 1238
                return 0;
            }
            break;
        }
1239

1240 1241 1242 1243
        /* Advance to the next chunk */
        icon_chunk += chunk_size + (2 * sizeof(DWORD));
        icon_data = icon_chunk + (2 * sizeof(DWORD));
    }
1244

1245 1246 1247 1248
    /* 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");
1249 1250
        for (i=1; i<ani_icon_data->num_frames; i++)
            free_icon_handle( ani_icon_data->frames[i] );
1251
        use_seq = FALSE;
1252
        info->delay = 0;
1253 1254
        ani_icon_data->num_steps = 1;
        ani_icon_data->num_frames = 1;
1255
    }
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277

    /* 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;
        release_icon_frame( info, i, frame );
    }

    HeapFree( GetProcessHeap(), 0, frames );
1278
    release_icon_ptr( cursor, info );
1279 1280 1281 1282 1283

    return cursor;
}


1284 1285 1286
/**********************************************************************
 *		CreateIconFromResourceEx (USER32.@)
 *
1287
 * FIXME: Convert to mono when cFlag is LR_MONOCHROME.
1288 1289 1290 1291 1292 1293
 */
HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
                                       BOOL bIcon, DWORD dwVersion,
                                       INT width, INT height,
                                       UINT cFlag )
{
1294
    POINT hotspot;
1295
    const BITMAPINFO *bmi;
1296 1297 1298

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

1301 1302
    if (!bits) return 0;

1303 1304 1305 1306 1307 1308
    if (dwVersion == 0x00020000)
    {
        FIXME_(cursor)("\t2.xx resources are not supported\n");
        return 0;
    }

1309 1310
    /* Check if the resource is an animated icon/cursor */
    if (!memcmp(bits, "RIFF", 4))
1311 1312
        return CURSORICON_CreateIconFromANI( bits, cbSize, width, height,
                                             0 /* default depth */, bIcon, cFlag );
1313

1314
    if (bIcon)
1315 1316 1317
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
1318
        bmi = (BITMAPINFO *)bits;
1319
    }
1320 1321
    else /* get the hotspot */
    {
1322
        const SHORT *pt = (const SHORT *)bits;
1323 1324
        hotspot.x = pt[0];
        hotspot.y = pt[1];
1325
        bmi = (const BITMAPINFO *)(pt + 2);
1326
        cbSize -= 2 * sizeof(*pt);
1327 1328
    }

1329
    return create_icon_from_bmi( bmi, cbSize, NULL, NULL, NULL, hotspot, bIcon, width, height, cFlag );
1330 1331 1332
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1333
/**********************************************************************
1334
 *		CreateIconFromResource (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1335
 */
1336 1337
HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
                                           BOOL bIcon, DWORD dwVersion)
Alexandre Julliard's avatar
Alexandre Julliard committed
1338
{
1339
    return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
Alexandre Julliard's avatar
Alexandre Julliard committed
1340 1341 1342
}


1343
static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1344
                             INT width, INT height, INT depth,
1345 1346
                             BOOL fCursor, UINT loadflags)
{
1347 1348
    const CURSORICONFILEDIRENTRY *entry;
    const CURSORICONFILEDIR *dir;
1349 1350
    DWORD filesize = 0;
    HICON hIcon = 0;
1351
    const BYTE *bits;
1352
    POINT hotspot;
1353 1354 1355 1356 1357 1358 1359

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

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

1360 1361 1362
    /* Check for .ani. */
    if (memcmp( bits, "RIFF", 4 ) == 0)
    {
1363
        hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height, depth, !fCursor, loadflags );
1364 1365 1366
        goto end;
    }

1367
    dir = (const CURSORICONFILEDIR*) bits;
1368
    if ( filesize < FIELD_OFFSET( CURSORICONFILEDIR, idEntries[dir->idCount] ))
1369 1370 1371
        goto end;

    if ( fCursor )
1372
        entry = CURSORICON_FindBestCursorFile( dir, filesize, width, height, depth, loadflags );
1373
    else
1374
        entry = CURSORICON_FindBestIconFile( dir, filesize, width, height, depth, loadflags );
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384

    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;

1385 1386
    hotspot.x = entry->xHotspot;
    hotspot.y = entry->yHotspot;
1387
    hIcon = create_icon_from_bmi( (const BITMAPINFO *)&bits[entry->dwDIBOffset], filesize - entry->dwDIBOffset,
1388
                                  NULL, NULL, NULL, hotspot, !fCursor, width, height, loadflags );
1389 1390 1391 1392 1393 1394
end:
    TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
    UnmapViewOfFile( bits );
    return hIcon;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1395
/**********************************************************************
1396
 *          CURSORICON_Load
Alexandre Julliard's avatar
Alexandre Julliard committed
1397
 *
1398
 * Load a cursor or icon from resource or file.
Alexandre Julliard's avatar
Alexandre Julliard committed
1399
 */
1400
static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1401
                             INT width, INT height, INT depth,
1402
                             BOOL fCursor, UINT loadflags)
Alexandre Julliard's avatar
Alexandre Julliard committed
1403
{
1404 1405
    HANDLE handle = 0;
    HICON hIcon = 0;
1406
    HRSRC hRsrc;
1407
    DWORD size;
1408 1409
    const CURSORICONDIR *dir;
    const CURSORICONDIRENTRY *dirEntry;
1410
    const BYTE *bits;
1411
    WORD wResId;
1412
    POINT hotspot;
1413

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

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

1420
    if (!hInstance) hInstance = user32_module;  /* Load OEM cursor/icon */
1421

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

1425
    /* Get directory resource ID */
Alexandre Julliard's avatar
Alexandre Julliard committed
1426

1427 1428
    if (!(hRsrc = FindResourceW( hInstance, name,
                                 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1429 1430 1431 1432 1433 1434 1435 1436 1437
    {
        /* 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
1438

1439
    /* Find the best entry in the directory */
1440

1441
    if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1442
    if (!(dir = LockResource( handle ))) return 0;
1443
    size = SizeofResource( hInstance, hRsrc );
1444
    if (fCursor)
1445
        dirEntry = CURSORICON_FindBestCursorRes( dir, size, width, height, depth, loadflags );
1446
    else
1447
        dirEntry = CURSORICON_FindBestIconRes( dir, size, width, height, depth, loadflags );
1448 1449 1450
    if (!dirEntry) return 0;
    wResId = dirEntry->wResId;
    FreeResource( handle );
1451

1452
    /* Load the resource */
1453

1454 1455
    if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
                                (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1456

1457
    /* If shared icon, check whether it was already loaded */
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
    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;
    }
1473

1474
    if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1475
    size = SizeofResource( hInstance, hRsrc );
1476
    bits = LockResource( handle );
1477 1478 1479 1480 1481 1482 1483 1484

    if (!fCursor)
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
    }
    else /* get the hotspot */
    {
1485
        const SHORT *pt = (const SHORT *)bits;
1486 1487 1488
        hotspot.x = pt[0];
        hotspot.y = pt[1];
        bits += 2 * sizeof(SHORT);
1489
        size -= 2 * sizeof(SHORT);
1490
    }
1491
    hIcon = create_icon_from_bmi( (const BITMAPINFO *)bits, size, hInstance, name, hRsrc,
1492
                                  hotspot, !fCursor, width, height, loadflags );
1493
    FreeResource( handle );
1494
    return hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1495 1496
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1497

Alexandre Julliard's avatar
Alexandre Julliard committed
1498
/***********************************************************************
1499
 *		CreateCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1500
 */
1501 1502 1503
HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
                                 INT xHotSpot, INT yHotSpot,
                                 INT nWidth, INT nHeight,
Alexandre Julliard's avatar
Alexandre Julliard committed
1504
                                 LPCVOID lpANDbits, LPCVOID lpXORbits )
Alexandre Julliard's avatar
Alexandre Julliard committed
1505
{
1506 1507
    ICONINFO info;
    HCURSOR hCursor;
Alexandre Julliard's avatar
Alexandre Julliard committed
1508

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

1512 1513 1514 1515 1516 1517 1518 1519 1520
    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
1521 1522 1523
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1524
/***********************************************************************
1525
 *		CreateIcon (USER32.@)
1526
 *
1527 1528 1529
 *  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
1530
 *  depth. The provided bitmaps must be top-down bitmaps.
1531
 *  Although Windows does not support 15bpp(*) this API must support it
1532 1533
 *  for Winelib applications.
 *
1534
 *  (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1535 1536
 *      format!
 *
1537 1538 1539 1540
 * RETURNS
 *  Success: handle to an icon
 *  Failure: NULL
 *
1541
 * FIXME: Do we need to resize the bitmaps?
Alexandre Julliard's avatar
Alexandre Julliard committed
1542
 */
1543
HICON WINAPI CreateIcon(
1544
    HINSTANCE hInstance,  /* [in] the application's hInstance */
1545 1546 1547 1548 1549 1550
    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
1551
{
1552
    ICONINFO iinfo;
1553
    HICON hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1554

1555 1556
    TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
                 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1557

1558
    iinfo.fIcon = TRUE;
1559 1560
    iinfo.xHotspot = nWidth / 2;
    iinfo.yHotspot = nHeight / 2;
1561 1562 1563 1564 1565 1566 1567
    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 );
1568 1569

    return hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1570 1571 1572 1573
}


/***********************************************************************
1574
 *		CopyIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1575
 */
1576
HICON WINAPI CopyIcon( HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1577
{
1578
    struct cursoricon_object *ptrOld, *ptrNew;
1579
    HICON hNew;
1580

1581 1582 1583 1584 1585
    if (!(ptrOld = get_icon_ptr( hIcon )))
    {
        SetLastError( ERROR_INVALID_CURSOR_HANDLE );
        return 0;
    }
1586
    if ((hNew = alloc_icon_handle( FALSE, 1 )))
1587
    {
1588 1589
        struct cursoricon_frame *frameOld, *frameNew;

1590
        ptrNew = get_icon_ptr( hNew );
1591 1592
        ptrNew->is_icon = ptrOld->is_icon;
        ptrNew->hotspot = ptrOld->hotspot;
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        if (!(frameOld = get_icon_frame( ptrOld, 0 )))
        {
            release_icon_ptr( hIcon, ptrOld );
            SetLastError( ERROR_INVALID_CURSOR_HANDLE );
            return 0;
        }
        if (!(frameNew = get_icon_frame( ptrNew, 0 )))
        {
            release_icon_frame( ptrOld, 0, frameOld );
            release_icon_ptr( hIcon, ptrOld );
            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 );
        release_icon_frame( ptrOld, 0, frameOld );
        release_icon_frame( ptrNew, 0, frameNew );
1614 1615
        release_icon_ptr( hNew, ptrNew );
    }
1616
    release_icon_ptr( hIcon, ptrOld );
1617
    return hNew;
Alexandre Julliard's avatar
Alexandre Julliard committed
1618
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1619 1620


Alexandre Julliard's avatar
Alexandre Julliard committed
1621
/***********************************************************************
1622
 *		DestroyIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1623
 */
1624
BOOL WINAPI DestroyIcon( HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1625
{
1626 1627 1628
    BOOL ret = FALSE;
    struct cursoricon_object *obj = get_icon_ptr( hIcon );

1629 1630
    TRACE_(icon)("%p\n", hIcon );

1631 1632 1633 1634 1635 1636 1637 1638
    if (obj)
    {
        BOOL shared = (obj->rsrc != NULL);
        release_icon_ptr( hIcon, obj );
        ret = (GetCursor() != hIcon);
        if (!shared) free_icon_handle( hIcon );
    }
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1639 1640
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1641 1642

/***********************************************************************
1643
 *		DestroyCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1644
 */
1645
BOOL WINAPI DestroyCursor( HCURSOR hCursor )
Alexandre Julliard's avatar
Alexandre Julliard committed
1646
{
1647
    return DestroyIcon( hCursor );
Alexandre Julliard's avatar
Alexandre Julliard committed
1648 1649
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1650
/***********************************************************************
1651
 *		DrawIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1652
 */
1653
BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1654
{
1655
    return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1656 1657
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1658
/***********************************************************************
1659
 *		SetCursor (USER32.@)
1660 1661 1662 1663
 *
 * Set the cursor shape.
 *
 * RETURNS
Alexandre Julliard's avatar
Alexandre Julliard committed
1664
 *	A handle to the previous cursor shape.
Alexandre Julliard's avatar
Alexandre Julliard committed
1665
 */
1666
HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1667
{
1668
    struct cursoricon_object *obj;
1669
    HCURSOR hOldCursor;
1670 1671
    int show_count;
    BOOL ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1672

1673
    TRACE("%p\n", hCursor);
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687

    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;
1688
    USER_Driver->pSetCursor( show_count >= 0 ? hCursor : 0 );
1689 1690 1691

    if (!(obj = get_icon_ptr( hOldCursor ))) return 0;
    release_icon_ptr( hOldCursor, obj );
Alexandre Julliard's avatar
Alexandre Julliard committed
1692 1693 1694
    return hOldCursor;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1695
/***********************************************************************
1696
 *		ShowCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1697
 */
1698
INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
Alexandre Julliard's avatar
Alexandre Julliard committed
1699
{
1700 1701
    HCURSOR cursor;
    int increment = bShow ? 1 : -1;
1702
    int count;
1703

1704 1705 1706 1707 1708 1709
    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 );
1710
        count = reply->prev_count + increment;
1711 1712 1713
    }
    SERVER_END_REQ;

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

1716 1717
    if (bShow && !count) USER_Driver->pSetCursor( cursor );
    else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
1718

1719
    return count;
Alexandre Julliard's avatar
Alexandre Julliard committed
1720 1721
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1722
/***********************************************************************
1723
 *		GetCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1724
 */
1725
HCURSOR WINAPI GetCursor(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
1726
{
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    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
1737 1738 1739 1740
}


/***********************************************************************
1741
 *		ClipCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1742
 */
1743
BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
Alexandre Julliard's avatar
Alexandre Julliard committed
1744
{
1745 1746
    BOOL ret;
    RECT new_rect;
1747

1748
    TRACE( "Clipping to %s\n", wine_dbgstr_rect(rect) );
1749

1750 1751
    if (rect && (rect->left > rect->right || rect->top > rect->bottom)) return FALSE;

1752 1753
    SERVER_START_REQ( set_cursor )
    {
1754
        req->clip_msg = WM_WINE_CLIPCURSOR;
1755 1756
        if (rect)
        {
1757
            req->flags       = SET_CURSOR_CLIP;
1758 1759 1760 1761 1762
            req->clip.left   = rect->left;
            req->clip.top    = rect->top;
            req->clip.right  = rect->right;
            req->clip.bottom = rect->bottom;
        }
1763 1764
        else req->flags = SET_CURSOR_NOCLIP;

1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
        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
1776 1777 1778 1779
}


/***********************************************************************
1780
 *		GetClipCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1781
 */
1782
BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
Alexandre Julliard's avatar
Alexandre Julliard committed
1783
{
1784
    BOOL ret;
1785

1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
    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;
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1801 1802
}

1803 1804 1805 1806 1807 1808

/***********************************************************************
 *		SetSystemCursor (USER32.@)
 */
BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
{
1809
    FIXME("(%p,%08x),stub!\n",  hcur, id);
1810 1811 1812 1813
    return TRUE;
}


1814 1815 1816 1817 1818
/**********************************************************************
 *		LookupIconIdFromDirectoryEx (USER32.@)
 */
INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
             INT width, INT height, UINT cFlag )
Alexandre Julliard's avatar
Alexandre Julliard committed
1819
{
1820
    const CURSORICONDIR *dir = (const CURSORICONDIR*)xdir;
1821
    UINT retVal = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
1822 1823
    if( dir && !dir->idReserved && (dir->idType & 3) )
    {
1824
        const CURSORICONDIRENTRY* entry;
1825

1826 1827 1828
        const HDC hdc = GetDC(0);
        const int depth = (cFlag & LR_MONOCHROME) ?
            1 : GetDeviceCaps(hdc, BITSPIXEL);
1829 1830 1831
        ReleaseDC(0, hdc);

        if( bIcon )
1832
            entry = CURSORICON_FindBestIconRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
1833
        else
1834
            entry = CURSORICON_FindBestCursorRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
1835

1836
        if( entry ) retVal = entry->wResId;
Alexandre Julliard's avatar
Alexandre Julliard committed
1837
    }
1838
    else WARN_(cursor)("invalid resource directory\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
1839 1840 1841
    return retVal;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1842
/**********************************************************************
1843
 *              LookupIconIdFromDirectory (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1844
 */
1845
INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1846
{
1847
    return LookupIconIdFromDirectoryEx( dir, bIcon, 0, 0, bIcon ? 0 : LR_MONOCHROME );
Alexandre Julliard's avatar
Alexandre Julliard committed
1848 1849
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1850
/***********************************************************************
1851
 *              LoadCursorW (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1852
 */
1853
HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1854
{
1855 1856
    TRACE("%p, %s\n", hInstance, debugstr_w(name));

1857
    return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1858
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1859 1860 1861
}

/***********************************************************************
1862
 *		LoadCursorA (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1863
 */
1864
HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1865
{
1866 1867
    TRACE("%p, %s\n", hInstance, debugstr_a(name));

1868
    return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1869
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1870
}
1871

Alexandre Julliard's avatar
Alexandre Julliard committed
1872
/***********************************************************************
1873 1874
 *		LoadCursorFromFileW (USER32.@)
 */
1875
HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1876
{
1877 1878
    TRACE("%s\n", debugstr_w(name));

1879
    return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1880
                       LR_LOADFROMFILE | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1881
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1882

Alexandre Julliard's avatar
Alexandre Julliard committed
1883
/***********************************************************************
1884 1885
 *		LoadCursorFromFileA (USER32.@)
 */
1886
HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1887
{
1888 1889
    TRACE("%s\n", debugstr_a(name));

1890
    return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1891
                       LR_LOADFROMFILE | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1892
}
1893

Alexandre Julliard's avatar
Alexandre Julliard committed
1894
/***********************************************************************
1895
 *		LoadIconW (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1896
 */
1897
HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1898
{
1899 1900
    TRACE("%p, %s\n", hInstance, debugstr_w(name));

1901
    return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1902
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1903 1904 1905
}

/***********************************************************************
1906
 *              LoadIconA (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1907
 */
1908
HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1909
{
1910 1911
    TRACE("%p, %s\n", hInstance, debugstr_a(name));

1912
    return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1913
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1914
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1915

1916 1917
/**********************************************************************
 *              GetCursorFrameInfo (USER32.@)
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
 *
 * 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)
1933
 */
1934
HCURSOR WINAPI GetCursorFrameInfo(HCURSOR hCursor, DWORD reserved, DWORD istep, DWORD *rate_jiffies, DWORD *num_steps)
1935 1936 1937
{
    struct cursoricon_object *ptr;
    HCURSOR ret = 0;
1938
    UINT icon_steps;
1939

1940
    if (rate_jiffies == NULL || num_steps == NULL) return 0;
1941 1942 1943

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

1944 1945 1946
    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);
1947

1948 1949
    icon_steps = get_icon_steps(ptr);
    if (istep < icon_steps || !ptr->is_ani)
1950
    {
1951 1952 1953 1954 1955 1956 1957 1958 1959
        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;
1960
        if (icon_frames == 1)
1961 1962
        {
            *rate_jiffies = 0;
1963
            *num_steps = 1;
1964
        }
1965 1966 1967 1968 1969 1970
        else if (icon_steps == 1)
        {
            *num_steps = ~0;
            *rate_jiffies = ptr->delay;
        }
        else if (istep < icon_steps)
1971
        {
1972 1973
            struct cursoricon_frame *frame;

1974
            *num_steps = icon_steps;
1975
            frame = get_icon_frame( ptr, istep );
1976
            if (get_icon_steps(ptr) == 1)
1977 1978
                *num_steps = ~0;
            else
1979
                *num_steps = get_icon_steps(ptr);
1980
            /* If this specific frame does not have a delay then use the global delay */
1981
            if (frame->delay == ~0)
1982 1983
                *rate_jiffies = ptr->delay;
            else
1984 1985
                *rate_jiffies = frame->delay;
            release_icon_frame( ptr, istep, frame );
1986 1987 1988 1989 1990 1991 1992 1993
        }
    }

    release_icon_ptr( hCursor, ptr );

    return ret;
}

1994
/**********************************************************************
1995
 *              GetIconInfo (USER32.@)
1996
 */
1997 1998
BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
{
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
    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
2010

2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
/**********************************************************************
 *              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;
}
2035

2036 2037 2038 2039 2040
/**********************************************************************
 *              GetIconInfoExW (USER32.@)
 */
BOOL WINAPI GetIconInfoExW( HICON icon, ICONINFOEXW *info )
{
2041
    struct cursoricon_frame *frame;
2042
    struct cursoricon_object *ptr;
2043
    HMODULE module;
2044
    BOOL ret = TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2045

2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
    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
2056

2057 2058 2059 2060 2061 2062 2063 2064 2065
    frame = get_icon_frame( ptr, 0 );
    if (!frame)
    {
        release_icon_ptr( icon, ptr );
        SetLastError( ERROR_INVALID_CURSOR_HANDLE );
        return FALSE;
    }

    TRACE("%p => %dx%d\n", icon, frame->width, frame->height);
2066 2067 2068 2069

    info->fIcon        = ptr->is_icon;
    info->xHotspot     = ptr->hotspot.x;
    info->yHotspot     = ptr->hotspot.y;
2070 2071
    info->hbmColor     = copy_bitmap( frame->color );
    info->hbmMask      = copy_bitmap( frame->mask );
2072 2073 2074 2075 2076 2077 2078 2079
    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 );
    }
2080
    if (!info->hbmMask || (!info->hbmColor && frame->color))
2081 2082 2083 2084 2085
    {
        DeleteObject( info->hbmMask );
        DeleteObject( info->hbmColor );
        ret = FALSE;
    }
2086
    module = ptr->module;
2087
    release_icon_frame( ptr, 0, frame );
2088
    release_icon_ptr( icon, ptr );
2089
    if (ret && module) GetModuleFileNameW( module, info->szModName, MAX_PATH );
2090
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
2091 2092
}

2093 2094 2095 2096 2097 2098 2099
/* 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 );

2100
    if (!SelectObject( hdc, src ))  /* do it the hard way */
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
    {
        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;
2112
        info->bmiHeader.biSizeImage = get_dib_image_size( width, height, info->bmiHeader.biBitCount );
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
        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
2130
/**********************************************************************
2131
 *		CreateIconIndirect (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
2132
 */
2133
HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
2134
{
2135
    BITMAP bmpXor, bmpAnd;
2136
    HICON hObj;
2137
    HBITMAP color = 0, mask;
2138
    int width, height;
2139
    HDC hdc;
Alexandre Julliard's avatar
Alexandre Julliard committed
2140

2141 2142 2143 2144
    TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
           iconinfo->hbmColor, iconinfo->hbmMask,
           iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);

2145 2146
    if (!iconinfo->hbmMask) return 0;

2147 2148 2149 2150 2151
    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);

2152 2153
    if (iconinfo->hbmColor)
    {
2154
        GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2155
        TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2156 2157
               bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
               bmpXor.bmPlanes, bmpXor.bmBitsPixel);
2158

2159 2160
        width = bmpXor.bmWidth;
        height = bmpXor.bmHeight;
2161
        if (bmpXor.bmPlanes * bmpXor.bmBitsPixel != 1 || bmpAnd.bmPlanes * bmpAnd.bmBitsPixel != 1)
2162 2163 2164 2165 2166
        {
            color = CreateCompatibleBitmap( screen_dc, width, height );
            mask = CreateBitmap( width, height, 1, 1, NULL );
        }
        else mask = CreateBitmap( width, height * 2, 1, 1, NULL );
2167
    }
2168 2169 2170 2171 2172 2173 2174
    else
    {
        width = bmpAnd.bmWidth;
        height = bmpAnd.bmHeight;
        mask = CreateBitmap( width, height, 1, 1, NULL );
    }

2175 2176 2177
    hdc = CreateCompatibleDC( 0 );
    SelectObject( hdc, mask );
    stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
2178 2179 2180

    if (color)
    {
2181 2182
        SelectObject( hdc, color );
        stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
2183 2184 2185
    }
    else if (iconinfo->hbmColor)
    {
2186
        stretch_blt_icon( hdc, 0, height, width, height, iconinfo->hbmColor, width, height );
2187
    }
2188 2189
    else height /= 2;

2190
    DeleteDC( hdc );
Alexandre Julliard's avatar
Alexandre Julliard committed
2191

2192
    hObj = alloc_icon_handle( FALSE, 1 );
Alexandre Julliard's avatar
Alexandre Julliard committed
2193 2194
    if (hObj)
    {
2195
        struct cursoricon_object *info = get_icon_ptr( hObj );
2196
        struct cursoricon_frame *frame;
2197

2198
        info->is_icon = iconinfo->fIcon;
2199 2200 2201 2202 2203 2204 2205 2206
        frame = get_icon_frame( info, 0 );
        frame->delay  = ~0;
        frame->width  = width;
        frame->height = height;
        frame->color  = color;
        frame->mask   = mask;
        frame->alpha  = create_alpha_bitmap( iconinfo->hbmColor, mask, NULL, NULL );
        release_icon_frame( info, 0, frame );
2207
        if (info->is_icon)
2208
        {
2209 2210
            info->hotspot.x = width / 2;
            info->hotspot.y = height / 2;
2211 2212 2213
        }
        else
        {
2214 2215
            info->hotspot.x = iconinfo->xHotspot;
            info->hotspot.y = iconinfo->yHotspot;
2216 2217
        }

2218
        release_icon_ptr( hObj, info );
Alexandre Julliard's avatar
Alexandre Julliard committed
2219
    }
2220
    return hObj;
Alexandre Julliard's avatar
Alexandre Julliard committed
2221
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2222

Alexandre Julliard's avatar
Alexandre Julliard committed
2223
/******************************************************************************
2224
 *		DrawIconEx (USER32.@) Draws an icon or cursor on device context
Alexandre Julliard's avatar
Alexandre Julliard committed
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
 *
 * 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
 */
2244
BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2245
                            INT cxWidth, INT cyWidth, UINT istep,
2246
                            HBRUSH hbr, UINT flags )
Alexandre Julliard's avatar
Alexandre Julliard committed
2247
{
2248
    struct cursoricon_frame *frame;
2249
    struct cursoricon_object *ptr;
2250
    HDC hdc_dest, hMemDC;
2251
    BOOL result = FALSE, DoOffscreen;
2252 2253 2254
    HBITMAP hB_off = 0;
    COLORREF oldFg, oldBg;
    INT x, y, nStretchMode;
2255

2256 2257
    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
2258

2259
    if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2260
    if (istep >= get_icon_steps( ptr ))
2261
    {
2262
        TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
2263
        release_icon_ptr( hIcon, ptr );
2264 2265
        return FALSE;
    }
2266 2267 2268 2269 2270 2271
    if (!(frame = get_icon_frame( ptr, istep )))
    {
        FIXME_(icon)("Error retrieving icon frame %d\n", istep);
        release_icon_ptr( hIcon, ptr );
        return FALSE;
    }
2272
    if (!(hMemDC = CreateCompatibleDC( hdc )))
2273
    {
2274
        release_icon_frame( ptr, istep, frame );
2275 2276 2277
        release_icon_ptr( hIcon, ptr );
        return FALSE;
    }
2278

2279 2280
    if (flags & DI_NOMIRROR)
        FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
2281

2282 2283
    /* Calculate the size of the destination image.  */
    if (cxWidth == 0)
2284
    {
2285 2286 2287
        if (flags & DI_DEFAULTSIZE)
            cxWidth = GetSystemMetrics (SM_CXICON);
        else
2288
            cxWidth = frame->width;
2289
    }
2290
    if (cyWidth == 0)
2291
    {
2292 2293 2294
        if (flags & DI_DEFAULTSIZE)
            cyWidth = GetSystemMetrics (SM_CYICON);
        else
2295
            cyWidth = frame->height;
2296
    }
2297

2298 2299
    DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);

2300
    if (DoOffscreen) {
2301 2302 2303 2304 2305 2306 2307
        RECT r;

        r.left = 0;
        r.top = 0;
        r.right = cxWidth;
        r.bottom = cxWidth;

2308
        if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
2309 2310 2311
        if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
        {
            DeleteDC( hdc_dest );
2312
            goto failed;
2313
        }
2314 2315 2316
        SelectObject(hdc_dest, hB_off);
        FillRect(hdc_dest, &r, hbr);
        x = y = 0;
2317
    }
2318
    else
Alexandre Julliard's avatar
Alexandre Julliard committed
2319
    {
2320 2321 2322 2323
        hdc_dest = hdc;
        x = x0;
        y = y0;
    }
2324

2325
    nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2326

2327 2328
    oldFg = SetTextColor( hdc, RGB(0,0,0) );
    oldBg = SetBkColor( hdc, RGB(255,255,255) );
2329

2330
    if (frame->alpha && (flags & DI_IMAGE))
2331
    {
2332
        BOOL alpha_blend = TRUE;
2333

2334 2335 2336 2337
        if (GetObjectType( hdc_dest ) == OBJ_MEMDC)
        {
            BITMAP bm;
            HBITMAP bmp = GetCurrentObject( hdc_dest, OBJ_BITMAP );
2338
            alpha_blend = GetObjectW( bmp, sizeof(bm), &bm ) && bm.bmBitsPixel > 8;
2339
        }
2340
        if (alpha_blend)
2341 2342
        {
            BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2343
            SelectObject( hMemDC, frame->alpha );
2344
            if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
2345 2346
                               0, 0, frame->width, frame->height,
                               pixelblend )) goto done;
2347
        }
2348 2349 2350
    }

    if (flags & DI_MASK)
2351
    {
2352
        DWORD rop = (flags & DI_IMAGE) ? SRCAND : SRCCOPY;
2353
        SelectObject( hMemDC, frame->mask );
2354
        StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2355
                    hMemDC, 0, 0, frame->width, frame->height, rop );
2356
    }
2357

2358 2359
    if (flags & DI_IMAGE)
    {
2360
        if (frame->color)
2361 2362
        {
            DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2363
            SelectObject( hMemDC, frame->color );
2364
            StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2365
                        hMemDC, 0, 0, frame->width, frame->height, rop );
2366 2367 2368 2369
        }
        else
        {
            DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2370
            SelectObject( hMemDC, frame->mask );
2371
            StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2372 2373
                        hMemDC, 0, frame->height, frame->width,
                        frame->height, rop );
2374
        }
Alexandre Julliard's avatar
Alexandre Julliard committed
2375
    }
2376

2377
done:
2378 2379 2380 2381 2382 2383 2384
    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 );
2385
    if (hB_off) DeleteObject(hB_off);
2386
failed:
2387
    DeleteDC( hMemDC );
2388
    release_icon_frame( ptr, istep, frame );
2389
    release_icon_ptr( hIcon, ptr );
Alexandre Julliard's avatar
Alexandre Julliard committed
2390 2391
    return result;
}
2392

2393 2394 2395 2396 2397 2398 2399 2400
/***********************************************************************
 *           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)
{
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
    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);
2455
    }
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
    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);
            }
        }
2474 2475 2476
}


2477 2478 2479
/**********************************************************************
 *       BITMAP_Load
 */
2480 2481
static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
                            INT desiredx, INT desiredy, UINT loadflags )
2482
{
2483
    HBITMAP hbitmap = 0, orig_bm;
2484 2485
    HRSRC hRsrc;
    HGLOBAL handle;
2486
    const char *ptr = NULL;
2487
    BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2488
    int size;
2489 2490 2491 2492
    BYTE pix;
    char *bits;
    LONG width, height, new_width, new_height;
    WORD bpp_dummy;
2493
    DWORD compr_dummy, offbits = 0;
2494 2495
    INT bm_type;
    HDC screen_mem_dc = NULL;
2496

2497 2498
    if (!(loadflags & LR_LOADFROMFILE))
    {
2499 2500 2501 2502 2503
        if (!instance)
        {
            /* OEM bitmap: try to load the resource from user32.dll */
            instance = user32_module;
        }
2504

2505 2506
        if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
        if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2507

2508
        if ((info = LockResource( handle )) == NULL) return 0;
2509 2510 2511
    }
    else
    {
2512 2513
        BITMAPFILEHEADER * bmfh;

2514
        if (!(ptr = map_fileW( name, NULL ))) return 0;
2515
        info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2516
        bmfh = (BITMAPFILEHEADER *)ptr;
2517
        if (bmfh->bfType != 0x4d42 /* 'BM' */)
2518 2519
        {
            WARN("Invalid/unsupported bitmap format!\n");
2520
            goto end;
2521
        }
2522
        if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2523
    }
2524

2525 2526 2527 2528 2529 2530 2531 2532
    bm_type = DIB_GetBitmapInfo( &info->bmiHeader, &width, &height,
                                 &bpp_dummy, &compr_dummy);
    if (bm_type == -1)
    {
        WARN("Invalid bitmap format!\n");
        goto end;
    }

2533
    size = bitmap_info_size(info, DIB_RGB_COLORS);
2534 2535
    fix_info = HeapAlloc(GetProcessHeap(), 0, size);
    scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2536

2537 2538
    if (!fix_info || !scaled_info) goto end;
    memcpy(fix_info, info, size);
2539

2540 2541
    pix = *((LPBYTE)info + size);
    DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2542

2543
    memcpy(scaled_info, fix_info, size);
2544

2545 2546 2547 2548
    if(desiredx != 0)
        new_width = desiredx;
    else
        new_width = width;
2549

2550 2551 2552 2553
    if(desiredy != 0)
        new_height = height > 0 ? desiredy : -desiredy;
    else
        new_height = height;
2554

2555 2556 2557 2558 2559 2560 2561 2562
    if(bm_type == 0)
    {
        BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
        core->bcWidth = new_width;
        core->bcHeight = new_height;
    }
    else
    {
2563 2564 2565 2566 2567 2568
        /* Some sanity checks for BITMAPINFO (not applicable to BITMAPCOREINFO) */
        if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
            WARN("Broken BitmapInfoHeader!\n");
            goto end;
        }

2569 2570 2571 2572 2573 2574 2575 2576 2577
        scaled_info->bmiHeader.biWidth = new_width;
        scaled_info->bmiHeader.biHeight = new_height;
    }

    if (new_height < 0) new_height = -new_height;

    if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
    if (!(screen_mem_dc = CreateCompatibleDC( screen_dc ))) goto end;

2578
    bits = (char *)info + (offbits ? offbits : size);
2579

2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
    if (loadflags & LR_CREATEDIBSECTION)
    {
        scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
        hbitmap = CreateDIBSection(screen_dc, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
    }
    else
    {
        if (is_dib_monochrome(fix_info))
            hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
        else
            hbitmap = CreateCompatibleBitmap(screen_dc, new_width, new_height);        
2591
    }
2592

2593 2594 2595 2596 2597 2598 2599 2600
    orig_bm = SelectObject(screen_mem_dc, hbitmap);
    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);
2601
    if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2602

2603 2604 2605 2606
    return hbitmap;
}

/**********************************************************************
2607
 *		LoadImageA (USER32.@)
2608
 *
2609
 * See LoadImageW.
2610 2611 2612 2613 2614 2615 2616
 */
HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
                              INT desiredx, INT desiredy, UINT loadflags)
{
    HANDLE res;
    LPWSTR u_name;

2617
    if (IS_INTRESOURCE(name))
2618
        return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2619

2620
    __TRY {
2621 2622 2623
        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 );
2624
    }
2625
    __EXCEPT_PAGE_FAULT {
2626 2627
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
2628 2629
    }
    __ENDTRY
2630
    res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2631
    HeapFree(GetProcessHeap(), 0, u_name);
2632 2633 2634 2635 2636
    return res;
}


/******************************************************************************
2637
 *		LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650
 *
 * 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
 *
2651
 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2652 2653 2654 2655
 */
HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
                INT desiredx, INT desiredy, UINT loadflags )
{
2656 2657
    int depth;

2658 2659 2660
    TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
                     hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);

2661 2662 2663
    if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
    switch (type) {
    case IMAGE_BITMAP:
2664
        return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2665 2666

    case IMAGE_ICON:
2667 2668 2669
    case IMAGE_CURSOR:
        depth = 1;
        if (!(loadflags & LR_MONOCHROME))
2670
        {
2671 2672
            if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
            if (screen_dc) depth = GetDeviceCaps( screen_dc, BITSPIXEL );
2673
        }
2674
        return CURSORICON_Load(hinst, name, desiredx, desiredy, depth, (type == IMAGE_CURSOR), loadflags);
2675 2676 2677 2678 2679
    }
    return 0;
}

/******************************************************************************
2680
 *		CopyImage (USER32.@) Creates new image and copies attributes to it
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
 *
 * 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
 *
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
 * 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.
2705
 */
2706
HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2707 2708
                             INT desiredy, UINT flags )
{
2709 2710 2711
    TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
          hnd, type, desiredx, desiredy, flags);

2712 2713
    switch (type)
    {
2714
        case IMAGE_BITMAP:
2715
        {
2716 2717 2718 2719
            HBITMAP res = NULL;
            DIBSECTION ds;
            int objSize;
            BITMAPINFO * bi;
2720

2721 2722 2723 2724 2725
            objSize = GetObjectW( hnd, sizeof(ds), &ds );
            if (!objSize) return 0;
            if ((desiredx < 0) || (desiredy < 0)) return 0;

            if (flags & LR_COPYFROMRESOURCE)
2726
            {
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
                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;
2760 2761 2762

                /* Get the color table or the color masks */
                GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777

                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);
2778 2779
                    bi->bmiHeader.biWidth  = ds.dsBm.bmWidth;
                    bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 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 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
                    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
                {
                    HDC screenDC = GetDC(NULL);
                    res = CreateCompatibleBitmap(screenDC, desiredx, desiredy);
                    ReleaseDC(NULL, screenDC);
                }
            }

            if (res)
            {
                /* Only copy the bitmap if it's a DIB section or if it's
                   compatible to the screen */
                BOOL copyContents;

                if (objSize == sizeof(DIBSECTION))
                {
                    copyContents = TRUE;
                }
                else
                {
                    HDC screenDC = GetDC(NULL);
                    int screen_depth = GetDeviceCaps(screenDC, BITSPIXEL);
                    ReleaseDC(NULL, screenDC);

                    copyContents = (ds.dsBm.bmBitsPixel == 1 || ds.dsBm.bmBitsPixel == screen_depth);
                }

                if (copyContents)
                {
                    /* The source bitmap may already be selected in a device context,
                       use GetDIBits/StretchDIBits and not StretchBlt  */

                    HDC dc;
                    void * bits;

                    dc = CreateCompatibleDC(NULL);

                    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);
                }
2887
            }
2888
            HeapFree(GetProcessHeap(), 0, bi);
2889
            return res;
2890
        }
2891 2892
        case IMAGE_ICON:
        case IMAGE_CURSOR:
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
        {
            struct cursoricon_object *icon;
            HICON res = 0;
            int depth = (flags & LR_MONOCHROME) ? 1 : GetDeviceCaps( screen_dc, BITSPIXEL );

            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;

2906
            if (icon->rsrc && (flags & LR_COPYFROMRESOURCE))
2907
                res = CURSORICON_Load( icon->module, icon->resname, desiredx, desiredy, depth,
2908
                                       !icon->is_icon, flags );
2909 2910 2911 2912 2913 2914 2915
            else
                res = CopyIcon( hnd ); /* FIXME: change size if necessary */
            release_icon_ptr( hnd, icon );

            if (res && (flags & LR_COPYDELETEORG)) DeleteObject( hnd );
            return res;
        }
2916 2917 2918 2919 2920 2921
    }
    return 0;
}


/******************************************************************************
2922
 *		LoadBitmapW (USER32.@) Loads bitmap from the executable file
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935
 *
 * 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 );
}

/**********************************************************************
2936
 *		LoadBitmapA (USER32.@)
2937 2938
 *
 * See LoadBitmapW.
2939 2940 2941 2942 2943
 */
HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
{
    return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );
}