cursoricon.c 80.6 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 <stdarg.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
29 30
#include <string.h>
#include <stdlib.h>
31

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

43
WINE_DEFAULT_DEBUG_CHANNEL(cursor);
44 45
WINE_DECLARE_DEBUG_CHANNEL(icon);
WINE_DECLARE_DEBUG_CHANNEL(resource);
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#include "pshpack1.h"

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

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

#include "poppack.h"

70
static RECT CURSOR_ClipRect;       /* Cursor clipping rect */
Alexandre Julliard's avatar
Alexandre Julliard committed
71

72
static HDC screen_dc;
73

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

76

77 78 79 80 81
/**********************************************************************
 * ICONCACHE for cursors/icons loaded with LR_SHARED.
 *
 * FIXME: This should not be allocated on the system heap, but on a
 *        subsystem-global heap (i.e. one for all Win16 processes,
82
 *        and one for each Win32 process).
83 84 85 86 87 88 89
 */
typedef struct tagICONCACHE
{
    struct tagICONCACHE *next;

    HMODULE              hModule;
    HRSRC                hRsrc;
90
    HRSRC                hGroupRsrc;
91
    HICON                hIcon;
92 93 94 95 96 97

    INT                  count;

} ICONCACHE;

static ICONCACHE *IconAnchor = NULL;
98 99 100 101 102 103

static CRITICAL_SECTION IconCrst;
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &IconCrst,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
104
      0, 0, { (DWORD_PTR)(__FILE__ ": IconCrst") }
105 106 107
};
static CRITICAL_SECTION IconCrst = { &critsect_debug, -1, 0, 0, 0, 0 };

108

109 110 111 112 113 114 115 116
/**********************************************************************
 * User objects management
 */

struct cursoricon_object
{
    struct user_object obj;      /* object header */
    ULONG_PTR          param;    /* opaque param used by 16-bit code */
117
    HBITMAP            color;    /* color bitmap */
118
    HBITMAP            alpha;    /* pre-multiplied alpha bitmap for 32-bpp icons */
119
    HBITMAP            mask;     /* mask bitmap (followed by color for 1-bpp icons) */
120 121 122 123
    BOOL               is_icon;  /* whether icon or cursor */
    UINT               width;
    UINT               height;
    POINT              hotspot;
124 125
};

126
static HICON alloc_icon_handle(void)
127
{
128
    struct cursoricon_object *obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) );
129 130
    if (!obj) return 0;
    obj->param = 0;
131
    obj->color = 0;
132
    obj->alpha = 0;
133
    obj->mask  = 0;
134 135 136
    return alloc_user_handle( &obj->obj, USER_ICON );
}

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

148
static void release_icon_ptr( HICON handle, struct cursoricon_object *ptr )
149
{
150
    release_user_handle_ptr( ptr );
151 152 153 154 155 156 157 158 159 160
}

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;
161
        if (obj->color) DeleteObject( obj->color );
162
        if (obj->alpha) DeleteObject( obj->alpha );
163
        DeleteObject( obj->mask );
164 165
        HeapFree( GetProcessHeap(), 0, obj );
        if (wow_handlers.free_icon_param && param) wow_handlers.free_icon_param( param );
166
        USER_Driver->pDestroyCursorIcon( handle );
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        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;
}


202 203 204 205
/***********************************************************************
 *             map_fileW
 *
 * Helper function to map a file to memory:
206
 *  name			-	file name
207
 *  [RETURN] ptr		-	pointer to mapped file
208
 *  [RETURN] filesize           -       pointer size of file to be stored if not NULL
209
 */
210
static void *map_fileW( LPCWSTR name, LPDWORD filesize )
211 212 213 214 215 216 217 218
{
    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)
    {
219
        hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
220 221 222 223
        if (hMapping)
        {
            ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
            CloseHandle( hMapping );
224 225
            if (filesize)
                *filesize = GetFileSize( hFile, NULL );
226
        }
227
        CloseHandle( hFile );
228 229 230 231 232
    }
    return ptr;
}


233 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
/***********************************************************************
 *          get_dib_width_bytes
 *
 * Return the width of a DIB bitmap in bytes. DIB bitmap data is 32-bit aligned.
 */
static int get_dib_width_bytes( int width, int depth )
{
    int words;

    switch(depth)
    {
    case 1:  words = (width + 31) / 32; break;
    case 4:  words = (width + 7) / 8; break;
    case 8:  words = (width + 3) / 4; break;
    case 15:
    case 16: words = (width + 1) / 2; break;
    case 24: words = (width * 3 + 3)/4; break;
    default:
        WARN("(%d): Unsupported depth\n", depth );
        /* fall through */
    case 32:
        words = width;
    }
    return 4 * words;
}


/***********************************************************************
 *           bitmap_info_size
 *
 * Return the size of the bitmap info structure including color table.
 */
static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
{
267
    unsigned int colors, size, masks = 0;
268 269 270

    if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
    {
271
        const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
272 273 274 275 276 277 278
        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;
279 280
        if (colors > 256) /* buffer overflow otherwise */
                colors = 256;
281 282
        if (!colors && (info->bmiHeader.biBitCount <= 8))
            colors = 1 << info->bmiHeader.biBitCount;
283
        if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
284 285
        size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
        return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
286 287 288 289
    }
}


290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
/***********************************************************************
 *             copy_bitmap
 *
 * Helper function to duplicate a bitmap.
 */
static HBITMAP copy_bitmap( HBITMAP bitmap )
{
    HDC src, dst;
    HBITMAP new_bitmap;
    BITMAP bmp;

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

    src = CreateCompatibleDC( 0 );
    dst = CreateCompatibleDC( 0 );
    SelectObject( src, bitmap );
    new_bitmap = CreateCompatibleBitmap( src, bmp.bmWidth, bmp.bmHeight );
    SelectObject( dst, new_bitmap );
    BitBlt( dst, 0, 0, bmp.bmWidth, bmp.bmHeight, src, 0, 0, SRCCOPY );
    DeleteDC( dst );
    DeleteDC( src );
    return new_bitmap;
}


316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
/***********************************************************************
 *          is_dib_monochrome
 *
 * Returns whether a DIB can be converted to a monochrome DDB.
 *
 * A DIB can be converted if its color table contains only black and
 * white. Black must be the first color in the color table.
 *
 * Note : If the first color in the color table is white followed by
 *        black, we can't convert it to a monochrome DDB with
 *        SetDIBits, because black and white would be inverted.
 */
static BOOL is_dib_monochrome( const BITMAPINFO* info )
{
    if (info->bmiHeader.biBitCount != 1) return FALSE;

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

336 337 338 339 340 341 342 343 344 345 346 347 348
        /* 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
349
        const RGBQUAD *rgb = info->bmiColors;
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

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

365 366 367 368 369 370 371 372 373 374 375
/***********************************************************************
 *           DIB_GetBitmapInfo
 *
 * Get the info from a bitmap header.
 * Return 1 for INFOHEADER, 0 for COREHEADER,
 */
static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
                              LONG *height, WORD *bpp, DWORD *compr )
{
    if (header->biSize == sizeof(BITMAPCOREHEADER))
    {
376
        const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
377 378 379 380 381 382
        *width  = core->bcWidth;
        *height = core->bcHeight;
        *bpp    = core->bcBitCount;
        *compr  = 0;
        return 0;
    }
383
    else if (header->biSize >= sizeof(BITMAPINFOHEADER))
384
    {
385 386 387 388 389
        *width  = header->biWidth;
        *height = header->biHeight;
        *bpp    = header->biBitCount;
        *compr  = header->biCompression;
        return 1;
390
    }
391
    ERR("(%d): unknown/wrong size for header\n", header->biSize );
392 393
    return -1;
}
394

395 396 397
/**********************************************************************
 *	    CURSORICON_FindSharedIcon
 */
398
static HICON CURSORICON_FindSharedIcon( HMODULE hModule, HRSRC hRsrc )
399
{
400
    HICON hIcon = 0;
401 402 403 404 405 406 407 408
    ICONCACHE *ptr;

    EnterCriticalSection( &IconCrst );

    for ( ptr = IconAnchor; ptr; ptr = ptr->next )
        if ( ptr->hModule == hModule && ptr->hRsrc == hRsrc )
        {
            ptr->count++;
409
            hIcon = ptr->hIcon;
410 411 412 413 414
            break;
        }

    LeaveCriticalSection( &IconCrst );

415
    return hIcon;
416 417
}

418
/*************************************************************************
419
 * CURSORICON_FindCache
420
 *
Andreas Mohr's avatar
Andreas Mohr committed
421
 * Given a handle, find the corresponding cache element
422 423
 *
 * PARAMS
424
 *      Handle     [I] handle to an Image
425 426 427 428 429 430
 *
 * RETURNS
 *     Success: The cache entry
 *     Failure: NULL
 *
 */
431
static ICONCACHE* CURSORICON_FindCache(HICON hIcon)
432 433 434 435 436 437 438
{
    ICONCACHE *ptr;
    ICONCACHE *pRet=NULL;
    BOOL IsFound = FALSE;

    EnterCriticalSection( &IconCrst );

439
    for (ptr = IconAnchor; ptr != NULL && !IsFound; ptr = ptr->next)
440
    {
441
        if ( hIcon == ptr->hIcon )
442 443 444 445 446 447 448 449 450 451 452
        {
            IsFound = TRUE;
            pRet = ptr;
        }
    }

    LeaveCriticalSection( &IconCrst );

    return pRet;
}

453 454 455
/**********************************************************************
 *	    CURSORICON_AddSharedIcon
 */
456
static void CURSORICON_AddSharedIcon( HMODULE hModule, HRSRC hRsrc, HRSRC hGroupRsrc, HICON hIcon )
457
{
458
    ICONCACHE *ptr = HeapAlloc( GetProcessHeap(), 0, sizeof(ICONCACHE) );
459 460 461 462
    if ( !ptr ) return;

    ptr->hModule = hModule;
    ptr->hRsrc   = hRsrc;
463
    ptr->hIcon  = hIcon;
464
    ptr->hGroupRsrc = hGroupRsrc;
465 466 467 468 469 470 471 472 473 474 475
    ptr->count   = 1;

    EnterCriticalSection( &IconCrst );
    ptr->next    = IconAnchor;
    IconAnchor   = ptr;
    LeaveCriticalSection( &IconCrst );
}

/**********************************************************************
 *	    CURSORICON_DelSharedIcon
 */
476
static INT CURSORICON_DelSharedIcon( HICON hIcon )
477 478 479 480 481 482 483
{
    INT count = -1;
    ICONCACHE *ptr;

    EnterCriticalSection( &IconCrst );

    for ( ptr = IconAnchor; ptr; ptr = ptr->next )
484
        if ( ptr->hIcon == hIcon )
485 486 487 488 489 490 491 492 493 494 495
        {
            if ( ptr->count > 0 ) ptr->count--;
            count = ptr->count;
            break;
        }

    LeaveCriticalSection( &IconCrst );

    return count;
}

496 497 498 499 500
/**********************************************************************
 *              get_icon_size
 */
BOOL get_icon_size( HICON handle, SIZE *size )
{
501
    struct cursoricon_object *info;
502

503
    if (!(info = get_icon_ptr( handle ))) return FALSE;
504 505
    size->cx = info->width;
    size->cy = info->height;
506
    release_icon_ptr( handle, info );
507 508 509
    return TRUE;
}

510 511 512 513 514 515 516
/*
 *  The following macro functions account for the irregularities of
 *   accessing cursor and icon resources in files and resource entries.
 */
typedef BOOL (*fnGetCIEntry)( LPVOID dir, int n,
                              int *width, int *height, int *bits );

Alexandre Julliard's avatar
Alexandre Julliard committed
517 518 519
/**********************************************************************
 *	    CURSORICON_FindBestIcon
 *
520
 * Find the icon closest to the requested size and bit depth.
Alexandre Julliard's avatar
Alexandre Julliard committed
521
 */
522
static int CURSORICON_FindBestIcon( LPVOID dir, fnGetCIEntry get_entry,
523
                                    int width, int height, int depth )
Alexandre Julliard's avatar
Alexandre Julliard committed
524
{
525
    int i, cx, cy, bits, bestEntry = -1;
526 527
    UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
    UINT iTempXDiff, iTempYDiff, iTempColorDiff;
Alexandre Julliard's avatar
Alexandre Julliard committed
528

529 530 531
    /* Find Best Fit */
    iTotalDiff = 0xFFFFFFFF;
    iColorDiff = 0xFFFFFFFF;
532
    for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
533
    {
534 535
        iTempXDiff = abs(width - cx);
        iTempYDiff = abs(height - cy);
Alexandre Julliard's avatar
Alexandre Julliard committed
536

537
        if(iTotalDiff > (iTempXDiff + iTempYDiff))
Alexandre Julliard's avatar
Alexandre Julliard committed
538
        {
539 540
            iXDiff = iTempXDiff;
            iYDiff = iTempYDiff;
541
            iTotalDiff = iXDiff + iYDiff;
Alexandre Julliard's avatar
Alexandre Julliard committed
542
        }
543
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
544

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

    return bestEntry;
}

562 563 564 565 566 567 568 569 570 571
static BOOL CURSORICON_GetResIconEntry( LPVOID dir, int n,
                                        int *width, int *height, int *bits )
{
    CURSORICONDIR *resdir = dir;
    ICONRESDIR *icon;

    if ( resdir->idCount <= n )
        return FALSE;
    icon = &resdir->idEntries[n].ResInfo.icon;
    *width = icon->bWidth;
572
    *height = icon->bHeight;
573 574 575
    *bits = resdir->idEntries[n].wBitCount;
    return TRUE;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
576 577 578 579 580

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

589 590 591 592
    /* Double height to account for AND and XOR masks */

    height *= 2;

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

    maxwidth = maxheight = 0;
596 597 598
    for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
    {
        if ((cx <= width) && (cy <= height) &&
599
            (cx > maxwidth) && (cy > maxheight))
Alexandre Julliard's avatar
Alexandre Julliard committed
600
        {
601 602 603
            bestEntry = i;
            maxwidth  = cx;
            maxheight = cy;
Alexandre Julliard's avatar
Alexandre Julliard committed
604
        }
605 606
    }
    if (bestEntry != -1) return bestEntry;
Alexandre Julliard's avatar
Alexandre Julliard committed
607 608 609 610

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

    maxwidth = maxheight = 255;
611 612
    for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
    {
613
        if (((cx < maxwidth) && (cy < maxheight)) || (bestEntry == -1))
Alexandre Julliard's avatar
Alexandre Julliard committed
614
        {
615 616 617
            bestEntry = i;
            maxwidth  = cx;
            maxheight = cy;
Alexandre Julliard's avatar
Alexandre Julliard committed
618
        }
619
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
620 621 622 623

    return bestEntry;
}

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
static BOOL CURSORICON_GetResCursorEntry( LPVOID dir, int n,
                                          int *width, int *height, int *bits )
{
    CURSORICONDIR *resdir = dir;
    CURSORDIR *cursor;

    if ( resdir->idCount <= n )
        return FALSE;
    cursor = &resdir->idEntries[n].ResInfo.cursor;
    *width = cursor->wWidth;
    *height = cursor->wHeight;
    *bits = resdir->idEntries[n].wBitCount;
    return TRUE;
}

static CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( CURSORICONDIR * dir,
640
                                      int width, int height, int depth )
641 642 643 644
{
    int n;

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

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

661 662
static BOOL CURSORICON_GetFileEntry( LPVOID dir, int n,
                                     int *width, int *height, int *bits )
663
{
664 665
    CURSORICONFILEDIR *filedir = dir;
    CURSORICONFILEDIRENTRY *entry;
666
    BITMAPINFOHEADER *info;
667

668 669 670
    if ( filedir->idCount <= n )
        return FALSE;
    entry = &filedir->idEntries[n];
671 672
    /* FIXME: check against file size */
    info = (BITMAPINFOHEADER *)((char *)dir + entry->dwDIBOffset);
673 674
    *width = entry->bWidth;
    *height = entry->bHeight;
675
    *bits = info->biBitCount;
676
    return TRUE;
677
}
Alexandre Julliard's avatar
Alexandre Julliard committed
678

679
static CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( CURSORICONFILEDIR *dir,
680
                                      int width, int height, int depth )
681 682
{
    int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetFileEntry,
683
                                       width, height, depth );
684 685 686 687 688 689
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}

static CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( CURSORICONFILEDIR *dir,
690
                                      int width, int height, int depth )
691 692
{
    int n = CURSORICON_FindBestIcon( dir, CURSORICON_GetFileEntry,
693
                                     width, height, depth );
694 695 696 697
    if ( n < 0 )
        return NULL;
    return &dir->idEntries[n];
}
Alexandre Julliard's avatar
Alexandre Julliard committed
698

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
/***********************************************************************
 *          bmi_has_alpha
 */
static BOOL bmi_has_alpha( const BITMAPINFO *info, const void *bits )
{
    int i;
    BOOL has_alpha = FALSE;
    const unsigned char *ptr = bits;

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

/***********************************************************************
 *          create_alpha_bitmap
 *
 * Create the alpha bitmap for a 32-bpp icon that has an alpha channel.
 */
static HBITMAP create_alpha_bitmap( HBITMAP color, HBITMAP mask,
                                    const BITMAPINFO *src_info, const void *color_bits )
{
    HBITMAP alpha = 0;
    BITMAPINFO *info = NULL;
    BITMAP bm;
    HDC hdc;
    void *bits;
    unsigned char *ptr;
    int i;

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

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

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

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

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

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


783 784 785
/***********************************************************************
 *          create_icon_bitmaps
 *
786
 * Create the color, mask and alpha bitmaps from the DIB info.
787 788
 */
static BOOL create_icon_bitmaps( const BITMAPINFO *bmi, int width, int height,
789
                                 HBITMAP *color, HBITMAP *mask, HBITMAP *alpha )
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
{
    BOOL monochrome = is_dib_monochrome( bmi );
    unsigned int size = bitmap_info_size( bmi, DIB_RGB_COLORS );
    BITMAPINFO *info;
    void *color_bits, *mask_bits;
    BOOL ret = FALSE;
    HDC hdc = 0;

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

    memcpy( info, bmi, size );
    info->bmiHeader.biHeight /= 2;

    color_bits = (char *)bmi + size;
    mask_bits = (char *)color_bits +
        get_dib_width_bytes( bmi->bmiHeader.biWidth,
                             bmi->bmiHeader.biBitCount ) * abs(info->bmiHeader.biHeight);

810
    *alpha = 0;
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
    if (monochrome)
    {
        if (!(*mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
        *color = 0;

        /* copy color data into second half of mask bitmap */
        SelectObject( hdc, *mask );
        StretchDIBits( hdc, 0, height, width, height,
                       0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
                       color_bits, info, DIB_RGB_COLORS, SRCCOPY );
    }
    else
    {
        if (!(*mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
        if (!(*color = CreateBitmap( width, height, GetDeviceCaps( screen_dc, PLANES ),
                                     GetDeviceCaps( screen_dc, BITSPIXEL ), NULL )))
        {
            DeleteObject( *mask );
            goto done;
        }
        SelectObject( hdc, *color );
        StretchDIBits( hdc, 0, 0, width, height,
                       0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
                       color_bits, info, DIB_RGB_COLORS, SRCCOPY );

836 837 838
        if (bmi_has_alpha( info, color_bits ))
            *alpha = create_alpha_bitmap( *color, *mask, info, color_bits );

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
        /* convert info to monochrome to copy the mask */
        info->bmiHeader.biBitCount = 1;
        if (info->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
        {
            RGBQUAD *rgb = info->bmiColors;

            info->bmiHeader.biClrUsed = info->bmiHeader.biClrImportant = 2;
            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
        {
            RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)info) + 1);

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

    SelectObject( hdc, *mask );
    StretchDIBits( hdc, 0, 0, width, height,
                   0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
                   mask_bits, info, DIB_RGB_COLORS, SRCCOPY );
    ret = TRUE;

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

871
static HICON CURSORICON_CreateIconFromBMI( BITMAPINFO *bmi,
872
					   POINT hotspot, BOOL bIcon,
873 874 875
					   DWORD dwVersion,
					   INT width, INT height,
					   UINT cFlag )
Alexandre Julliard's avatar
Alexandre Julliard committed
876
{
877
    HICON hObj;
878
    HBITMAP color = 0, mask = 0, alpha = 0;
879
    BOOL do_stretch;
Alexandre Julliard's avatar
Alexandre Julliard committed
880

Alexandre Julliard's avatar
Alexandre Julliard committed
881 882
    if (dwVersion == 0x00020000)
    {
883 884
        FIXME_(cursor)("\t2.xx resources are not supported\n");
        return 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
885 886
    }

Alexandre Julliard's avatar
Alexandre Julliard committed
887
    /* Check bitmap header */
Alexandre Julliard's avatar
Alexandre Julliard committed
888

Alexandre Julliard's avatar
Alexandre Julliard committed
889
    if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
890 891
         (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER)  ||
          bmi->bmiHeader.biCompression != BI_RGB) )
Alexandre Julliard's avatar
Alexandre Julliard committed
892
    {
893
          WARN_(cursor)("\tinvalid resource bitmap header.\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
894
          return 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
895 896
    }

897 898
    if (!width) width = bmi->bmiHeader.biWidth;
    if (!height) height = bmi->bmiHeader.biHeight/2;
899 900
    do_stretch = (bmi->bmiHeader.biHeight/2 != height) ||
                 (bmi->bmiHeader.biWidth != width);
901

902
    /* Scale the hotspot */
903 904 905 906 907 908
    if (bIcon)
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
    }
    else if (do_stretch)
909 910 911 912 913
    {
        hotspot.x = (hotspot.x * width) / bmi->bmiHeader.biWidth;
        hotspot.y = (hotspot.y * height) / (bmi->bmiHeader.biHeight / 2);
    }

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

917
    if (!create_icon_bitmaps( bmi, width, height, &color, &mask, &alpha )) return 0;
918

919
    hObj = alloc_icon_handle();
Alexandre Julliard's avatar
Alexandre Julliard committed
920
    if (hObj)
Alexandre Julliard's avatar
Alexandre Julliard committed
921
    {
922
        struct cursoricon_object *info = get_icon_ptr( hObj );
Alexandre Julliard's avatar
Alexandre Julliard committed
923

924 925 926 927 928 929 930
        info->color   = color;
        info->mask    = mask;
        info->alpha   = alpha;
        info->is_icon = bIcon;
        info->hotspot = hotspot;
        info->width   = width;
        info->height  = height;
931
        release_icon_ptr( hObj, info );
932
        USER_Driver->pCreateCursorIcon( hObj );
Alexandre Julliard's avatar
Alexandre Julliard committed
933
    }
934 935 936
    else
    {
        DeleteObject( color );
937
        DeleteObject( alpha );
938 939
        DeleteObject( mask );
    }
940
    return hObj;
Alexandre Julliard's avatar
Alexandre Julliard committed
941 942 943
}


944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
/**********************************************************************
 *          .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')

#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)
    {
1019 1020
        if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
                || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1021 1022
        {
            ptr += sizeof(DWORD);
1023
            chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1024 1025 1026 1027 1028 1029 1030 1031
            ptr += sizeof(DWORD);
            if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
            chunk->data = ptr;

            return;
        }

        ptr += sizeof(DWORD);
1032
        ptr += (*(const DWORD *)ptr + 1) & ~1;
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        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
 */
static HCURSOR CURSORICON_CreateIconFromANI( const LPBYTE bits, DWORD bits_size,
1051
    INT width, INT height, INT depth )
1052 1053 1054 1055
{
    HCURSOR cursor;
    ani_header header = {0};
    LPBYTE frame_bits = 0;
1056
    POINT hotspot;
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    CURSORICONFILEDIRENTRY *entry;

    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};
    const unsigned char *icon_data;

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

    if (!bits) return 0;

    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 );

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

    /* FIXME: For now, just load the first frame.  Before we can load all the
     * frames, we need to write the needed code in wineserver, etc. to handle
     * cursors.  Once this code is written, we can extend it to support .ani
     * cursors and then update user32 and winex11.drv to load all frames.
     *
     * Hopefully this will at least make some games (C&C3, etc.) more playable
1098
     * in the meantime.
1099 1100 1101 1102
     */
    FIXME("Loading all frames for .ani cursors not implemented.\n");
    icon_data = fram_chunk.data + (2 * sizeof(DWORD));

1103
    entry = CURSORICON_FindBestIconFile( (CURSORICONFILEDIR *) icon_data,
1104
        width, height, depth );
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

    frame_bits = HeapAlloc( GetProcessHeap(), 0, entry->dwDIBSize );
    memcpy( frame_bits, icon_data + entry->dwDIBOffset, entry->dwDIBSize );

    if (!header.width || !header.height)
    {
        header.width = entry->bWidth;
        header.height = entry->bHeight;
    }

    hotspot.x = entry->xHotspot;
    hotspot.y = entry->yHotspot;

    cursor = CURSORICON_CreateIconFromBMI( (BITMAPINFO *) frame_bits, hotspot,
        FALSE, 0x00030000, header.width, header.height, 0 );

    HeapFree( GetProcessHeap(), 0, frame_bits );

    return cursor;
}


1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
/**********************************************************************
 *		CreateIconFromResourceEx (USER32.@)
 *
 * FIXME: Convert to mono when cFlag is LR_MONOCHROME. Do something
 *        with cbSize parameter as well.
 */
HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
                                       BOOL bIcon, DWORD dwVersion,
                                       INT width, INT height,
                                       UINT cFlag )
{
1138
    POINT hotspot;
1139 1140 1141 1142
    BITMAPINFO *bmi;

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

    if (bIcon)
1146 1147 1148
    {
        hotspot.x = width / 2;
        hotspot.y = height / 2;
1149
        bmi = (BITMAPINFO *)bits;
1150
    }
1151 1152
    else /* get the hotspot */
    {
1153 1154 1155 1156
        SHORT *pt = (SHORT *)bits;
        hotspot.x = pt[0];
        hotspot.y = pt[1];
        bmi = (BITMAPINFO *)(pt + 2);
1157 1158 1159 1160 1161 1162 1163
    }

    return CURSORICON_CreateIconFromBMI( bmi, hotspot, bIcon, dwVersion,
					 width, height, cFlag );
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1164
/**********************************************************************
1165
 *		CreateIconFromResource (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1166
 */
1167 1168
HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
                                           BOOL bIcon, DWORD dwVersion)
Alexandre Julliard's avatar
Alexandre Julliard committed
1169
{
1170
    return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
Alexandre Julliard's avatar
Alexandre Julliard committed
1171 1172 1173
}


1174
static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1175
                             INT width, INT height, INT depth,
1176 1177 1178 1179 1180 1181 1182
                             BOOL fCursor, UINT loadflags)
{
    CURSORICONFILEDIRENTRY *entry;
    CURSORICONFILEDIR *dir;
    DWORD filesize = 0;
    HICON hIcon = 0;
    LPBYTE bits;
1183
    POINT hotspot;
1184 1185 1186 1187 1188 1189 1190

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

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

1191 1192 1193
    /* Check for .ani. */
    if (memcmp( bits, "RIFF", 4 ) == 0)
    {
1194
        hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height,
1195
            depth );
1196 1197 1198
        goto end;
    }

1199 1200 1201 1202 1203 1204 1205 1206
    dir = (CURSORICONFILEDIR*) bits;
    if ( filesize < sizeof(*dir) )
        goto end;

    if ( filesize < (sizeof(*dir) + sizeof(dir->idEntries[0])*(dir->idCount-1)) )
        goto end;

    if ( fCursor )
1207
        entry = CURSORICON_FindBestCursorFile( dir, width, height, depth );
1208
    else
1209
        entry = CURSORICON_FindBestIconFile( dir, width, height, depth );
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219

    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;

1220 1221
    hotspot.x = entry->xHotspot;
    hotspot.y = entry->yHotspot;
1222 1223 1224
    hIcon = CURSORICON_CreateIconFromBMI( (BITMAPINFO *)&bits[entry->dwDIBOffset],
					  hotspot, !fCursor, 0x00030000,
					  width, height, loadflags );
1225 1226 1227 1228 1229 1230
end:
    TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
    UnmapViewOfFile( bits );
    return hIcon;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1231
/**********************************************************************
1232
 *          CURSORICON_Load
Alexandre Julliard's avatar
Alexandre Julliard committed
1233
 *
1234
 * Load a cursor or icon from resource or file.
Alexandre Julliard's avatar
Alexandre Julliard committed
1235
 */
1236
static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1237
                             INT width, INT height, INT depth,
1238
                             BOOL fCursor, UINT loadflags)
Alexandre Julliard's avatar
Alexandre Julliard committed
1239
{
1240 1241
    HANDLE handle = 0;
    HICON hIcon = 0;
1242
    HRSRC hRsrc, hGroupRsrc;
1243 1244 1245
    CURSORICONDIR *dir;
    CURSORICONDIRENTRY *dirEntry;
    LPBYTE bits;
1246 1247
    WORD wResId;
    DWORD dwBytesInRes;
1248

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

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

1255
    if (!hInstance) hInstance = user32_module;  /* Load OEM cursor/icon */
1256

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

1260
    /* Get directory resource ID */
Alexandre Julliard's avatar
Alexandre Julliard committed
1261

1262 1263 1264 1265
    if (!(hRsrc = FindResourceW( hInstance, name,
                                 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
        return 0;
    hGroupRsrc = hRsrc;
Alexandre Julliard's avatar
Alexandre Julliard committed
1266

1267
    /* Find the best entry in the directory */
1268

1269
    if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1270
    if (!(dir = LockResource( handle ))) return 0;
1271
    if (fCursor)
1272
        dirEntry = CURSORICON_FindBestCursorRes( dir, width, height, depth );
1273
    else
1274
        dirEntry = CURSORICON_FindBestIconRes( dir, width, height, depth );
1275 1276 1277 1278
    if (!dirEntry) return 0;
    wResId = dirEntry->wResId;
    dwBytesInRes = dirEntry->dwBytesInRes;
    FreeResource( handle );
1279

1280
    /* Load the resource */
1281

1282 1283
    if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
                                (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1284

1285 1286 1287 1288
    /* If shared icon, check whether it was already loaded */
    if (    (loadflags & LR_SHARED)
         && (hIcon = CURSORICON_FindSharedIcon( hInstance, hRsrc ) ) != 0 )
        return hIcon;
1289

1290
    if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1291
    bits = LockResource( handle );
1292 1293 1294
    hIcon = CreateIconFromResourceEx( bits, dwBytesInRes,
                                      !fCursor, 0x00030000, width, height, loadflags);
    FreeResource( handle );
1295

1296
    /* If shared icon, add to icon cache */
1297

1298 1299
    if ( hIcon && (loadflags & LR_SHARED) )
        CURSORICON_AddSharedIcon( hInstance, hRsrc, hGroupRsrc, hIcon );
1300

1301
    return hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1302 1303
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1304

1305
/*************************************************************************
1306
 * CURSORICON_ExtCopy
1307 1308 1309 1310
 *
 * Copies an Image from the Cache if LR_COPYFROMRESOURCE is specified
 *
 * PARAMS
1311
 *      Handle     [I] handle to an Image
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
 *      nType      [I] Type of Handle (IMAGE_CURSOR | IMAGE_ICON)
 *      iDesiredCX [I] The Desired width of the Image
 *      iDesiredCY [I] The desired height of the Image
 *      nFlags     [I] The flags from CopyImage
 *
 * RETURNS
 *     Success: The new handle of the Image
 *
 * NOTES
 *     LR_COPYDELETEORG and LR_MONOCHROME are currently not implemented.
1322
 *     LR_MONOCHROME should be implemented by CreateIconFromResourceEx.
1323 1324
 *     LR_COPYFROMRESOURCE will only work if the Image is in the Cache.
 *
1325
 *
1326 1327
 */

1328
static HICON CURSORICON_ExtCopy(HICON hIcon, UINT nType,
1329 1330
                                INT iDesiredCX, INT iDesiredCY,
                                UINT nFlags)
1331
{
1332
    HICON hNew=0;
1333

1334 1335
    TRACE_(icon)("hIcon %p, nType %u, iDesiredCX %i, iDesiredCY %i, nFlags %u\n",
                 hIcon, nType, iDesiredCX, iDesiredCY, nFlags);
1336

1337
    if(hIcon == 0)
1338
    {
1339
        return 0;
1340 1341 1342 1343 1344
    }

    /* Best Fit or Monochrome */
    if( (nFlags & LR_COPYFROMRESOURCE
        && (iDesiredCX > 0 || iDesiredCY > 0))
1345
        || nFlags & LR_MONOCHROME)
1346
    {
1347
        ICONCACHE* pIconCache = CURSORICON_FindCache(hIcon);
1348

1349
        /* Not Found in Cache, then do a straight copy
1350 1351 1352
        */
        if(pIconCache == NULL)
        {
1353
            hNew = CopyIcon( hIcon );
1354 1355 1356 1357 1358 1359 1360
            if(nFlags & LR_COPYFROMRESOURCE)
            {
                TRACE_(icon)("LR_COPYFROMRESOURCE: Failed to load from cache\n");
            }
        }
        else
        {
1361
            int iTargetCY = iDesiredCY, iTargetCX = iDesiredCX;
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
            LPBYTE pBits;
            HANDLE hMem;
            HRSRC hRsrc;
            DWORD dwBytesInRes;
            WORD wResId;
            CURSORICONDIR *pDir;
            CURSORICONDIRENTRY *pDirEntry;
            BOOL bIsIcon = (nType == IMAGE_ICON);

            /* Completing iDesiredCX CY for Monochrome Bitmaps if needed
            */
            if(((nFlags & LR_MONOCHROME) && !(nFlags & LR_COPYFROMRESOURCE))
                || (iDesiredCX == 0 && iDesiredCY == 0))
            {
1376
                iDesiredCY = GetSystemMetrics(bIsIcon ?
1377
                    SM_CYICON : SM_CYCURSOR);
1378
                iDesiredCX = GetSystemMetrics(bIsIcon ?
1379 1380 1381
                    SM_CXICON : SM_CXCURSOR);
            }

1382
            /* Retrieve the CURSORICONDIRENTRY
1383
            */
1384 1385
            if (!(hMem = LoadResource( pIconCache->hModule ,
                            pIconCache->hGroupRsrc)))
1386 1387 1388
            {
                return 0;
            }
1389
            if (!(pDir = LockResource( hMem )))
1390 1391 1392 1393
            {
                return 0;
            }

1394
            /* Find Best Fit
1395 1396 1397
            */
            if(bIsIcon)
            {
1398 1399
                pDirEntry = CURSORICON_FindBestIconRes(
                                pDir, iDesiredCX, iDesiredCY, 256 );
1400 1401 1402
            }
            else
            {
1403
                pDirEntry = CURSORICON_FindBestCursorRes(
1404 1405 1406 1407 1408 1409 1410
                                pDir, iDesiredCX, iDesiredCY, 1);
            }

            wResId = pDirEntry->wResId;
            dwBytesInRes = pDirEntry->dwBytesInRes;
            FreeResource(hMem);

1411
            TRACE_(icon)("ResID %u, BytesInRes %u, Width %d, Height %d DX %d, DY %d\n",
1412
                wResId, dwBytesInRes,  pDirEntry->ResInfo.icon.bWidth,
1413 1414 1415 1416 1417
                pDirEntry->ResInfo.icon.bHeight, iDesiredCX, iDesiredCY);

            /* Get the Best Fit
            */
            if (!(hRsrc = FindResourceW(pIconCache->hModule ,
1418
                MAKEINTRESOURCEW(wResId), (LPWSTR)(bIsIcon ? RT_ICON : RT_CURSOR))))
1419 1420 1421
            {
                return 0;
            }
1422
            if (!(hMem = LoadResource( pIconCache->hModule , hRsrc )))
1423 1424 1425 1426
            {
                return 0;
            }

1427
            pBits = LockResource( hMem );
1428

1429 1430 1431
            if(nFlags & LR_DEFAULTSIZE)
            {
                iTargetCY = GetSystemMetrics(SM_CYICON);
1432
                iTargetCX = GetSystemMetrics(SM_CXICON);
1433
            }
1434 1435 1436

            /* Create a New Icon with the proper dimension
            */
1437
            hNew = CreateIconFromResourceEx( pBits, dwBytesInRes,
1438 1439 1440 1441
                       bIsIcon, 0x00030000, iTargetCX, iTargetCY, nFlags);
            FreeResource(hMem);
        }
    }
1442
    else hNew = CopyIcon( hIcon );
1443 1444 1445
    return hNew;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1446 1447

/***********************************************************************
1448
 *		CreateCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1449
 */
1450 1451 1452
HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
                                 INT xHotSpot, INT yHotSpot,
                                 INT nWidth, INT nHeight,
Alexandre Julliard's avatar
Alexandre Julliard committed
1453
                                 LPCVOID lpANDbits, LPCVOID lpXORbits )
Alexandre Julliard's avatar
Alexandre Julliard committed
1454
{
1455 1456
    ICONINFO info;
    HCURSOR hCursor;
Alexandre Julliard's avatar
Alexandre Julliard committed
1457

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

1461 1462 1463 1464 1465 1466 1467 1468 1469
    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
1470 1471 1472
}


Alexandre Julliard's avatar
Alexandre Julliard committed
1473
/***********************************************************************
1474
 *		CreateIcon (USER32.@)
1475
 *
1476 1477 1478
 *  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
1479
 *  depth. The provided bitmaps must be top-down bitmaps.
1480
 *  Although Windows does not support 15bpp(*) this API must support it
1481 1482
 *  for Winelib applications.
 *
1483
 *  (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1484 1485
 *      format!
 *
1486 1487 1488 1489
 * RETURNS
 *  Success: handle to an icon
 *  Failure: NULL
 *
1490
 * FIXME: Do we need to resize the bitmaps?
Alexandre Julliard's avatar
Alexandre Julliard committed
1491
 */
1492
HICON WINAPI CreateIcon(
1493
    HINSTANCE hInstance,  /* [in] the application's hInstance */
1494 1495 1496 1497 1498 1499
    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
1500
{
1501
    ICONINFO iinfo;
1502
    HICON hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1503

1504 1505
    TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
                 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1506

1507
    iinfo.fIcon = TRUE;
1508 1509
    iinfo.xHotspot = nWidth / 2;
    iinfo.yHotspot = nHeight / 2;
1510 1511 1512 1513 1514 1515 1516
    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 );
1517 1518

    return hIcon;
Alexandre Julliard's avatar
Alexandre Julliard committed
1519 1520 1521 1522
}


/***********************************************************************
1523
 *		CopyIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1524
 */
1525
HICON WINAPI CopyIcon( HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1526
{
1527
    struct cursoricon_object *ptrOld, *ptrNew;
1528
    HICON hNew;
1529

1530
    if (!(ptrOld = get_icon_ptr( hIcon ))) return 0;
1531 1532 1533
    if ((hNew = alloc_icon_handle()))
    {
        ptrNew = get_icon_ptr( hNew );
1534 1535 1536 1537 1538 1539 1540
        ptrNew->color   = copy_bitmap( ptrOld->color );
        ptrNew->alpha   = copy_bitmap( ptrOld->alpha );
        ptrNew->mask    = copy_bitmap( ptrOld->mask );
        ptrNew->is_icon = ptrOld->is_icon;
        ptrNew->width   = ptrOld->width;
        ptrNew->height  = ptrOld->height;
        ptrNew->hotspot = ptrOld->hotspot;
1541 1542
        release_icon_ptr( hNew, ptrNew );
    }
1543
    release_icon_ptr( hIcon, ptrOld );
1544
    if (hNew) USER_Driver->pCreateCursorIcon( hNew );
1545
    return hNew;
Alexandre Julliard's avatar
Alexandre Julliard committed
1546
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1547 1548


Alexandre Julliard's avatar
Alexandre Julliard committed
1549
/***********************************************************************
1550
 *		DestroyIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1551
 */
1552
BOOL WINAPI DestroyIcon( HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1553
{
1554 1555 1556
    TRACE_(icon)("%p\n", hIcon );

    if (CURSORICON_DelSharedIcon( hIcon ) == -1)
1557
        free_icon_handle( hIcon );
1558
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1559 1560
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1561 1562

/***********************************************************************
1563
 *		DestroyCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1564
 */
1565
BOOL WINAPI DestroyCursor( HCURSOR hCursor )
Alexandre Julliard's avatar
Alexandre Julliard committed
1566
{
1567
    if (GetCursor() == hCursor)
1568 1569 1570 1571 1572
    {
        WARN_(cursor)("Destroying active cursor!\n" );
        return FALSE;
    }
    return DestroyIcon( hCursor );
Alexandre Julliard's avatar
Alexandre Julliard committed
1573 1574
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1575
/***********************************************************************
1576
 *		DrawIcon (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1577
 */
1578
BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1579
{
1580
    return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1581 1582
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1583
/***********************************************************************
1584
 *		SetCursor (USER32.@)
1585 1586 1587 1588
 *
 * Set the cursor shape.
 *
 * RETURNS
Alexandre Julliard's avatar
Alexandre Julliard committed
1589
 *	A handle to the previous cursor shape.
Alexandre Julliard's avatar
Alexandre Julliard committed
1590
 */
1591
HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1592
{
1593
    HCURSOR hOldCursor;
1594 1595
    int show_count;
    BOOL ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1596

1597
    TRACE("%p\n", hCursor);
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612

    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;

Alexandre Julliard's avatar
Alexandre Julliard committed
1613
    /* Change the cursor shape only if it is visible */
1614
    if (show_count >= 0 && hOldCursor != hCursor) USER_Driver->pSetCursor( hCursor );
Alexandre Julliard's avatar
Alexandre Julliard committed
1615 1616 1617
    return hOldCursor;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1618
/***********************************************************************
1619
 *		ShowCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1620
 */
1621
INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
Alexandre Julliard's avatar
Alexandre Julliard committed
1622
{
1623 1624
    HCURSOR cursor;
    int increment = bShow ? 1 : -1;
1625
    int count;
1626

1627 1628 1629 1630 1631 1632
    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 );
1633
        count = reply->prev_count + increment;
1634 1635 1636
    }
    SERVER_END_REQ;

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

1639 1640
    if (bShow && !count) USER_Driver->pSetCursor( cursor );
    else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
1641

1642
    return count;
Alexandre Julliard's avatar
Alexandre Julliard committed
1643 1644
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1645
/***********************************************************************
1646
 *		GetCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1647
 */
1648
HCURSOR WINAPI GetCursor(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
1649
{
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
    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
1660 1661 1662 1663
}


/***********************************************************************
1664
 *		ClipCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1665
 */
1666
BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
Alexandre Julliard's avatar
Alexandre Julliard committed
1667
{
1668 1669 1670 1671 1672 1673 1674
    RECT virt;

    SetRect( &virt, 0, 0, GetSystemMetrics( SM_CXVIRTUALSCREEN ),
                          GetSystemMetrics( SM_CYVIRTUALSCREEN ) );
    OffsetRect( &virt, GetSystemMetrics( SM_XVIRTUALSCREEN ),
                       GetSystemMetrics( SM_YVIRTUALSCREEN ) );

1675 1676 1677
    TRACE( "Clipping to: %s was: %s screen: %s\n", wine_dbgstr_rect(rect),
           wine_dbgstr_rect(&CURSOR_ClipRect), wine_dbgstr_rect(&virt) );

1678 1679 1680
    if (!IntersectRect( &CURSOR_ClipRect, &virt, rect ))
        CURSOR_ClipRect = virt;

1681
    USER_Driver->pClipCursor( rect );
Alexandre Julliard's avatar
Alexandre Julliard committed
1682 1683 1684 1685 1686
    return TRUE;
}


/***********************************************************************
1687
 *		GetClipCursor (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1688
 */
1689
BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
Alexandre Julliard's avatar
Alexandre Julliard committed
1690
{
1691 1692 1693
    /* If this is first time - initialize the rect */
    if (IsRectEmpty( &CURSOR_ClipRect )) ClipCursor( NULL );

1694
    return CopyRect( rect, &CURSOR_ClipRect );
Alexandre Julliard's avatar
Alexandre Julliard committed
1695 1696
}

1697 1698 1699 1700 1701 1702

/***********************************************************************
 *		SetSystemCursor (USER32.@)
 */
BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
{
1703
    FIXME("(%p,%08x),stub!\n",  hcur, id);
1704 1705 1706 1707
    return TRUE;
}


1708 1709 1710 1711 1712
/**********************************************************************
 *		LookupIconIdFromDirectoryEx (USER32.@)
 */
INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
             INT width, INT height, UINT cFlag )
Alexandre Julliard's avatar
Alexandre Julliard committed
1713
{
1714
    CURSORICONDIR       *dir = (CURSORICONDIR*)xdir;
1715
    UINT retVal = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
1716 1717
    if( dir && !dir->idReserved && (dir->idType & 3) )
    {
1718 1719
        CURSORICONDIRENTRY* entry;

1720 1721 1722
        const HDC hdc = GetDC(0);
        const int depth = (cFlag & LR_MONOCHROME) ?
            1 : GetDeviceCaps(hdc, BITSPIXEL);
1723 1724 1725
        ReleaseDC(0, hdc);

        if( bIcon )
1726
            entry = CURSORICON_FindBestIconRes( dir, width, height, depth );
1727
        else
1728
            entry = CURSORICON_FindBestCursorRes( dir, width, height, depth );
1729

1730
        if( entry ) retVal = entry->wResId;
Alexandre Julliard's avatar
Alexandre Julliard committed
1731
    }
1732
    else WARN_(cursor)("invalid resource directory\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
1733 1734 1735
    return retVal;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1736
/**********************************************************************
1737
 *              LookupIconIdFromDirectory (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1738
 */
1739
INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
Alexandre Julliard's avatar
Alexandre Julliard committed
1740
{
1741
    return LookupIconIdFromDirectoryEx( dir, bIcon,
1742 1743
           bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
           bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
Alexandre Julliard's avatar
Alexandre Julliard committed
1744 1745
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1746
/***********************************************************************
1747
 *              LoadCursorW (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1748
 */
1749
HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1750
{
1751 1752
    TRACE("%p, %s\n", hInstance, debugstr_w(name));

1753
    return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1754
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1755 1756 1757
}

/***********************************************************************
1758
 *		LoadCursorA (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1759
 */
1760
HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1761
{
1762 1763
    TRACE("%p, %s\n", hInstance, debugstr_a(name));

1764
    return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1765
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1766
}
1767

Alexandre Julliard's avatar
Alexandre Julliard committed
1768
/***********************************************************************
1769 1770
 *		LoadCursorFromFileW (USER32.@)
 */
1771
HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1772
{
1773 1774
    TRACE("%s\n", debugstr_w(name));

1775
    return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1776
                       LR_LOADFROMFILE | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1777
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1778

Alexandre Julliard's avatar
Alexandre Julliard committed
1779
/***********************************************************************
1780 1781
 *		LoadCursorFromFileA (USER32.@)
 */
1782
HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1783
{
1784 1785
    TRACE("%s\n", debugstr_a(name));

1786
    return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1787
                       LR_LOADFROMFILE | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1788
}
1789

Alexandre Julliard's avatar
Alexandre Julliard committed
1790
/***********************************************************************
1791
 *		LoadIconW (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1792
 */
1793
HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1794
{
1795 1796
    TRACE("%p, %s\n", hInstance, debugstr_w(name));

1797
    return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1798
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1799 1800 1801
}

/***********************************************************************
1802
 *              LoadIconA (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1803
 */
1804
HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
Alexandre Julliard's avatar
Alexandre Julliard committed
1805
{
1806 1807
    TRACE("%p, %s\n", hInstance, debugstr_a(name));

1808
    return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1809
                       LR_SHARED | LR_DEFAULTSIZE );
Alexandre Julliard's avatar
Alexandre Julliard committed
1810
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1811

1812
/**********************************************************************
1813
 *              GetIconInfo (USER32.@)
1814
 */
1815 1816
BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
{
1817
    struct cursoricon_object *ptr;
Alexandre Julliard's avatar
Alexandre Julliard committed
1818

1819
    if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
1820

1821
    TRACE("%p => %dx%d\n", hIcon, ptr->width, ptr->height);
Alexandre Julliard's avatar
Alexandre Julliard committed
1822

1823 1824 1825
    iconinfo->fIcon    = ptr->is_icon;
    iconinfo->xHotspot = ptr->hotspot.x;
    iconinfo->yHotspot = ptr->hotspot.y;
1826 1827 1828
    iconinfo->hbmColor = copy_bitmap( ptr->color );
    iconinfo->hbmMask  = copy_bitmap( ptr->mask );
    release_icon_ptr( hIcon, ptr );
Alexandre Julliard's avatar
Alexandre Julliard committed
1829

Alexandre Julliard's avatar
Alexandre Julliard committed
1830 1831 1832
    return TRUE;
}

1833 1834 1835 1836 1837 1838 1839
/* 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 );

1840
    if (!SelectObject( hdc, src ))  /* do it the hard way */
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
    {
        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;
        info->bmiHeader.biSizeImage = height * get_dib_width_bytes( width, info->bmiHeader.biBitCount );
        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
1870
/**********************************************************************
1871
 *		CreateIconIndirect (USER32.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
1872
 */
1873
HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
1874
{
1875
    BITMAP bmpXor, bmpAnd;
1876
    HICON hObj;
1877
    HBITMAP color = 0, mask;
1878
    int width, height;
1879
    HDC hdc;
Alexandre Julliard's avatar
Alexandre Julliard committed
1880

1881 1882 1883 1884
    TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
           iconinfo->hbmColor, iconinfo->hbmMask,
           iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);

1885 1886
    if (!iconinfo->hbmMask) return 0;

1887 1888 1889 1890 1891
    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);

1892 1893
    if (iconinfo->hbmColor)
    {
1894
        GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
1895
        TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
1896 1897
               bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
               bmpXor.bmPlanes, bmpXor.bmBitsPixel);
1898

1899 1900 1901
        width = bmpXor.bmWidth;
        height = bmpXor.bmHeight;
        if (bmpXor.bmPlanes * bmpXor.bmBitsPixel != 1)
1902 1903 1904 1905 1906
        {
            color = CreateCompatibleBitmap( screen_dc, width, height );
            mask = CreateBitmap( width, height, 1, 1, NULL );
        }
        else mask = CreateBitmap( width, height * 2, 1, 1, NULL );
1907
    }
1908 1909 1910 1911 1912 1913 1914
    else
    {
        width = bmpAnd.bmWidth;
        height = bmpAnd.bmHeight;
        mask = CreateBitmap( width, height, 1, 1, NULL );
    }

1915 1916 1917
    hdc = CreateCompatibleDC( 0 );
    SelectObject( hdc, mask );
    stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
1918 1919 1920

    if (color)
    {
1921 1922
        SelectObject( hdc, color );
        stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
1923 1924 1925
    }
    else if (iconinfo->hbmColor)
    {
1926
        stretch_blt_icon( hdc, 0, height, width, height, iconinfo->hbmColor, width, height );
1927
    }
1928 1929
    else height /= 2;

1930
    DeleteDC( hdc );
Alexandre Julliard's avatar
Alexandre Julliard committed
1931

1932
    hObj = alloc_icon_handle();
Alexandre Julliard's avatar
Alexandre Julliard committed
1933 1934
    if (hObj)
    {
1935
        struct cursoricon_object *info = get_icon_ptr( hObj );
1936

1937 1938 1939 1940 1941 1942 1943
        info->color   = color;
        info->mask    = mask;
        info->alpha   = create_alpha_bitmap( iconinfo->hbmColor, mask, NULL, NULL );
        info->is_icon = iconinfo->fIcon;
        info->width   = width;
        info->height  = height;
        if (info->is_icon)
1944
        {
1945 1946
            info->hotspot.x = width / 2;
            info->hotspot.y = height / 2;
1947 1948 1949
        }
        else
        {
1950 1951
            info->hotspot.x = iconinfo->xHotspot;
            info->hotspot.y = iconinfo->yHotspot;
1952 1953
        }

1954
        release_icon_ptr( hObj, info );
1955
        USER_Driver->pCreateCursorIcon( hObj );
Alexandre Julliard's avatar
Alexandre Julliard committed
1956
    }
1957
    return hObj;
Alexandre Julliard's avatar
Alexandre Julliard committed
1958
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1959

Alexandre Julliard's avatar
Alexandre Julliard committed
1960
/******************************************************************************
1961
 *		DrawIconEx (USER32.@) Draws an icon or cursor on device context
Alexandre Julliard's avatar
Alexandre Julliard committed
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
 *
 * 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
 */
1981
BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
1982
                            INT cxWidth, INT cyWidth, UINT istep,
1983
                            HBRUSH hbr, UINT flags )
Alexandre Julliard's avatar
Alexandre Julliard committed
1984
{
1985
    struct cursoricon_object *ptr;
1986
    HDC hdc_dest, hMemDC;
1987
    BOOL result = FALSE, DoOffscreen;
1988 1989 1990
    HBITMAP hB_off = 0;
    COLORREF oldFg, oldBg;
    INT x, y, nStretchMode;
1991

1992 1993
    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
1994

1995
    if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
1996 1997
    if (!(hMemDC = CreateCompatibleDC( hdc )))
    {
1998
        release_icon_ptr( hIcon, ptr );
1999 2000
        return FALSE;
    }
2001

Alexandre Julliard's avatar
Alexandre Julliard committed
2002
    if (istep)
2003
        FIXME_(icon)("Ignoring istep=%d\n", istep);
2004 2005
    if (flags & DI_NOMIRROR)
        FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
2006

2007 2008
    /* Calculate the size of the destination image.  */
    if (cxWidth == 0)
2009
    {
2010 2011 2012
        if (flags & DI_DEFAULTSIZE)
            cxWidth = GetSystemMetrics (SM_CXICON);
        else
2013
            cxWidth = ptr->width;
2014
    }
2015
    if (cyWidth == 0)
2016
    {
2017 2018 2019
        if (flags & DI_DEFAULTSIZE)
            cyWidth = GetSystemMetrics (SM_CYICON);
        else
2020
            cyWidth = ptr->height;
2021
    }
2022

2023 2024
    DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);

2025
    if (DoOffscreen) {
2026 2027 2028 2029 2030 2031 2032
        RECT r;

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

2033
        if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
2034 2035 2036
        if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
        {
            DeleteDC( hdc_dest );
2037
            goto failed;
2038
        }
2039 2040 2041
        SelectObject(hdc_dest, hB_off);
        FillRect(hdc_dest, &r, hbr);
        x = y = 0;
2042
    }
2043
    else
Alexandre Julliard's avatar
Alexandre Julliard committed
2044
    {
2045 2046 2047 2048
        hdc_dest = hdc;
        x = x0;
        y = y0;
    }
2049

2050
    nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2051

2052 2053
    oldFg = SetTextColor( hdc, RGB(0,0,0) );
    oldBg = SetBkColor( hdc, RGB(255,255,255) );
2054

2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
    if (ptr->alpha && (flags & DI_IMAGE))
    {
        BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };

        SelectObject( hMemDC, ptr->alpha );
        if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
                           0, 0, ptr->width, ptr->height, pixelblend )) goto done;
    }

    if (flags & DI_MASK)
2065 2066 2067
    {
        SelectObject( hMemDC, ptr->mask );
        StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2068
                    hMemDC, 0, 0, ptr->width, ptr->height, SRCAND );
2069
    }
2070

2071 2072
    if (flags & DI_IMAGE)
    {
2073
        if (ptr->color)
2074 2075 2076 2077
        {
            DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
            SelectObject( hMemDC, ptr->color );
            StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2078
                        hMemDC, 0, 0, ptr->width, ptr->height, rop );
2079 2080 2081 2082 2083 2084
        }
        else
        {
            DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
            SelectObject( hMemDC, ptr->mask );
            StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2085
                        hMemDC, 0, ptr->height, ptr->width, ptr->height, rop );
2086
        }
Alexandre Julliard's avatar
Alexandre Julliard committed
2087
    }
2088

2089
done:
2090 2091 2092 2093 2094 2095 2096
    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 );
2097
    if (hB_off) DeleteObject(hB_off);
2098
failed:
2099
    DeleteDC( hMemDC );
2100
    release_icon_ptr( hIcon, ptr );
Alexandre Julliard's avatar
Alexandre Julliard committed
2101 2102
    return result;
}
2103

2104 2105 2106 2107 2108 2109 2110 2111
/***********************************************************************
 *           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)
{
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
    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);
2166
    }
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
    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);
            }
        }
2185 2186 2187
}


2188 2189 2190
/**********************************************************************
 *       BITMAP_Load
 */
2191 2192
static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
                            INT desiredx, INT desiredy, UINT loadflags )
2193
{
2194
    HBITMAP hbitmap = 0, orig_bm;
2195 2196 2197
    HRSRC hRsrc;
    HGLOBAL handle;
    char *ptr = NULL;
2198
    BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2199
    int size;
2200 2201 2202 2203
    BYTE pix;
    char *bits;
    LONG width, height, new_width, new_height;
    WORD bpp_dummy;
2204
    DWORD compr_dummy, offbits = 0;
2205 2206
    INT bm_type;
    HDC screen_mem_dc = NULL;
2207

2208 2209
    if (!(loadflags & LR_LOADFROMFILE))
    {
2210 2211 2212 2213 2214
        if (!instance)
        {
            /* OEM bitmap: try to load the resource from user32.dll */
            instance = user32_module;
        }
2215

2216 2217
        if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
        if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2218

2219
        if ((info = LockResource( handle )) == NULL) return 0;
2220 2221 2222
    }
    else
    {
2223 2224
        BITMAPFILEHEADER * bmfh;

2225
        if (!(ptr = map_fileW( name, NULL ))) return 0;
2226
        info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2227
        bmfh = (BITMAPFILEHEADER *)ptr;
2228
        if (bmfh->bfType != 0x4d42 /* 'BM' */)
2229 2230
        {
            WARN("Invalid/unsupported bitmap format!\n");
2231
            goto end_close;
2232
        }
2233
        if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2234
    }
2235

2236 2237 2238 2239 2240
    if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
        WARN("Broken BitmapInfoHeader!\n");
        goto end_close;
    }

2241
    size = bitmap_info_size(info, DIB_RGB_COLORS);
2242 2243
    fix_info = HeapAlloc(GetProcessHeap(), 0, size);
    scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2244

2245 2246
    if (!fix_info || !scaled_info) goto end;
    memcpy(fix_info, info, size);
2247

2248 2249
    pix = *((LPBYTE)info + size);
    DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2250

2251 2252 2253 2254 2255 2256 2257
    memcpy(scaled_info, fix_info, size);
    bm_type = DIB_GetBitmapInfo( &fix_info->bmiHeader, &width, &height,
                                 &bpp_dummy, &compr_dummy);
    if(desiredx != 0)
        new_width = desiredx;
    else
        new_width = width;
2258

2259 2260 2261 2262
    if(desiredy != 0)
        new_height = height > 0 ? desiredy : -desiredy;
    else
        new_height = height;
2263

2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    if(bm_type == 0)
    {
        BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
        core->bcWidth = new_width;
        core->bcHeight = new_height;
    }
    else
    {
        scaled_info->bmiHeader.biWidth = new_width;
        scaled_info->bmiHeader.biHeight = new_height;
    }

    if (new_height < 0) new_height = -new_height;

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

2281
    bits = (char *)info + (offbits ? offbits : size);
2282

2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
    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);        
2294
    }
2295

2296 2297 2298 2299 2300 2301 2302 2303
    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);
2304
end_close:
2305
    if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2306

2307 2308 2309 2310
    return hbitmap;
}

/**********************************************************************
2311
 *		LoadImageA (USER32.@)
2312
 *
2313
 * See LoadImageW.
2314 2315 2316 2317 2318 2319 2320
 */
HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
                              INT desiredx, INT desiredy, UINT loadflags)
{
    HANDLE res;
    LPWSTR u_name;

2321
    if (IS_INTRESOURCE(name))
2322
        return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2323

2324
    __TRY {
2325 2326 2327
        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 );
2328
    }
2329
    __EXCEPT_PAGE_FAULT {
2330 2331
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
2332 2333
    }
    __ENDTRY
2334
    res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2335
    HeapFree(GetProcessHeap(), 0, u_name);
2336 2337 2338 2339 2340
    return res;
}


/******************************************************************************
2341
 *		LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
 *
 * 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
 *
2355
 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2356 2357 2358 2359
 */
HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
                INT desiredx, INT desiredy, UINT loadflags )
{
2360 2361 2362
    TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
                     hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);

2363 2364
    if (loadflags & LR_DEFAULTSIZE) {
        if (type == IMAGE_ICON) {
2365 2366 2367
            if (!desiredx) desiredx = GetSystemMetrics(SM_CXICON);
            if (!desiredy) desiredy = GetSystemMetrics(SM_CYICON);
        } else if (type == IMAGE_CURSOR) {
2368
            if (!desiredx) desiredx = GetSystemMetrics(SM_CXCURSOR);
2369 2370
            if (!desiredy) desiredy = GetSystemMetrics(SM_CYCURSOR);
        }
2371 2372 2373 2374
    }
    if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
    switch (type) {
    case IMAGE_BITMAP:
2375
        return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2376 2377

    case IMAGE_ICON:
2378
        if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2379
        if (screen_dc)
2380
        {
2381
            return CURSORICON_Load(hinst, name, desiredx, desiredy,
2382 2383
                                   GetDeviceCaps(screen_dc, BITSPIXEL),
                                   FALSE, loadflags);
2384 2385
        }
        break;
2386 2387 2388

    case IMAGE_CURSOR:
        return CURSORICON_Load(hinst, name, desiredx, desiredy,
2389
                               1, TRUE, loadflags);
2390 2391 2392 2393 2394
    }
    return 0;
}

/******************************************************************************
2395
 *		CopyImage (USER32.@) Creates new image and copies attributes to it
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
 *
 * 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
 *
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
 * 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.
2420
 */
2421
HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2422 2423
                             INT desiredy, UINT flags )
{
2424 2425 2426
    TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
          hnd, type, desiredx, desiredy, flags);

2427 2428
    switch (type)
    {
2429
        case IMAGE_BITMAP:
2430
        {
2431 2432 2433 2434
            HBITMAP res = NULL;
            DIBSECTION ds;
            int objSize;
            BITMAPINFO * bi;
2435

2436 2437 2438 2439 2440
            objSize = GetObjectW( hnd, sizeof(ds), &ds );
            if (!objSize) return 0;
            if ((desiredx < 0) || (desiredy < 0)) return 0;

            if (flags & LR_COPYFROMRESOURCE)
2441
            {
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
                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));
                }

                /* Get the color table or the color masks */
                GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);

                bi->bmiHeader.biWidth  = desiredx;
                bi->bmiHeader.biHeight = desiredy;
                bi->bmiHeader.biSizeImage = 0;

                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);
                    bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
                    bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
                    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);
                }
2603
            }
2604
            HeapFree(GetProcessHeap(), 0, bi);
2605
            return res;
2606
        }
2607 2608 2609 2610 2611 2612
        case IMAGE_ICON:
                return CURSORICON_ExtCopy(hnd,type, desiredx, desiredy, flags);
        case IMAGE_CURSOR:
                /* Should call CURSORICON_ExtCopy but more testing
                 * needs to be done before we change this
                 */
2613
                if (flags) FIXME("Flags are ignored\n");
2614
                return CopyCursor(hnd);
2615 2616 2617 2618 2619 2620
    }
    return 0;
}


/******************************************************************************
2621
 *		LoadBitmapW (USER32.@) Loads bitmap from the executable file
2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
 *
 * 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 );
}

/**********************************************************************
2635
 *		LoadBitmapA (USER32.@)
2636 2637
 *
 * See LoadBitmapW.
2638 2639 2640 2641 2642
 */
HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
{
    return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );
}