cursoricon.c 93.2 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
static struct list icon_cache = LIST_INIT( icon_cache );
52

53 54 55 56
/**********************************************************************
 * User objects management
 */

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

struct cursoricon_object
{
69
    struct user_object      obj;        /* object header */
70
    struct list             entry;      /* entry in shared icons list */
71
    ULONG_PTR               param;      /* opaque param used by 16-bit code */
72 73
    HMODULE                 module;     /* module for icons loaded from resources */
    LPWSTR                  resname;    /* resource name for icons loaded from resources */
74
    HRSRC                   rsrc;       /* resource for shared icons */
75
    BOOL                    is_icon;    /* whether icon or cursor */
76 77
    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) */
78
    POINT                   hotspot;
79 80
};

81
struct static_cursoricon_object
82
{
83 84 85 86 87 88 89 90 91 92 93 94
    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 */
};

95 96 97 98 99 100 101 102 103 104 105
static HDC get_screen_dc(void)
{
    static const WCHAR DISPLAYW[] = {'D','I','S','P','L','A','Y',0};
    static HDC screen_dc;

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

    return screen_dc;
}

106
static HICON alloc_icon_handle( BOOL is_ani, UINT num_steps )
107 108 109
{
    struct cursoricon_object *obj;
    int icon_size;
110
    HICON handle;
111 112

    if (is_ani)
113
        icon_size = FIELD_OFFSET( struct animated_cursoricon_object, frames[num_steps] );
114 115 116
    else
        icon_size = sizeof( struct static_cursoricon_object );
    obj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, icon_size );
117
    if (!obj) return NULL;
118

119
    obj->delay = 0;
120 121 122 123 124
    obj->is_ani = is_ani;
    if (is_ani)
    {
        struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;

125 126
        ani_icon_data->num_steps = num_steps;
        ani_icon_data->num_frames = num_steps; /* changed later for some animated cursors */
127
    }
128 129 130 131

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

134
static struct cursoricon_object *get_icon_ptr( HICON handle )
135 136 137 138 139 140 141
{
    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;
    }
142
    return obj;
143 144
}

145 146
static struct cursoricon_frame *get_icon_frame( struct cursoricon_object *obj, int istep )
{
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    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;
163 164
}

165
static void release_icon_frame( struct cursoricon_object *obj, struct cursoricon_frame *frame )
166
{
167 168 169 170 171
    if (obj->is_ani)
    {
        struct cursoricon_object *frameobj;

        frameobj = (struct cursoricon_object *) (((char *)frame) - FIELD_OFFSET(struct static_cursoricon_object, frame));
172
        release_user_handle_ptr( frameobj );
173
    }
174 175
}

176 177
static UINT get_icon_steps( struct cursoricon_object *obj )
{
178 179 180 181 182 183 184 185
    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;
186 187
}

188 189 190 191 192 193 194 195
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;
196 197
        UINT i;

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

200
        if (!obj->is_ani)
201
        {
202
            struct cursoricon_frame *frame = get_icon_frame( obj, 0 );
203 204 205 206

            if (frame->alpha) DeleteObject( frame->alpha );
            if (frame->color) DeleteObject( frame->color );
            DeleteObject( frame->mask );
207
            release_icon_frame( obj, frame );
208
        }
209 210 211 212
        else
        {
            struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            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;
                    }
                }
            }
229
        }
230
        if (!IS_INTRESOURCE( obj->resname )) HeapFree( GetProcessHeap(), 0, obj->resname );
231 232
        HeapFree( GetProcessHeap(), 0, obj );
        if (wow_handlers.free_icon_param && param) wow_handlers.free_icon_param( param );
233
        USER_Driver->pDestroyCursorIcon( handle );
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        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;
}


269 270 271 272
/***********************************************************************
 *             map_fileW
 *
 * Helper function to map a file to memory:
273
 *  name			-	file name
274
 *  [RETURN] ptr		-	pointer to mapped file
275
 *  [RETURN] filesize           -       pointer size of file to be stored if not NULL
276
 */
277
static const void *map_fileW( LPCWSTR name, LPDWORD filesize )
278 279 280 281 282 283 284 285
{
    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)
    {
286
        hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
287 288 289 290
        if (hMapping)
        {
            ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
            CloseHandle( hMapping );
291 292
            if (filesize)
                *filesize = GetFileSize( hFile, NULL );
293
        }
294
        CloseHandle( hFile );
295 296 297 298 299
    }
    return ptr;
}


300
/***********************************************************************
301
 *          get_dib_image_size
302
 *
303
 * Return the size of a DIB bitmap in bytes.
304
 */
305
static int get_dib_image_size( int width, int height, int depth )
306
{
307
    return (((width * depth + 31) / 8) & ~3) * abs( height );
308 309 310 311 312 313 314 315
}


/***********************************************************************
 *           bitmap_info_size
 *
 * Return the size of the bitmap info structure including color table.
 */
316
int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
317
{
318
    unsigned int colors, size, masks = 0;
319 320 321

    if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
    {
322
        const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
323 324 325 326 327 328 329
        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;
330 331
        if (colors > 256) /* buffer overflow otherwise */
                colors = 256;
332 333
        if (!colors && (info->bmiHeader.biBitCount <= 8))
            colors = 1 << info->bmiHeader.biBitCount;
334
        if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
335 336
        size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
        return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
337 338 339 340
    }
}


341 342 343 344 345 346 347
/***********************************************************************
 *             copy_bitmap
 *
 * Helper function to duplicate a bitmap.
 */
static HBITMAP copy_bitmap( HBITMAP bitmap )
{
348 349
    HDC src, dst = 0;
    HBITMAP new_bitmap = 0;
350 351 352 353 354
    BITMAP bmp;

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

355 356 357 358 359 360 361 362 363
    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 );
        }
    }
364 365 366 367 368 369
    DeleteDC( dst );
    DeleteDC( src );
    return new_bitmap;
}


370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
/***********************************************************************
 *          is_dib_monochrome
 *
 * Returns whether a DIB can be converted to a monochrome DDB.
 *
 * A DIB can be converted if its color table contains only black and
 * white. Black must be the first color in the color table.
 *
 * Note : If the first color in the color table is white followed by
 *        black, we can't convert it to a monochrome DDB with
 *        SetDIBits, because black and white would be inverted.
 */
static BOOL is_dib_monochrome( const BITMAPINFO* info )
{
    if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
    {
386
        const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
387

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

390 391 392 393 394 395 396 397 398 399 400 401 402
        /* 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
403
        const RGBQUAD *rgb = info->bmiColors;
404

405 406
        if (info->bmiHeader.biBitCount != 1) return FALSE;

407 408 409 410 411 412 413 414 415 416 417 418 419 420
        /* 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;
    }
}

421 422 423 424
/***********************************************************************
 *           DIB_GetBitmapInfo
 *
 * Get the info from a bitmap header.
425
 * Return 1 for INFOHEADER, 0 for COREHEADER, -1 in case of failure.
426 427 428 429 430 431
 */
static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
                              LONG *height, WORD *bpp, DWORD *compr )
{
    if (header->biSize == sizeof(BITMAPCOREHEADER))
    {
432
        const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
433 434 435 436 437 438
        *width  = core->bcWidth;
        *height = core->bcHeight;
        *bpp    = core->bcBitCount;
        *compr  = 0;
        return 0;
    }
439 440 441
    else if (header->biSize == sizeof(BITMAPINFOHEADER) ||
             header->biSize == sizeof(BITMAPV4HEADER) ||
             header->biSize == sizeof(BITMAPV5HEADER))
442
    {
443 444 445 446 447
        *width  = header->biWidth;
        *height = header->biHeight;
        *bpp    = header->biBitCount;
        *compr  = header->biCompression;
        return 1;
448
    }
449
    WARN("unknown/wrong size (%u) for header\n", header->biSize);
450 451
    return -1;
}
452

453 454 455 456 457
/**********************************************************************
 *              get_icon_size
 */
BOOL get_icon_size( HICON handle, SIZE *size )
{
458
    struct cursoricon_object *info;
459
    struct cursoricon_frame *frame;
460

461
    if (!(info = get_icon_ptr( handle ))) return FALSE;
462 463 464
    frame = get_icon_frame( info, 0 );
    size->cx = frame->width;
    size->cy = frame->height;
465
    release_icon_frame( info, frame);
466
    release_user_handle_ptr( info );
467 468 469
    return TRUE;
}

470 471 472 473
/*
 *  The following macro functions account for the irregularities of
 *   accessing cursor and icon resources in files and resource entries.
 */
474
typedef BOOL (*fnGetCIEntry)( LPCVOID dir, DWORD size, int n,
475 476
                              int *width, int *height, int *bits );

Alexandre Julliard's avatar
Alexandre Julliard committed
477 478 479
/**********************************************************************
 *	    CURSORICON_FindBestIcon
 *
480
 * Find the icon closest to the requested size and bit depth.
Alexandre Julliard's avatar
Alexandre Julliard committed
481
 */
482
static int CURSORICON_FindBestIcon( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
483
                                    int width, int height, int depth, UINT loadflags )
Alexandre Julliard's avatar
Alexandre Julliard committed
484
{
485
    int i, cx, cy, bits, bestEntry = -1;
486 487
    UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
    UINT iTempXDiff, iTempYDiff, iTempColorDiff;
Alexandre Julliard's avatar
Alexandre Julliard committed
488

489 490 491
    /* Find Best Fit */
    iTotalDiff = 0xFFFFFFFF;
    iColorDiff = 0xFFFFFFFF;
492 493 494 495 496 497 498 499 500

    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 */
501
        if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
502 503 504
        iTotalDiff = 0;
    }

505
    for ( i = 0; iTotalDiff && get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
506
    {
507 508
        iTempXDiff = abs(width - cx);
        iTempYDiff = abs(height - cy);
Alexandre Julliard's avatar
Alexandre Julliard committed
509

510
        if(iTotalDiff > (iTempXDiff + iTempYDiff))
Alexandre Julliard's avatar
Alexandre Julliard committed
511
        {
512 513
            iXDiff = iTempXDiff;
            iYDiff = iTempYDiff;
514
            iTotalDiff = iXDiff + iYDiff;
Alexandre Julliard's avatar
Alexandre Julliard committed
515
        }
516
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
517

518
    /* Find Best Colors for Best Fit */
519
    for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
520
    {
521
        if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
Alexandre Julliard's avatar
Alexandre Julliard committed
522
        {
523
            iTempColorDiff = abs(depth - bits);
524
            if(iColorDiff > iTempColorDiff)
525
            {
526
                bestEntry = i;
527
                iColorDiff = iTempColorDiff;
528
            }
529 530
        }
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
531 532 533 534

    return bestEntry;
}

535
static BOOL CURSORICON_GetResIconEntry( LPCVOID dir, DWORD size, int n,
536 537
                                        int *width, int *height, int *bits )
{
538 539
    const CURSORICONDIR *resdir = dir;
    const ICONRESDIR *icon;
540 541 542

    if ( resdir->idCount <= n )
        return FALSE;
543 544
    if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
        return FALSE;
545 546
    icon = &resdir->idEntries[n].ResInfo.icon;
    *width = icon->bWidth;
547
    *height = icon->bHeight;
548 549 550
    *bits = resdir->idEntries[n].wBitCount;
    return TRUE;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
551 552 553 554 555

/**********************************************************************
 *	    CURSORICON_FindBestCursor
 *
 * Find the cursor closest to the requested size.
556 557
 *
 * FIXME: parameter 'color' ignored.
Alexandre Julliard's avatar
Alexandre Julliard committed
558
 */
559
static int CURSORICON_FindBestCursor( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
560
                                      int width, int height, int depth, UINT loadflags )
Alexandre Julliard's avatar
Alexandre Julliard committed
561
{
562
    int i, maxwidth, maxheight, maxbits, cx, cy, bits, bestEntry = -1;
Alexandre Julliard's avatar
Alexandre Julliard committed
563

564 565 566 567 568 569 570 571
    if (loadflags & LR_DEFAULTSIZE)
    {
        if (!width) width = GetSystemMetrics( SM_CXCURSOR );
        if (!height) height = GetSystemMetrics( SM_CYCURSOR );
    }
    else if (!width && !height)
    {
        /* use the first entry */
572
        if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
573 574 575
        return 0;
    }

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

578
    maxwidth = maxheight = maxbits = 0;
579
    for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
580
    {
581 582
        if (cx > width || cy > height) continue;
        if (cx < maxwidth || cy < maxheight) continue;
583
        if (cx == maxwidth && cy == maxheight)
Alexandre Julliard's avatar
Alexandre Julliard committed
584
        {
585 586 587 588 589
            if (loadflags & LR_MONOCHROME)
            {
                if (maxbits && bits >= maxbits) continue;
            }
            else if (bits <= maxbits) continue;
Alexandre Julliard's avatar
Alexandre Julliard committed
590
        }
591 592 593 594
        bestEntry = i;
        maxwidth  = cx;
        maxheight = cy;
        maxbits = bits;
595 596
    }
    if (bestEntry != -1) return bestEntry;
Alexandre Julliard's avatar
Alexandre Julliard committed
597 598 599 600

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

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

    return bestEntry;
}

622
static BOOL CURSORICON_GetResCursorEntry( LPCVOID dir, DWORD size, int n,
623 624
                                          int *width, int *height, int *bits )
{
625 626
    const CURSORICONDIR *resdir = dir;
    const CURSORDIR *cursor;
627 628 629

    if ( resdir->idCount <= n )
        return FALSE;
630 631
    if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
        return FALSE;
632 633 634 635
    cursor = &resdir->idEntries[n].ResInfo.cursor;
    *width = cursor->wWidth;
    *height = cursor->wHeight;
    *bits = resdir->idEntries[n].wBitCount;
636
    if (*height == *width * 2) *height /= 2;
637 638 639
    return TRUE;
}

640
static const CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( const CURSORICONDIR * dir, DWORD size,
641 642
                                                             int width, int height, int depth,
                                                             UINT loadflags )
643 644 645
{
    int n;

646
    n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetResIconEntry,
647
                                 width, height, depth, loadflags );
648 649 650 651 652
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

653
static const CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( const CURSORICONDIR *dir, DWORD size,
654 655
                                                               int width, int height, int depth,
                                                               UINT loadflags )
656
{
657
    int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetResCursorEntry,
658
                                       width, height, depth, loadflags );
659 660 661 662 663
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

664
static BOOL CURSORICON_GetFileEntry( LPCVOID dir, DWORD size, int n,
665
                                     int *width, int *height, int *bits )
666
{
667 668 669
    const CURSORICONFILEDIR *filedir = dir;
    const CURSORICONFILEDIRENTRY *entry;
    const BITMAPINFOHEADER *info;
670

671 672
    if ( filedir->idCount <= n )
        return FALSE;
673 674
    if ((const char *)&filedir->idEntries[n + 1] - (const char *)dir > size)
        return FALSE;
675
    entry = &filedir->idEntries[n];
676
    info = (const BITMAPINFOHEADER *)((const char *)dir + entry->dwDIBOffset);
677 678 679 680 681 682 683 684 685 686 687
    if (info->biSize != sizeof(BITMAPCOREHEADER))
    {
        if ((const char *)(info + 1) - (const char *)dir > size) return FALSE;
        *bits = info->biBitCount;
    }
    else
    {
        const BITMAPCOREHEADER *coreinfo = (const BITMAPCOREHEADER *)((const char *)dir + entry->dwDIBOffset);
        if ((const char *)(coreinfo + 1) - (const char *)dir > size) return FALSE;
        *bits = coreinfo->bcBitCount;
    }
688 689
    *width = entry->bWidth;
    *height = entry->bHeight;
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
/***********************************************************************
 *          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.
 */
735
static HBITMAP create_alpha_bitmap( HBITMAP color, const BITMAPINFO *src_info, const void *color_bits )
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
{
    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;
}


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

820 821
    /* Check bitmap header */

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

    size = bitmap_info_size( bmi, DIB_RGB_COLORS );
842 843 844 845
    DIB_GetBitmapInfo(&bmi->bmiHeader, &bmi_width, &bmi_height, &bpp, &compr);
    color_size = get_dib_image_size( bmi_width, bmi_height / 2,
                                     bpp );
    mask_size = get_dib_image_size( bmi_width, bmi_height / 2, 1 );
846 847 848 849
    if (size > maxsize || color_size > maxsize - size)
    {
        WARN( "truncated file %u < %u+%u+%u\n", maxsize, size, color_size, mask_size );
        return 0;
850
    }
851
    if (mask_size > maxsize - size - color_size) mask_size = 0;  /* no mask */
852 853 854 855 856 857 858 859

    if (cFlag & LR_DEFAULTSIZE)
    {
        if (!width) width = GetSystemMetrics( bIcon ? SM_CXICON : SM_CXCURSOR );
        if (!height) height = GetSystemMetrics( bIcon ? SM_CYICON : SM_CYCURSOR );
    }
    else
    {
860 861
        if (!width) width = bmi_width;
        if (!height) height = bmi_height/2;
862
    }
863 864
    do_stretch = (bmi_height/2 != height) ||
                 (bmi_width != width);
865 866 867 868 869 870 871 872 873

    /* Scale the hotspot */
    if (bIcon)
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
    }
    else if (do_stretch)
    {
874 875
        hotspot.x = (hotspot.x * width) / bmi_width;
        hotspot.y = (hotspot.y * height) / (bmi_height / 2);
876 877
    }

878
    if (!(screen_dc = get_screen_dc())) return 0;
879 880 881

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

884
    memcpy( bmi_copy, bmi, size );
885 886 887 888 889
    if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
        bmi_copy->bmiHeader.biHeight /= 2;
    else
        ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcHeight /= 2;
    bmi_height /= 2;
890

891
    color_bits = (const char*)bmi + size;
892
    mask_bits = (const char*)color_bits + color_size;
893

894
    alpha = 0;
895
    if (is_dib_monochrome( bmi ))
896
    {
897 898
        if (!(mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
        color = 0;
899 900

        /* copy color data into second half of mask bitmap */
901
        SelectObject( hdc, mask );
902
        StretchDIBits( hdc, 0, height, width, height,
903
                       0, 0, bmi_width, bmi_height,
904
                       color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
905 906 907
    }
    else
    {
908 909
        if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
        if (!(color = CreateBitmap( width, height, GetDeviceCaps( screen_dc, PLANES ),
910 911
                                     GetDeviceCaps( screen_dc, BITSPIXEL ), NULL )))
        {
912
            DeleteObject( mask );
913 914
            goto done;
        }
915
        SelectObject( hdc, color );
916
        StretchDIBits( hdc, 0, 0, width, height,
917
                       0, 0, bmi_width, bmi_height,
918
                       color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
919

920
        if (bmi_has_alpha( bmi_copy, color_bits ))
921
            alpha = create_alpha_bitmap( color, bmi_copy, color_bits );
922

923
        /* convert info to monochrome to copy the mask */
924
        if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
925
        {
926
            RGBQUAD *rgb = bmi_copy->bmiColors;
927

928
            bmi_copy->bmiHeader.biBitCount = 1;
929
            bmi_copy->bmiHeader.biClrUsed = bmi_copy->bmiHeader.biClrImportant = 2;
930 931 932 933 934 935
            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
        {
936
            RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)bmi_copy) + 1);
937

938
            ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcBitCount = 1;
939 940 941 942 943
            rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
            rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
        }
    }

944 945 946 947
    if (mask_size)
    {
        SelectObject( hdc, mask );
        StretchDIBits( hdc, 0, 0, width, height,
948
                       0, 0, bmi_width, bmi_height,
949 950
                       mask_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
    }
951 952 953 954
    ret = TRUE;

done:
    DeleteDC( hdc );
955
    HeapFree( GetProcessHeap(), 0, bmi_copy );
956

957
    if (ret)
958
        hObj = alloc_icon_handle( FALSE, 0 );
Alexandre Julliard's avatar
Alexandre Julliard committed
959
    if (hObj)
Alexandre Julliard's avatar
Alexandre Julliard committed
960
    {
961
        struct cursoricon_object *info = get_icon_ptr( hObj );
962
        struct cursoricon_frame *frame;
Alexandre Julliard's avatar
Alexandre Julliard committed
963

964
        info->is_icon = bIcon;
965
        info->module  = module;
966
        info->hotspot = hotspot;
967 968 969 970 971 972 973
        frame = get_icon_frame( info, 0 );
        frame->delay  = ~0;
        frame->width  = width;
        frame->height = height;
        frame->color  = color;
        frame->mask   = mask;
        frame->alpha  = alpha;
974
        release_icon_frame( info, frame );
975 976 977 978 979 980 981
        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) );

982 983 984 985 986
        if (module && (cFlag & LR_SHARED))
        {
            info->rsrc = rsrc;
            list_add_head( &icon_cache, &info->entry );
        }
987
        release_user_handle_ptr( info );
Alexandre Julliard's avatar
Alexandre Julliard committed
988
    }
989 990 991
    else
    {
        DeleteObject( color );
992
        DeleteObject( alpha );
993 994
        DeleteObject( mask );
    }
995
    return hObj;
Alexandre Julliard's avatar
Alexandre Julliard committed
996 997 998
}


999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
/**********************************************************************
 *          .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')
1012
#define ANI_rate_ID RIFF_FOURCC('r', 'a', 't', 'e')
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 1067 1068 1069 1070 1071 1072 1073 1074

#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)
    {
1075 1076
        if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
                || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1077 1078
        {
            ptr += sizeof(DWORD);
1079
            chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1080 1081 1082 1083 1084 1085 1086 1087
            ptr += sizeof(DWORD);
            if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
            chunk->data = ptr;

            return;
        }

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

    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};
1124
    riff_chunk_t rate_chunk = {0};
1125
    riff_chunk_t seq_chunk = {0};
1126
    const unsigned char *icon_chunk;
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    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 );

1147 1148 1149 1150 1151 1152 1153
    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)
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    {
        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;
        }
    }
1167 1168

    riff_find_chunk( ANI_rate_ID, 0, &ACON_chunk, &rate_chunk );
1169
    if (rate_chunk.data)
1170
        frame_rates = (DWORD *) rate_chunk.data;
1171

1172 1173 1174 1175 1176 1177 1178
    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;
    }

1179
    cursor = alloc_icon_handle( TRUE, header.num_steps );
1180
    if (!cursor) return 0;
1181
    frames = HeapAlloc( GetProcessHeap(), 0, sizeof(*frames) * header.num_frames );
1182 1183 1184 1185 1186
    if (!frames)
    {
        free_icon_handle( cursor );
        return 0;
    }
1187

1188
    info = get_icon_ptr( cursor );
1189
    ani_icon_data = (struct animated_cursoricon_object *) info;
1190
    info->is_icon = is_icon;
1191
    ani_icon_data->num_frames = header.num_frames;
1192

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

1196 1197 1198
    icon_chunk = fram_chunk.data;
    icon_data = fram_chunk.data + (2 * sizeof(DWORD));
    for (i=0; i<header.num_frames; i++)
1199
    {
1200 1201
        const DWORD chunk_size = *(const DWORD *)(icon_chunk + sizeof(DWORD));
        const CURSORICONFILEDIRENTRY *entry;
1202
        INT frameWidth, frameHeight;
1203
        const BITMAPINFO *bmi;
1204

1205
        entry = CURSORICON_FindBestIconFile((const CURSORICONFILEDIR *) icon_data,
1206
                                            bits + bits_size - icon_data,
1207
                                            width, height, depth, loadflags );
1208 1209 1210 1211 1212

        info->hotspot.x = entry->xHotspot;
        info->hotspot.y = entry->yHotspot;
        if (!header.width || !header.height)
        {
1213 1214
            frameWidth = entry->bWidth;
            frameHeight = entry->bHeight;
1215
        }
1216
        else
1217 1218 1219 1220
        {
            frameWidth = header.width;
            frameHeight = header.height;
        }
1221

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
        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 );
        }

1232
        if (!frames[i])
1233 1234 1235 1236 1237 1238
        {
            FIXME_(cursor)("failed to convert animated cursor frame.\n");
            error = TRUE;
            if (i == 0)
            {
                FIXME_(cursor)("Completely failed to create animated cursor!\n");
1239
                ani_icon_data->num_frames = 0;
1240
                release_user_handle_ptr( info );
1241
                free_icon_handle( cursor );
1242
                HeapFree( GetProcessHeap(), 0, frames );
1243 1244 1245 1246
                return 0;
            }
            break;
        }
1247

1248 1249 1250 1251
        /* Advance to the next chunk */
        icon_chunk += chunk_size + (2 * sizeof(DWORD));
        icon_data = icon_chunk + (2 * sizeof(DWORD));
    }
1252

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

    /* 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;
1282
        release_icon_frame( info, frame );
1283 1284 1285
    }

    HeapFree( GetProcessHeap(), 0, frames );
1286
    release_user_handle_ptr( info );
1287 1288 1289 1290 1291

    return cursor;
}


1292 1293 1294
/**********************************************************************
 *		CreateIconFromResourceEx (USER32.@)
 *
1295
 * FIXME: Convert to mono when cFlag is LR_MONOCHROME.
1296 1297 1298 1299 1300 1301
 */
HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
                                       BOOL bIcon, DWORD dwVersion,
                                       INT width, INT height,
                                       UINT cFlag )
{
1302
    POINT hotspot;
1303
    const BITMAPINFO *bmi;
1304 1305 1306

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

1309 1310
    if (!bits) return 0;

1311 1312 1313 1314 1315 1316
    if (dwVersion == 0x00020000)
    {
        FIXME_(cursor)("\t2.xx resources are not supported\n");
        return 0;
    }

1317 1318
    /* Check if the resource is an animated icon/cursor */
    if (!memcmp(bits, "RIFF", 4))
1319 1320
        return CURSORICON_CreateIconFromANI( bits, cbSize, width, height,
                                             0 /* default depth */, bIcon, cFlag );
1321

1322
    if (bIcon)
1323 1324 1325
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
1326
        bmi = (BITMAPINFO *)bits;
1327
    }
1328 1329
    else /* get the hotspot */
    {
1330
        const SHORT *pt = (const SHORT *)bits;
1331 1332
        hotspot.x = pt[0];
        hotspot.y = pt[1];
1333
        bmi = (const BITMAPINFO *)(pt + 2);
1334
        cbSize -= 2 * sizeof(*pt);
1335 1336
    }

1337
    return create_icon_from_bmi( bmi, cbSize, NULL, NULL, NULL, hotspot, bIcon, width, height, cFlag );
1338 1339 1340
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1341
/**********************************************************************
1342
 *		CreateIconFromResource (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1343
 */
1344 1345
HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
                                           BOOL bIcon, DWORD dwVersion)
Alexandre Julliard's avatar
Alexandre Julliard committed
1346
{
1347
    return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
Alexandre Julliard's avatar
Alexandre Julliard committed
1348 1349 1350
}


1351
static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1352
                             INT width, INT height, INT depth,
1353 1354
                             BOOL fCursor, UINT loadflags)
{
1355 1356
    const CURSORICONFILEDIRENTRY *entry;
    const CURSORICONFILEDIR *dir;
1357 1358
    DWORD filesize = 0;
    HICON hIcon = 0;
1359
    const BYTE *bits;
1360
    POINT hotspot;
1361 1362 1363 1364 1365 1366 1367

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

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

1368 1369 1370
    /* Check for .ani. */
    if (memcmp( bits, "RIFF", 4 ) == 0)
    {
1371
        hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height, depth, !fCursor, loadflags );
1372 1373 1374
        goto end;
    }

1375
    dir = (const CURSORICONFILEDIR*) bits;
1376
    if ( filesize < FIELD_OFFSET( CURSORICONFILEDIR, idEntries[dir->idCount] ))
1377 1378 1379
        goto end;

    if ( fCursor )
1380
        entry = CURSORICON_FindBestCursorFile( dir, filesize, width, height, depth, loadflags );
1381
    else
1382
        entry = CURSORICON_FindBestIconFile( dir, filesize, width, height, depth, loadflags );
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392

    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;

1393 1394
    hotspot.x = entry->xHotspot;
    hotspot.y = entry->yHotspot;
1395
    hIcon = create_icon_from_bmi( (const BITMAPINFO *)&bits[entry->dwDIBOffset], filesize - entry->dwDIBOffset,
1396
                                  NULL, NULL, NULL, hotspot, !fCursor, width, height, loadflags );
1397 1398 1399 1400 1401 1402
end:
    TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
    UnmapViewOfFile( bits );
    return hIcon;
}

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

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

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

1428
    if (!hInstance) hInstance = user32_module;  /* Load OEM cursor/icon */
1429

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

1433
    /* Get directory resource ID */
Alexandre Julliard's avatar
Alexandre Julliard committed
1434

1435 1436
    if (!(hRsrc = FindResourceW( hInstance, name,
                                 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1437 1438 1439 1440 1441 1442 1443 1444 1445
    {
        /* 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
1446

1447
    /* Find the best entry in the directory */
1448

1449
    if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1450
    if (!(dir = LockResource( handle ))) return 0;
1451
    size = SizeofResource( hInstance, hRsrc );
1452
    if (fCursor)
1453
        dirEntry = CURSORICON_FindBestCursorRes( dir, size, width, height, depth, loadflags );
1454
    else
1455
        dirEntry = CURSORICON_FindBestIconRes( dir, size, width, height, depth, loadflags );
1456 1457 1458
    if (!dirEntry) return 0;
    wResId = dirEntry->wResId;
    FreeResource( handle );
1459

1460
    /* Load the resource */
1461

1462 1463
    if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
                                (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1464

1465
    /* If shared icon, check whether it was already loaded */
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
    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;
    }
1481

1482
    if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1483
    size = SizeofResource( hInstance, hRsrc );
1484
    bits = LockResource( handle );
1485 1486 1487 1488 1489 1490 1491 1492

    if (!fCursor)
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
    }
    else /* get the hotspot */
    {
1493
        const SHORT *pt = (const SHORT *)bits;
1494 1495 1496
        hotspot.x = pt[0];
        hotspot.y = pt[1];
        bits += 2 * sizeof(SHORT);
1497
        size -= 2 * sizeof(SHORT);
1498
    }
1499
    hIcon = create_icon_from_bmi( (const BITMAPINFO *)bits, size, hInstance, name, hRsrc,
1500
                                  hotspot, !fCursor, width, height, loadflags );
1501
    FreeResource( handle );
1502
    return hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1503 1504
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1505

Alexandre Julliard's avatar
Alexandre Julliard committed
1506
/***********************************************************************
1507
 *		CreateCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1508
 */
1509 1510 1511
HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
                                 INT xHotSpot, INT yHotSpot,
                                 INT nWidth, INT nHeight,
Alexandre Julliard's avatar
Alexandre Julliard committed
1512
                                 LPCVOID lpANDbits, LPCVOID lpXORbits )
Alexandre Julliard's avatar
Alexandre Julliard committed
1513
{
1514 1515
    ICONINFO info;
    HCURSOR hCursor;
Alexandre Julliard's avatar
Alexandre Julliard committed
1516

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

1520 1521 1522 1523 1524 1525 1526 1527 1528
    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
1529 1530 1531
}


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

1563 1564
    TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
                 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1565

1566
    iinfo.fIcon = TRUE;
1567 1568
    iinfo.xHotspot = nWidth / 2;
    iinfo.yHotspot = nHeight / 2;
1569 1570 1571 1572 1573 1574 1575
    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 );
1576 1577

    return hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1578 1579 1580 1581
}


/***********************************************************************
1582
 *		CopyIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1583
 */
1584
HICON WINAPI CopyIcon( HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1585
{
1586
    struct cursoricon_object *ptrOld, *ptrNew;
1587
    HICON hNew;
1588

1589 1590 1591 1592 1593
    if (!(ptrOld = get_icon_ptr( hIcon )))
    {
        SetLastError( ERROR_INVALID_CURSOR_HANDLE );
        return 0;
    }
1594
    if ((hNew = alloc_icon_handle( FALSE, 0 )))
1595
    {
1596 1597
        struct cursoricon_frame *frameOld, *frameNew;

1598
        ptrNew = get_icon_ptr( hNew );
1599 1600
        ptrNew->is_icon = ptrOld->is_icon;
        ptrNew->hotspot = ptrOld->hotspot;
1601 1602
        if (!(frameOld = get_icon_frame( ptrOld, 0 )))
        {
1603
            release_user_handle_ptr( ptrOld );
1604 1605 1606 1607 1608
            SetLastError( ERROR_INVALID_CURSOR_HANDLE );
            return 0;
        }
        if (!(frameNew = get_icon_frame( ptrNew, 0 )))
        {
1609
            release_icon_frame( ptrOld, frameOld );
1610
            release_user_handle_ptr( ptrOld );
1611 1612 1613 1614 1615 1616 1617 1618 1619
            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 );
1620 1621
        release_icon_frame( ptrOld, frameOld );
        release_icon_frame( ptrNew, frameNew );
1622
        release_user_handle_ptr( ptrNew );
1623
    }
1624
    release_user_handle_ptr( ptrOld );
1625
    return hNew;
Alexandre Julliard's avatar
Alexandre Julliard committed
1626
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1627 1628


Alexandre Julliard's avatar
Alexandre Julliard committed
1629
/***********************************************************************
1630
 *		DestroyIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1631
 */
1632
BOOL WINAPI DestroyIcon( HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1633
{
1634 1635 1636
    BOOL ret = FALSE;
    struct cursoricon_object *obj = get_icon_ptr( hIcon );

1637 1638
    TRACE_(icon)("%p\n", hIcon );

1639 1640 1641
    if (obj)
    {
        BOOL shared = (obj->rsrc != NULL);
1642
        release_user_handle_ptr( obj );
1643 1644 1645 1646
        ret = (GetCursor() != hIcon);
        if (!shared) free_icon_handle( hIcon );
    }
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1647 1648
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1649 1650

/***********************************************************************
1651
 *		DestroyCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1652
 */
1653
BOOL WINAPI DestroyCursor( HCURSOR hCursor )
Alexandre Julliard's avatar
Alexandre Julliard committed
1654
{
1655
    return DestroyIcon( hCursor );
Alexandre Julliard's avatar
Alexandre Julliard committed
1656 1657
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1658
/***********************************************************************
1659
 *		DrawIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1660
 */
1661
BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1662
{
1663
    return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1664 1665
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1666
/***********************************************************************
1667
 *		SetCursor (USER32.@)
1668 1669 1670 1671
 *
 * Set the cursor shape.
 *
 * RETURNS
Alexandre Julliard's avatar
Alexandre Julliard committed
1672
 *	A handle to the previous cursor shape.
Alexandre Julliard's avatar
Alexandre Julliard committed
1673
 */
1674
HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1675
{
1676
    struct cursoricon_object *obj;
1677
    HCURSOR hOldCursor;
1678 1679
    int show_count;
    BOOL ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1680

1681
    TRACE("%p\n", hCursor);
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695

    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;
1696
    USER_Driver->pSetCursor( show_count >= 0 ? hCursor : 0 );
1697 1698

    if (!(obj = get_icon_ptr( hOldCursor ))) return 0;
1699
    release_user_handle_ptr( obj );
Alexandre Julliard's avatar
Alexandre Julliard committed
1700 1701 1702
    return hOldCursor;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1703
/***********************************************************************
1704
 *		ShowCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1705
 */
1706
INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
Alexandre Julliard's avatar
Alexandre Julliard committed
1707
{
1708 1709
    HCURSOR cursor;
    int increment = bShow ? 1 : -1;
1710
    int count;
1711

1712 1713 1714 1715 1716 1717
    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 );
1718
        count = reply->prev_count + increment;
1719 1720 1721
    }
    SERVER_END_REQ;

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

1724 1725
    if (bShow && !count) USER_Driver->pSetCursor( cursor );
    else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
1726

1727
    return count;
Alexandre Julliard's avatar
Alexandre Julliard committed
1728 1729
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1730
/***********************************************************************
1731
 *		GetCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1732
 */
1733
HCURSOR WINAPI GetCursor(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
1734
{
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
    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
1745 1746 1747 1748
}


/***********************************************************************
1749
 *		ClipCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1750
 */
1751
BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
Alexandre Julliard's avatar
Alexandre Julliard committed
1752
{
1753 1754
    BOOL ret;
    RECT new_rect;
1755

1756
    TRACE( "Clipping to %s\n", wine_dbgstr_rect(rect) );
1757

1758 1759
    if (rect && (rect->left > rect->right || rect->top > rect->bottom)) return FALSE;

1760 1761
    SERVER_START_REQ( set_cursor )
    {
1762
        req->clip_msg = WM_WINE_CLIPCURSOR;
1763 1764
        if (rect)
        {
1765
            req->flags       = SET_CURSOR_CLIP;
1766 1767 1768 1769 1770
            req->clip.left   = rect->left;
            req->clip.top    = rect->top;
            req->clip.right  = rect->right;
            req->clip.bottom = rect->bottom;
        }
1771 1772
        else req->flags = SET_CURSOR_NOCLIP;

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
        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
1784 1785 1786 1787
}


/***********************************************************************
1788
 *		GetClipCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1789
 */
1790
BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
Alexandre Julliard's avatar
Alexandre Julliard committed
1791
{
1792
    BOOL ret;
1793

1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
    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
1809 1810
}

1811 1812 1813 1814 1815 1816

/***********************************************************************
 *		SetSystemCursor (USER32.@)
 */
BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
{
1817
    FIXME("(%p,%08x),stub!\n",  hcur, id);
1818 1819 1820 1821
    return TRUE;
}


1822 1823 1824 1825 1826
/**********************************************************************
 *		LookupIconIdFromDirectoryEx (USER32.@)
 */
INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
             INT width, INT height, UINT cFlag )
Alexandre Julliard's avatar
Alexandre Julliard committed
1827
{
1828
    const CURSORICONDIR *dir = (const CURSORICONDIR*)xdir;
1829
    UINT retVal = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
1830 1831
    if( dir && !dir->idReserved && (dir->idType & 3) )
    {
1832
        const CURSORICONDIRENTRY* entry;
1833

1834 1835 1836
        const HDC hdc = GetDC(0);
        const int depth = (cFlag & LR_MONOCHROME) ?
            1 : GetDeviceCaps(hdc, BITSPIXEL);
1837 1838 1839
        ReleaseDC(0, hdc);

        if( bIcon )
1840
            entry = CURSORICON_FindBestIconRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
1841
        else
1842
            entry = CURSORICON_FindBestCursorRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
1843

1844
        if( entry ) retVal = entry->wResId;
Alexandre Julliard's avatar
Alexandre Julliard committed
1845
    }
1846
    else WARN_(cursor)("invalid resource directory\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
1847 1848 1849
    return retVal;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1850
/**********************************************************************
1851
 *              LookupIconIdFromDirectory (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1852
 */
1853
INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1854
{
1855
    return LookupIconIdFromDirectoryEx( dir, bIcon, 0, 0, bIcon ? 0 : LR_MONOCHROME );
Alexandre Julliard's avatar
Alexandre Julliard committed
1856 1857
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1858
/***********************************************************************
1859
 *              LoadCursorW (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1860
 */
1861
HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1862
{
1863 1864
    TRACE("%p, %s\n", hInstance, debugstr_w(name));

1865
    return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1866
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1867 1868 1869
}

/***********************************************************************
1870
 *		LoadCursorA (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1871
 */
1872
HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1873
{
1874 1875
    TRACE("%p, %s\n", hInstance, debugstr_a(name));

1876
    return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1877
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1878
}
1879

Alexandre Julliard's avatar
Alexandre Julliard committed
1880
/***********************************************************************
1881 1882
 *		LoadCursorFromFileW (USER32.@)
 */
1883
HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1884
{
1885 1886
    TRACE("%s\n", debugstr_w(name));

1887
    return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1888
                       LR_LOADFROMFILE | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1889
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1890

Alexandre Julliard's avatar
Alexandre Julliard committed
1891
/***********************************************************************
1892 1893
 *		LoadCursorFromFileA (USER32.@)
 */
1894
HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1895
{
1896 1897
    TRACE("%s\n", debugstr_a(name));

1898
    return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1899
                       LR_LOADFROMFILE | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1900
}
1901

Alexandre Julliard's avatar
Alexandre Julliard committed
1902
/***********************************************************************
1903
 *		LoadIconW (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1904
 */
1905
HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1906
{
1907 1908
    TRACE("%p, %s\n", hInstance, debugstr_w(name));

1909
    return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1910
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1911 1912 1913
}

/***********************************************************************
1914
 *              LoadIconA (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1915
 */
1916
HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1917
{
1918 1919
    TRACE("%p, %s\n", hInstance, debugstr_a(name));

1920
    return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1921
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1922
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1923

1924 1925
/**********************************************************************
 *              GetCursorFrameInfo (USER32.@)
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
 *
 * 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)
1941
 */
1942
HCURSOR WINAPI GetCursorFrameInfo(HCURSOR hCursor, DWORD reserved, DWORD istep, DWORD *rate_jiffies, DWORD *num_steps)
1943 1944 1945
{
    struct cursoricon_object *ptr;
    HCURSOR ret = 0;
1946
    UINT icon_steps;
1947

1948
    if (rate_jiffies == NULL || num_steps == NULL) return 0;
1949 1950 1951

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

1952 1953 1954
    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);
1955

1956 1957
    icon_steps = get_icon_steps(ptr);
    if (istep < icon_steps || !ptr->is_ani)
1958
    {
1959 1960 1961 1962 1963 1964 1965 1966 1967
        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;
1968
        if (icon_frames == 1)
1969 1970
        {
            *rate_jiffies = 0;
1971
            *num_steps = 1;
1972
        }
1973 1974 1975 1976 1977 1978
        else if (icon_steps == 1)
        {
            *num_steps = ~0;
            *rate_jiffies = ptr->delay;
        }
        else if (istep < icon_steps)
1979
        {
1980 1981
            struct cursoricon_frame *frame;

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

1997
    release_user_handle_ptr( ptr );
1998 1999 2000 2001

    return ret;
}

2002
/**********************************************************************
2003
 *              GetIconInfo (USER32.@)
2004
 */
2005 2006
BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
{
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
    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
2018

2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
/**********************************************************************
 *              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;
}
2043

2044 2045 2046 2047 2048
/**********************************************************************
 *              GetIconInfoExW (USER32.@)
 */
BOOL WINAPI GetIconInfoExW( HICON icon, ICONINFOEXW *info )
{
2049
    struct cursoricon_frame *frame;
2050
    struct cursoricon_object *ptr;
2051
    HMODULE module;
2052
    BOOL ret = TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2053

2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
    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
2064

2065 2066 2067
    frame = get_icon_frame( ptr, 0 );
    if (!frame)
    {
2068
        release_user_handle_ptr( ptr );
2069 2070 2071 2072 2073
        SetLastError( ERROR_INVALID_CURSOR_HANDLE );
        return FALSE;
    }

    TRACE("%p => %dx%d\n", icon, frame->width, frame->height);
2074 2075 2076 2077

    info->fIcon        = ptr->is_icon;
    info->xHotspot     = ptr->hotspot.x;
    info->yHotspot     = ptr->hotspot.y;
2078 2079
    info->hbmColor     = copy_bitmap( frame->color );
    info->hbmMask      = copy_bitmap( frame->mask );
2080 2081 2082 2083 2084 2085 2086 2087
    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 );
    }
2088
    if (!info->hbmMask || (!info->hbmColor && frame->color))
2089 2090 2091 2092 2093
    {
        DeleteObject( info->hbmMask );
        DeleteObject( info->hbmColor );
        ret = FALSE;
    }
2094
    module = ptr->module;
2095
    release_icon_frame( ptr, frame );
2096
    release_user_handle_ptr( ptr );
2097
    if (ret && module) GetModuleFileNameW( module, info->szModName, MAX_PATH );
2098
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
2099 2100
}

2101 2102 2103 2104 2105 2106 2107
/* 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 );

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

2149 2150 2151 2152
    TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
           iconinfo->hbmColor, iconinfo->hbmMask,
           iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);

2153 2154
    if (!iconinfo->hbmMask) return 0;

2155 2156 2157 2158 2159
    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);

2160 2161
    if (iconinfo->hbmColor)
    {
2162
        GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2163
        TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2164 2165
               bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
               bmpXor.bmPlanes, bmpXor.bmBitsPixel);
2166

2167 2168
        width = bmpXor.bmWidth;
        height = bmpXor.bmHeight;
2169
        if (bmpXor.bmPlanes * bmpXor.bmBitsPixel != 1 || bmpAnd.bmPlanes * bmpAnd.bmBitsPixel != 1)
2170
        {
2171
            color = CreateCompatibleBitmap( get_screen_dc(), width, height );
2172 2173 2174
            mask = CreateBitmap( width, height, 1, 1, NULL );
        }
        else mask = CreateBitmap( width, height * 2, 1, 1, NULL );
2175
    }
2176 2177 2178 2179 2180 2181 2182
    else
    {
        width = bmpAnd.bmWidth;
        height = bmpAnd.bmHeight;
        mask = CreateBitmap( width, height, 1, 1, NULL );
    }

2183 2184 2185
    hdc = CreateCompatibleDC( 0 );
    SelectObject( hdc, mask );
    stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
2186 2187 2188

    if (color)
    {
2189 2190
        SelectObject( hdc, color );
        stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
2191 2192 2193
    }
    else if (iconinfo->hbmColor)
    {
2194
        stretch_blt_icon( hdc, 0, height, width, height, iconinfo->hbmColor, width, height );
2195
    }
2196 2197
    else height /= 2;

2198
    DeleteDC( hdc );
Alexandre Julliard's avatar
Alexandre Julliard committed
2199

2200
    hObj = alloc_icon_handle( FALSE, 0 );
Alexandre Julliard's avatar
Alexandre Julliard committed
2201 2202
    if (hObj)
    {
2203
        struct cursoricon_object *info = get_icon_ptr( hObj );
2204
        struct cursoricon_frame *frame;
2205

2206
        info->is_icon = iconinfo->fIcon;
2207 2208 2209 2210 2211 2212
        frame = get_icon_frame( info, 0 );
        frame->delay  = ~0;
        frame->width  = width;
        frame->height = height;
        frame->color  = color;
        frame->mask   = mask;
2213
        frame->alpha  = create_alpha_bitmap( iconinfo->hbmColor, NULL, NULL );
2214
        release_icon_frame( info, frame );
2215
        if (info->is_icon)
2216
        {
2217 2218
            info->hotspot.x = width / 2;
            info->hotspot.y = height / 2;
2219 2220 2221
        }
        else
        {
2222 2223
            info->hotspot.x = iconinfo->xHotspot;
            info->hotspot.y = iconinfo->yHotspot;
2224 2225
        }

2226
        release_user_handle_ptr( info );
Alexandre Julliard's avatar
Alexandre Julliard committed
2227
    }
2228
    return hObj;
Alexandre Julliard's avatar
Alexandre Julliard committed
2229
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2230

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

2264 2265
    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
2266

2267
    if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2268
    if (istep >= get_icon_steps( ptr ))
2269
    {
2270
        TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
2271
        release_user_handle_ptr( ptr );
2272 2273
        return FALSE;
    }
2274 2275 2276
    if (!(frame = get_icon_frame( ptr, istep )))
    {
        FIXME_(icon)("Error retrieving icon frame %d\n", istep);
2277
        release_user_handle_ptr( ptr );
2278 2279
        return FALSE;
    }
2280
    if (!(hMemDC = CreateCompatibleDC( hdc )))
2281
    {
2282
        release_icon_frame( ptr, frame );
2283
        release_user_handle_ptr( ptr );
2284 2285
        return FALSE;
    }
2286

2287 2288
    if (flags & DI_NOMIRROR)
        FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
2289

2290 2291
    /* Calculate the size of the destination image.  */
    if (cxWidth == 0)
2292
    {
2293 2294 2295
        if (flags & DI_DEFAULTSIZE)
            cxWidth = GetSystemMetrics (SM_CXICON);
        else
2296
            cxWidth = frame->width;
2297
    }
2298
    if (cyWidth == 0)
2299
    {
2300 2301 2302
        if (flags & DI_DEFAULTSIZE)
            cyWidth = GetSystemMetrics (SM_CYICON);
        else
2303
            cyWidth = frame->height;
2304
    }
2305

2306 2307
    DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);

2308
    if (DoOffscreen) {
2309 2310
        RECT r;

2311
        SetRect(&r, 0, 0, cxWidth, cxWidth);
2312

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

2330
    nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2331

2332 2333
    oldFg = SetTextColor( hdc, RGB(0,0,0) );
    oldBg = SetBkColor( hdc, RGB(255,255,255) );
2334

2335
    if (frame->alpha && (flags & DI_IMAGE))
2336
    {
2337
        BOOL alpha_blend = TRUE;
2338

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

    if (flags & DI_MASK)
2356
    {
2357
        DWORD rop = (flags & DI_IMAGE) ? SRCAND : SRCCOPY;
2358
        SelectObject( hMemDC, frame->mask );
2359
        StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2360
                    hMemDC, 0, 0, frame->width, frame->height, rop );
2361
    }
2362

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

2382
done:
2383 2384 2385 2386 2387 2388 2389
    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 );
2390
    if (hB_off) DeleteObject(hB_off);
2391
failed:
2392
    DeleteDC( hMemDC );
2393
    release_icon_frame( ptr, frame );
2394
    release_user_handle_ptr( ptr );
Alexandre Julliard's avatar
Alexandre Julliard committed
2395 2396
    return result;
}
2397

2398 2399 2400 2401 2402 2403 2404 2405
/***********************************************************************
 *           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)
{
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 2455 2456 2457 2458 2459
    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);
2460
    }
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
    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);
            }
        }
2479 2480 2481
}


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

2503 2504
    if (!(loadflags & LR_LOADFROMFILE))
    {
2505 2506 2507 2508 2509
        if (!instance)
        {
            /* OEM bitmap: try to load the resource from user32.dll */
            instance = user32_module;
        }
2510

2511 2512
        if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
        if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2513

2514
        if ((info = LockResource( handle )) == NULL) return 0;
2515 2516 2517
    }
    else
    {
2518 2519
        BITMAPFILEHEADER * bmfh;

2520
        if (!(ptr = map_fileW( name, NULL ))) return 0;
2521
        info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2522
        bmfh = (BITMAPFILEHEADER *)ptr;
2523
        if (bmfh->bfType != 0x4d42 /* 'BM' */)
2524 2525
        {
            WARN("Invalid/unsupported bitmap format!\n");
2526
            goto end;
2527
        }
2528
        if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2529
    }
2530

2531 2532 2533 2534 2535 2536 2537 2538
    bm_type = DIB_GetBitmapInfo( &info->bmiHeader, &width, &height,
                                 &bpp_dummy, &compr_dummy);
    if (bm_type == -1)
    {
        WARN("Invalid bitmap format!\n");
        goto end;
    }

2539
    size = bitmap_info_size(info, DIB_RGB_COLORS);
2540 2541
    fix_info = HeapAlloc(GetProcessHeap(), 0, size);
    scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2542

2543 2544
    if (!fix_info || !scaled_info) goto end;
    memcpy(fix_info, info, size);
2545

2546 2547
    pix = *((LPBYTE)info + size);
    DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2548

2549
    memcpy(scaled_info, fix_info, size);
2550

2551 2552 2553 2554
    if(desiredx != 0)
        new_width = desiredx;
    else
        new_width = width;
2555

2556 2557 2558 2559
    if(desiredy != 0)
        new_height = height > 0 ? desiredy : -desiredy;
    else
        new_height = height;
2560

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

2575 2576 2577 2578 2579 2580
        scaled_info->bmiHeader.biWidth = new_width;
        scaled_info->bmiHeader.biHeight = new_height;
    }

    if (new_height < 0) new_height = -new_height;

2581
    screen_dc = get_screen_dc();
2582 2583
    if (!(screen_mem_dc = CreateCompatibleDC( screen_dc ))) goto end;

2584
    bits = (char *)info + (offbits ? offbits : size);
2585

2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
    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);        
2597
    }
2598

2599 2600 2601 2602 2603 2604 2605 2606
    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);
2607
    if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2608

2609 2610 2611 2612
    return hbitmap;
}

/**********************************************************************
2613
 *		LoadImageA (USER32.@)
2614
 *
2615
 * See LoadImageW.
2616 2617 2618 2619 2620 2621 2622
 */
HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
                              INT desiredx, INT desiredy, UINT loadflags)
{
    HANDLE res;
    LPWSTR u_name;

2623
    if (IS_INTRESOURCE(name))
2624
        return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2625

2626
    __TRY {
2627 2628 2629
        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 );
2630
    }
2631
    __EXCEPT_PAGE_FAULT {
2632 2633
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
2634 2635
    }
    __ENDTRY
2636
    res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2637
    HeapFree(GetProcessHeap(), 0, u_name);
2638 2639 2640 2641 2642
    return res;
}


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

2664 2665 2666
    TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
                     hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);

2667 2668 2669
    if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
    switch (type) {
    case IMAGE_BITMAP:
2670
        return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2671 2672

    case IMAGE_ICON:
2673 2674 2675
    case IMAGE_CURSOR:
        depth = 1;
        if (!(loadflags & LR_MONOCHROME))
2676
        {
2677 2678 2679 2680
            HDC screen_dc;

            if ((screen_dc = get_screen_dc()))
                depth = GetDeviceCaps( screen_dc, BITSPIXEL );
2681
        }
2682
        return CURSORICON_Load(hinst, name, desiredx, desiredy, depth, (type == IMAGE_CURSOR), loadflags);
2683 2684 2685 2686 2687
    }
    return 0;
}

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

2720 2721
    switch (type)
    {
2722
        case IMAGE_BITMAP:
2723
        {
2724 2725 2726 2727
            HBITMAP res = NULL;
            DIBSECTION ds;
            int objSize;
            BITMAPINFO * bi;
2728

2729 2730 2731 2732 2733
            objSize = GetObjectW( hnd, sizeof(ds), &ds );
            if (!objSize) return 0;
            if ((desiredx < 0) || (desiredy < 0)) return 0;

            if (flags & LR_COPYFROMRESOURCE)
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 2760 2761 2762 2763 2764 2765 2766 2767
                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;
2768 2769 2770

                /* Get the color table or the color masks */
                GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785

                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);
2786 2787
                    bi->bmiHeader.biWidth  = ds.dsBm.bmWidth;
                    bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
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 2887 2888 2889 2890 2891 2892 2893 2894
                    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);
                }
2895
            }
2896
            HeapFree(GetProcessHeap(), 0, bi);
2897
            return res;
2898
        }
2899 2900
        case IMAGE_ICON:
        case IMAGE_CURSOR:
2901 2902 2903
        {
            struct cursoricon_object *icon;
            HICON res = 0;
2904
            int depth = (flags & LR_MONOCHROME) ? 1 : GetDeviceCaps( get_screen_dc(), BITSPIXEL );
2905 2906 2907 2908 2909 2910 2911 2912 2913

            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;

2914
            if (icon->rsrc && (flags & LR_COPYFROMRESOURCE))
2915
                res = CURSORICON_Load( icon->module, icon->resname, desiredx, desiredy, depth,
2916
                                       !icon->is_icon, flags );
2917 2918
            else
                res = CopyIcon( hnd ); /* FIXME: change size if necessary */
2919
            release_user_handle_ptr( icon );
2920 2921 2922 2923

            if (res && (flags & LR_COPYDELETEORG)) DeleteObject( hnd );
            return res;
        }
2924 2925 2926 2927 2928 2929
    }
    return 0;
}


/******************************************************************************
2930
 *		LoadBitmapW (USER32.@) Loads bitmap from the executable file
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
 *
 * 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 );
}

/**********************************************************************
2944
 *		LoadBitmapA (USER32.@)
2945 2946
 *
 * See LoadBitmapW.
2947 2948 2949 2950 2951
 */
HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
{
    return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );
}