wininet: Keep handles invalid but reserved in InternetCloseHandle.
[wine] / dlls / user32 / cursoricon.c
1 /*
2  * Cursor and icon support
3  *
4  * Copyright 1995 Alexandre Julliard
5  *           1996 Martin Von Loewis
6  *           1997 Alex Korobka
7  *           1998 Turchanov Sergey
8  *           2007 Henri Verbeet
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * 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
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <stdarg.h>
30 #include <string.h>
31 #include <stdlib.h>
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "wingdi.h"
36 #include "winerror.h"
37 #include "winnls.h"
38 #include "wine/exception.h"
39 #include "wine/server.h"
40 #include "controls.h"
41 #include "win.h"
42 #include "user_private.h"
43 #include "wine/list.h"
44 #include "wine/unicode.h"
45 #include "wine/debug.h"
46
47 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
48 WINE_DECLARE_DEBUG_CHANNEL(icon);
49 WINE_DECLARE_DEBUG_CHANNEL(resource);
50
51 #include "pshpack1.h"
52
53 typedef struct {
54     BYTE bWidth;
55     BYTE bHeight;
56     BYTE bColorCount;
57     BYTE bReserved;
58     WORD xHotspot;
59     WORD yHotspot;
60     DWORD dwDIBSize;
61     DWORD dwDIBOffset;
62 } CURSORICONFILEDIRENTRY;
63
64 typedef struct
65 {
66     WORD                idReserved;
67     WORD                idType;
68     WORD                idCount;
69     CURSORICONFILEDIRENTRY  idEntries[1];
70 } CURSORICONFILEDIR;
71
72 #include "poppack.h"
73
74 static RECT CURSOR_ClipRect;       /* Cursor clipping rect */
75
76 static HDC screen_dc;
77
78 static const WCHAR DISPLAYW[] = {'D','I','S','P','L','A','Y',0};
79
80 static struct list icon_cache = LIST_INIT( icon_cache );
81
82 /**********************************************************************
83  * User objects management
84  */
85
86 struct cursoricon_frame
87 {
88     HBITMAP            color;    /* color bitmap */
89     HBITMAP            alpha;    /* pre-multiplied alpha bitmap for 32-bpp icons */
90     HBITMAP            mask;     /* mask bitmap (followed by color for 1-bpp icons) */
91 };
92
93 struct cursoricon_object
94 {
95     struct user_object      obj;        /* object header */
96     struct list             entry;      /* entry in shared icons list */
97     ULONG_PTR               param;      /* opaque param used by 16-bit code */
98     HMODULE                 module;     /* module for icons loaded from resources */
99     LPWSTR                  resname;    /* resource name for icons loaded from resources */
100     HRSRC                   rsrc;       /* resource for shared icons */
101     BOOL                    is_icon;    /* whether icon or cursor */
102     UINT                    width;
103     UINT                    height;
104     POINT                   hotspot;
105     UINT                    num_frames; /* number of frames in the icon/cursor */
106     UINT                    ms_delay;   /* delay between frames (in milliseconds) */
107     struct cursoricon_frame frames[1];  /* icon frame information */
108 };
109
110 static HICON alloc_icon_handle( UINT num_frames )
111 {
112     struct cursoricon_object *obj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
113                                                FIELD_OFFSET( struct cursoricon_object, frames[num_frames] ));
114
115     if (!obj) return 0;
116     obj->num_frames = num_frames;
117     return alloc_user_handle( &obj->obj, USER_ICON );
118 }
119
120 static struct cursoricon_object *get_icon_ptr( HICON handle )
121 {
122     struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
123     if (obj == OBJ_OTHER_PROCESS)
124     {
125         WARN( "icon handle %p from other process\n", handle );
126         obj = NULL;
127     }
128     return obj;
129 }
130
131 static void release_icon_ptr( HICON handle, struct cursoricon_object *ptr )
132 {
133     release_user_handle_ptr( ptr );
134 }
135
136 static BOOL free_icon_handle( HICON handle )
137 {
138     struct cursoricon_object *obj = free_user_handle( handle, USER_ICON );
139
140     if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
141     else if (obj)
142     {
143         ULONG_PTR param = obj->param;
144         UINT i;
145
146         assert( !obj->rsrc );  /* shared icons can't be freed */
147
148         for (i=0; i<obj->num_frames; i++)
149         {
150             if (obj->frames[i].alpha) DeleteObject( obj->frames[i].alpha );
151             if (obj->frames[i].color) DeleteObject( obj->frames[i].color );
152             DeleteObject( obj->frames[i].mask );
153         }
154         if (!IS_INTRESOURCE( obj->resname )) HeapFree( GetProcessHeap(), 0, obj->resname );
155         HeapFree( GetProcessHeap(), 0, obj );
156         if (wow_handlers.free_icon_param && param) wow_handlers.free_icon_param( param );
157         USER_Driver->pDestroyCursorIcon( handle );
158         return TRUE;
159     }
160     return FALSE;
161 }
162
163 ULONG_PTR get_icon_param( HICON handle )
164 {
165     ULONG_PTR ret = 0;
166     struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
167
168     if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
169     else if (obj)
170     {
171         ret = obj->param;
172         release_user_handle_ptr( obj );
173     }
174     return ret;
175 }
176
177 ULONG_PTR set_icon_param( HICON handle, ULONG_PTR param )
178 {
179     ULONG_PTR ret = 0;
180     struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
181
182     if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
183     else if (obj)
184     {
185         ret = obj->param;
186         obj->param = param;
187         release_user_handle_ptr( obj );
188     }
189     return ret;
190 }
191
192
193 /***********************************************************************
194  *             map_fileW
195  *
196  * Helper function to map a file to memory:
197  *  name                        -       file name
198  *  [RETURN] ptr                -       pointer to mapped file
199  *  [RETURN] filesize           -       pointer size of file to be stored if not NULL
200  */
201 static void *map_fileW( LPCWSTR name, LPDWORD filesize )
202 {
203     HANDLE hFile, hMapping;
204     LPVOID ptr = NULL;
205
206     hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
207                          OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
208     if (hFile != INVALID_HANDLE_VALUE)
209     {
210         hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
211         if (hMapping)
212         {
213             ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
214             CloseHandle( hMapping );
215             if (filesize)
216                 *filesize = GetFileSize( hFile, NULL );
217         }
218         CloseHandle( hFile );
219     }
220     return ptr;
221 }
222
223
224 /***********************************************************************
225  *          get_dib_width_bytes
226  *
227  * Return the width of a DIB bitmap in bytes. DIB bitmap data is 32-bit aligned.
228  */
229 static int get_dib_width_bytes( int width, int depth )
230 {
231     int words;
232
233     switch(depth)
234     {
235     case 1:  words = (width + 31) / 32; break;
236     case 4:  words = (width + 7) / 8; break;
237     case 8:  words = (width + 3) / 4; break;
238     case 15:
239     case 16: words = (width + 1) / 2; break;
240     case 24: words = (width * 3 + 3)/4; break;
241     default:
242         WARN("(%d): Unsupported depth\n", depth );
243         /* fall through */
244     case 32:
245         words = width;
246     }
247     return 4 * words;
248 }
249
250
251 /***********************************************************************
252  *           bitmap_info_size
253  *
254  * Return the size of the bitmap info structure including color table.
255  */
256 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
257 {
258     unsigned int colors, size, masks = 0;
259
260     if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
261     {
262         const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
263         colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
264         return sizeof(BITMAPCOREHEADER) + colors *
265              ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
266     }
267     else  /* assume BITMAPINFOHEADER */
268     {
269         colors = info->bmiHeader.biClrUsed;
270         if (colors > 256) /* buffer overflow otherwise */
271                 colors = 256;
272         if (!colors && (info->bmiHeader.biBitCount <= 8))
273             colors = 1 << info->bmiHeader.biBitCount;
274         if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
275         size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
276         return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
277     }
278 }
279
280
281 /***********************************************************************
282  *             copy_bitmap
283  *
284  * Helper function to duplicate a bitmap.
285  */
286 static HBITMAP copy_bitmap( HBITMAP bitmap )
287 {
288     HDC src, dst = 0;
289     HBITMAP new_bitmap = 0;
290     BITMAP bmp;
291
292     if (!bitmap) return 0;
293     if (!GetObjectW( bitmap, sizeof(bmp), &bmp )) return 0;
294
295     if ((src = CreateCompatibleDC( 0 )) && (dst = CreateCompatibleDC( 0 )))
296     {
297         SelectObject( src, bitmap );
298         if ((new_bitmap = CreateCompatibleBitmap( src, bmp.bmWidth, bmp.bmHeight )))
299         {
300             SelectObject( dst, new_bitmap );
301             BitBlt( dst, 0, 0, bmp.bmWidth, bmp.bmHeight, src, 0, 0, SRCCOPY );
302         }
303     }
304     DeleteDC( dst );
305     DeleteDC( src );
306     return new_bitmap;
307 }
308
309
310 /***********************************************************************
311  *          is_dib_monochrome
312  *
313  * Returns whether a DIB can be converted to a monochrome DDB.
314  *
315  * A DIB can be converted if its color table contains only black and
316  * white. Black must be the first color in the color table.
317  *
318  * Note : If the first color in the color table is white followed by
319  *        black, we can't convert it to a monochrome DDB with
320  *        SetDIBits, because black and white would be inverted.
321  */
322 static BOOL is_dib_monochrome( const BITMAPINFO* info )
323 {
324     if (info->bmiHeader.biBitCount != 1) return FALSE;
325
326     if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
327     {
328         const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
329
330         /* Check if the first color is black */
331         if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
332         {
333             rgb++;
334
335             /* Check if the second color is white */
336             return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
337                  && (rgb->rgbtBlue == 0xff));
338         }
339         else return FALSE;
340     }
341     else  /* assume BITMAPINFOHEADER */
342     {
343         const RGBQUAD *rgb = info->bmiColors;
344
345         /* Check if the first color is black */
346         if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
347             (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
348         {
349             rgb++;
350
351             /* Check if the second color is white */
352             return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
353                  && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
354         }
355         else return FALSE;
356     }
357 }
358
359 /***********************************************************************
360  *           DIB_GetBitmapInfo
361  *
362  * Get the info from a bitmap header.
363  * Return 1 for INFOHEADER, 0 for COREHEADER, -1 in case of failure.
364  */
365 static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
366                               LONG *height, WORD *bpp, DWORD *compr )
367 {
368     if (header->biSize == sizeof(BITMAPCOREHEADER))
369     {
370         const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
371         *width  = core->bcWidth;
372         *height = core->bcHeight;
373         *bpp    = core->bcBitCount;
374         *compr  = 0;
375         return 0;
376     }
377     else if (header->biSize >= sizeof(BITMAPINFOHEADER))
378     {
379         *width  = header->biWidth;
380         *height = header->biHeight;
381         *bpp    = header->biBitCount;
382         *compr  = header->biCompression;
383         return 1;
384     }
385     ERR("(%d): unknown/wrong size for header\n", header->biSize );
386     return -1;
387 }
388
389 /**********************************************************************
390  *              get_icon_size
391  */
392 BOOL get_icon_size( HICON handle, SIZE *size )
393 {
394     struct cursoricon_object *info;
395
396     if (!(info = get_icon_ptr( handle ))) return FALSE;
397     size->cx = info->width;
398     size->cy = info->height;
399     release_icon_ptr( handle, info );
400     return TRUE;
401 }
402
403 /*
404  *  The following macro functions account for the irregularities of
405  *   accessing cursor and icon resources in files and resource entries.
406  */
407 typedef BOOL (*fnGetCIEntry)( LPCVOID dir, int n,
408                               int *width, int *height, int *bits );
409
410 /**********************************************************************
411  *          CURSORICON_FindBestIcon
412  *
413  * Find the icon closest to the requested size and bit depth.
414  */
415 static int CURSORICON_FindBestIcon( LPCVOID dir, fnGetCIEntry get_entry,
416                                     int width, int height, int depth, UINT loadflags )
417 {
418     int i, cx, cy, bits, bestEntry = -1;
419     UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
420     UINT iTempXDiff, iTempYDiff, iTempColorDiff;
421
422     /* Find Best Fit */
423     iTotalDiff = 0xFFFFFFFF;
424     iColorDiff = 0xFFFFFFFF;
425
426     if (loadflags & LR_DEFAULTSIZE)
427     {
428         if (!width) width = GetSystemMetrics( SM_CXICON );
429         if (!height) height = GetSystemMetrics( SM_CYICON );
430     }
431     else if (!width && !height)
432     {
433         /* use the size of the first entry */
434         if (!get_entry( dir, 0, &width, &height, &bits )) return -1;
435         iTotalDiff = 0;
436     }
437
438     for ( i = 0; iTotalDiff && get_entry( dir, i, &cx, &cy, &bits ); i++ )
439     {
440         iTempXDiff = abs(width - cx);
441         iTempYDiff = abs(height - cy);
442
443         if(iTotalDiff > (iTempXDiff + iTempYDiff))
444         {
445             iXDiff = iTempXDiff;
446             iYDiff = iTempYDiff;
447             iTotalDiff = iXDiff + iYDiff;
448         }
449     }
450
451     /* Find Best Colors for Best Fit */
452     for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
453     {
454         if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
455         {
456             iTempColorDiff = abs(depth - bits);
457             if(iColorDiff > iTempColorDiff)
458             {
459                 bestEntry = i;
460                 iColorDiff = iTempColorDiff;
461             }
462         }
463     }
464
465     return bestEntry;
466 }
467
468 static BOOL CURSORICON_GetResIconEntry( LPCVOID dir, int n,
469                                         int *width, int *height, int *bits )
470 {
471     const CURSORICONDIR *resdir = dir;
472     const ICONRESDIR *icon;
473
474     if ( resdir->idCount <= n )
475         return FALSE;
476     icon = &resdir->idEntries[n].ResInfo.icon;
477     *width = icon->bWidth;
478     *height = icon->bHeight;
479     *bits = resdir->idEntries[n].wBitCount;
480     return TRUE;
481 }
482
483 /**********************************************************************
484  *          CURSORICON_FindBestCursor
485  *
486  * Find the cursor closest to the requested size.
487  *
488  * FIXME: parameter 'color' ignored.
489  */
490 static int CURSORICON_FindBestCursor( LPCVOID dir, fnGetCIEntry get_entry,
491                                       int width, int height, int depth, UINT loadflags )
492 {
493     int i, maxwidth, maxheight, cx, cy, bits, bestEntry = -1;
494
495     if (loadflags & LR_DEFAULTSIZE)
496     {
497         if (!width) width = GetSystemMetrics( SM_CXCURSOR );
498         if (!height) height = GetSystemMetrics( SM_CYCURSOR );
499     }
500     else if (!width && !height)
501     {
502         /* use the first entry */
503         if (!get_entry( dir, 0, &width, &height, &bits )) return -1;
504         return 0;
505     }
506
507     /* Double height to account for AND and XOR masks */
508
509     height *= 2;
510
511     /* First find the largest one smaller than or equal to the requested size*/
512
513     maxwidth = maxheight = 0;
514     for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
515     {
516         if ((cx <= width) && (cy <= height) &&
517             (cx > maxwidth) && (cy > maxheight))
518         {
519             bestEntry = i;
520             maxwidth  = cx;
521             maxheight = cy;
522         }
523     }
524     if (bestEntry != -1) return bestEntry;
525
526     /* Now find the smallest one larger than the requested size */
527
528     maxwidth = maxheight = 255;
529     for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
530     {
531         if (((cx < maxwidth) && (cy < maxheight)) || (bestEntry == -1))
532         {
533             bestEntry = i;
534             maxwidth  = cx;
535             maxheight = cy;
536         }
537     }
538
539     return bestEntry;
540 }
541
542 static BOOL CURSORICON_GetResCursorEntry( LPCVOID dir, int n,
543                                           int *width, int *height, int *bits )
544 {
545     const CURSORICONDIR *resdir = dir;
546     const CURSORDIR *cursor;
547
548     if ( resdir->idCount <= n )
549         return FALSE;
550     cursor = &resdir->idEntries[n].ResInfo.cursor;
551     *width = cursor->wWidth;
552     *height = cursor->wHeight;
553     *bits = resdir->idEntries[n].wBitCount;
554     return TRUE;
555 }
556
557 static const CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( const CURSORICONDIR * dir,
558                                                              int width, int height, int depth,
559                                                              UINT loadflags )
560 {
561     int n;
562
563     n = CURSORICON_FindBestIcon( dir, CURSORICON_GetResIconEntry,
564                                  width, height, depth, loadflags );
565     if ( n < 0 )
566         return NULL;
567     return &dir->idEntries[n];
568 }
569
570 static const CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( const CURSORICONDIR *dir,
571                                                                int width, int height, int depth,
572                                                                UINT loadflags )
573 {
574     int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetResCursorEntry,
575                                        width, height, depth, loadflags );
576     if ( n < 0 )
577         return NULL;
578     return &dir->idEntries[n];
579 }
580
581 static BOOL CURSORICON_GetFileEntry( LPCVOID dir, int n,
582                                      int *width, int *height, int *bits )
583 {
584     const CURSORICONFILEDIR *filedir = dir;
585     const CURSORICONFILEDIRENTRY *entry;
586     const BITMAPINFOHEADER *info;
587
588     if ( filedir->idCount <= n )
589         return FALSE;
590     entry = &filedir->idEntries[n];
591     /* FIXME: check against file size */
592     info = (const BITMAPINFOHEADER *)((const char *)dir + entry->dwDIBOffset);
593     *width = entry->bWidth;
594     *height = entry->bHeight;
595     *bits = info->biBitCount;
596     return TRUE;
597 }
598
599 static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( const CURSORICONFILEDIR *dir,
600                                                                     int width, int height, int depth,
601                                                                     UINT loadflags )
602 {
603     int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetFileEntry,
604                                        width, height, depth, loadflags );
605     if ( n < 0 )
606         return NULL;
607     return &dir->idEntries[n];
608 }
609
610 static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( const CURSORICONFILEDIR *dir,
611                                                                   int width, int height, int depth,
612                                                                   UINT loadflags )
613 {
614     int n = CURSORICON_FindBestIcon( dir, CURSORICON_GetFileEntry,
615                                      width, height, depth, loadflags );
616     if ( n < 0 )
617         return NULL;
618     return &dir->idEntries[n];
619 }
620
621 /***********************************************************************
622  *          bmi_has_alpha
623  */
624 static BOOL bmi_has_alpha( const BITMAPINFO *info, const void *bits )
625 {
626     int i;
627     BOOL has_alpha = FALSE;
628     const unsigned char *ptr = bits;
629
630     if (info->bmiHeader.biBitCount != 32) return FALSE;
631     for (i = 0; i < info->bmiHeader.biWidth * abs(info->bmiHeader.biHeight); i++, ptr += 4)
632         if ((has_alpha = (ptr[3] != 0))) break;
633     return has_alpha;
634 }
635
636 /***********************************************************************
637  *          create_alpha_bitmap
638  *
639  * Create the alpha bitmap for a 32-bpp icon that has an alpha channel.
640  */
641 static HBITMAP create_alpha_bitmap( HBITMAP color, HBITMAP mask,
642                                     const BITMAPINFO *src_info, const void *color_bits )
643 {
644     HBITMAP alpha = 0;
645     BITMAPINFO *info = NULL;
646     BITMAP bm;
647     HDC hdc;
648     void *bits;
649     unsigned char *ptr;
650     int i;
651
652     if (!GetObjectW( color, sizeof(bm), &bm )) return 0;
653     if (bm.bmBitsPixel != 32) return 0;
654
655     if (!(hdc = CreateCompatibleDC( 0 ))) return 0;
656     if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto done;
657     info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
658     info->bmiHeader.biWidth = bm.bmWidth;
659     info->bmiHeader.biHeight = -bm.bmHeight;
660     info->bmiHeader.biPlanes = 1;
661     info->bmiHeader.biBitCount = 32;
662     info->bmiHeader.biCompression = BI_RGB;
663     info->bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
664     info->bmiHeader.biXPelsPerMeter = 0;
665     info->bmiHeader.biYPelsPerMeter = 0;
666     info->bmiHeader.biClrUsed = 0;
667     info->bmiHeader.biClrImportant = 0;
668     if (!(alpha = CreateDIBSection( hdc, info, DIB_RGB_COLORS, &bits, NULL, 0 ))) goto done;
669
670     if (src_info)
671     {
672         SelectObject( hdc, alpha );
673         StretchDIBits( hdc, 0, 0, bm.bmWidth, bm.bmHeight,
674                        0, 0, src_info->bmiHeader.biWidth, src_info->bmiHeader.biHeight,
675                        color_bits, src_info, DIB_RGB_COLORS, SRCCOPY );
676
677     }
678     else
679     {
680         GetDIBits( hdc, color, 0, bm.bmHeight, bits, info, DIB_RGB_COLORS );
681         if (!bmi_has_alpha( info, bits ))
682         {
683             DeleteObject( alpha );
684             alpha = 0;
685             goto done;
686         }
687     }
688
689     /* pre-multiply by alpha */
690     for (i = 0, ptr = bits; i < bm.bmWidth * bm.bmHeight; i++, ptr += 4)
691     {
692         unsigned int alpha = ptr[3];
693         ptr[0] = ptr[0] * alpha / 255;
694         ptr[1] = ptr[1] * alpha / 255;
695         ptr[2] = ptr[2] * alpha / 255;
696     }
697
698 done:
699     DeleteDC( hdc );
700     HeapFree( GetProcessHeap(), 0, info );
701     return alpha;
702 }
703
704
705 /***********************************************************************
706  *          create_icon_bitmaps
707  *
708  * Create the color, mask and alpha bitmaps from the DIB info.
709  */
710 static BOOL create_icon_bitmaps( const BITMAPINFO *bmi, int width, int height,
711                                  HBITMAP *color, HBITMAP *mask, HBITMAP *alpha )
712 {
713     BOOL monochrome = is_dib_monochrome( bmi );
714     unsigned int size = bitmap_info_size( bmi, DIB_RGB_COLORS );
715     BITMAPINFO *info;
716     const void *color_bits, *mask_bits;
717     BOOL ret = FALSE;
718     HDC hdc = 0;
719
720     if (!(info = HeapAlloc( GetProcessHeap(), 0, max( size, FIELD_OFFSET( BITMAPINFO, bmiColors[2] )))))
721         return FALSE;
722     if (!(hdc = CreateCompatibleDC( 0 ))) goto done;
723
724     memcpy( info, bmi, size );
725     info->bmiHeader.biHeight /= 2;
726
727     color_bits = (const char*)bmi + size;
728     mask_bits = (const char*)color_bits +
729         get_dib_width_bytes( bmi->bmiHeader.biWidth,
730                              bmi->bmiHeader.biBitCount ) * abs(info->bmiHeader.biHeight);
731
732     *alpha = 0;
733     if (monochrome)
734     {
735         if (!(*mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
736         *color = 0;
737
738         /* copy color data into second half of mask bitmap */
739         SelectObject( hdc, *mask );
740         StretchDIBits( hdc, 0, height, width, height,
741                        0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
742                        color_bits, info, DIB_RGB_COLORS, SRCCOPY );
743     }
744     else
745     {
746         if (!(*mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
747         if (!(*color = CreateBitmap( width, height, GetDeviceCaps( screen_dc, PLANES ),
748                                      GetDeviceCaps( screen_dc, BITSPIXEL ), NULL )))
749         {
750             DeleteObject( *mask );
751             goto done;
752         }
753         SelectObject( hdc, *color );
754         StretchDIBits( hdc, 0, 0, width, height,
755                        0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
756                        color_bits, info, DIB_RGB_COLORS, SRCCOPY );
757
758         if (bmi_has_alpha( info, color_bits ))
759             *alpha = create_alpha_bitmap( *color, *mask, info, color_bits );
760
761         /* convert info to monochrome to copy the mask */
762         info->bmiHeader.biBitCount = 1;
763         if (info->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
764         {
765             RGBQUAD *rgb = info->bmiColors;
766
767             info->bmiHeader.biClrUsed = info->bmiHeader.biClrImportant = 2;
768             rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
769             rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
770             rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
771         }
772         else
773         {
774             RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)info) + 1);
775
776             rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
777             rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
778         }
779     }
780
781     SelectObject( hdc, *mask );
782     StretchDIBits( hdc, 0, 0, width, height,
783                    0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
784                    mask_bits, info, DIB_RGB_COLORS, SRCCOPY );
785     ret = TRUE;
786
787 done:
788     DeleteDC( hdc );
789     HeapFree( GetProcessHeap(), 0, info );
790     return ret;
791 }
792
793 static HICON CURSORICON_CreateIconFromBMI( BITMAPINFO *bmi, HMODULE module, LPCWSTR resname, HRSRC rsrc,
794                                            POINT hotspot, BOOL bIcon, INT width, INT height, UINT cFlag )
795 {
796     HICON hObj;
797     HBITMAP color = 0, mask = 0, alpha = 0;
798     BOOL do_stretch;
799
800     /* Check bitmap header */
801
802     if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
803          (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER)  ||
804           bmi->bmiHeader.biCompression != BI_RGB) )
805     {
806           WARN_(cursor)("\tinvalid resource bitmap header.\n");
807           return 0;
808     }
809
810     if (cFlag & LR_DEFAULTSIZE)
811     {
812         if (!width) width = GetSystemMetrics( bIcon ? SM_CXICON : SM_CXCURSOR );
813         if (!height) height = GetSystemMetrics( bIcon ? SM_CYICON : SM_CYCURSOR );
814     }
815     else
816     {
817         if (!width) width = bmi->bmiHeader.biWidth;
818         if (!height) height = bmi->bmiHeader.biHeight/2;
819     }
820     do_stretch = (bmi->bmiHeader.biHeight/2 != height) ||
821                  (bmi->bmiHeader.biWidth != width);
822
823     /* Scale the hotspot */
824     if (bIcon)
825     {
826         hotspot.x = width / 2;
827         hotspot.y = height / 2;
828     }
829     else if (do_stretch)
830     {
831         hotspot.x = (hotspot.x * width) / bmi->bmiHeader.biWidth;
832         hotspot.y = (hotspot.y * height) / (bmi->bmiHeader.biHeight / 2);
833     }
834
835     if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
836     if (!screen_dc) return 0;
837
838     if (!create_icon_bitmaps( bmi, width, height, &color, &mask, &alpha )) return 0;
839
840     hObj = alloc_icon_handle(1);
841     if (hObj)
842     {
843         struct cursoricon_object *info = get_icon_ptr( hObj );
844
845         info->is_icon = bIcon;
846         info->module  = module;
847         info->hotspot = hotspot;
848         info->width   = width;
849         info->height  = height;
850         info->frames[0].color = color;
851         info->frames[0].mask  = mask;
852         info->frames[0].alpha = alpha;
853         if (!IS_INTRESOURCE(resname))
854         {
855             info->resname = HeapAlloc( GetProcessHeap(), 0, (strlenW(resname) + 1) * sizeof(WCHAR) );
856             if (info->resname) strcpyW( info->resname, resname );
857         }
858         else info->resname = MAKEINTRESOURCEW( LOWORD(resname) );
859
860         if (module && (cFlag & LR_SHARED))
861         {
862             info->rsrc = rsrc;
863             list_add_head( &icon_cache, &info->entry );
864         }
865         release_icon_ptr( hObj, info );
866         USER_Driver->pCreateCursorIcon( hObj );
867     }
868     else
869     {
870         DeleteObject( color );
871         DeleteObject( alpha );
872         DeleteObject( mask );
873     }
874     return hObj;
875 }
876
877
878 /**********************************************************************
879  *          .ANI cursor support
880  */
881 #define RIFF_FOURCC( c0, c1, c2, c3 ) \
882         ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
883         ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
884
885 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
886 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
887 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
888 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
889 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
890 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
891
892 #define ANI_FLAG_ICON       0x1
893 #define ANI_FLAG_SEQUENCE   0x2
894
895 typedef struct {
896     DWORD header_size;
897     DWORD num_frames;
898     DWORD num_steps;
899     DWORD width;
900     DWORD height;
901     DWORD bpp;
902     DWORD num_planes;
903     DWORD display_rate;
904     DWORD flags;
905 } ani_header;
906
907 typedef struct {
908     DWORD           data_size;
909     const unsigned char   *data;
910 } riff_chunk_t;
911
912 static void dump_ani_header( const ani_header *header )
913 {
914     TRACE("     header size: %d\n", header->header_size);
915     TRACE("          frames: %d\n", header->num_frames);
916     TRACE("           steps: %d\n", header->num_steps);
917     TRACE("           width: %d\n", header->width);
918     TRACE("          height: %d\n", header->height);
919     TRACE("             bpp: %d\n", header->bpp);
920     TRACE("          planes: %d\n", header->num_planes);
921     TRACE("    display rate: %d\n", header->display_rate);
922     TRACE("           flags: 0x%08x\n", header->flags);
923 }
924
925
926 /*
927  * RIFF:
928  * DWORD "RIFF"
929  * DWORD size
930  * DWORD riff_id
931  * BYTE[] data
932  *
933  * LIST:
934  * DWORD "LIST"
935  * DWORD size
936  * DWORD list_id
937  * BYTE[] data
938  *
939  * CHUNK:
940  * DWORD chunk_id
941  * DWORD size
942  * BYTE[] data
943  */
944 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
945 {
946     const unsigned char *ptr = parent_chunk->data;
947     const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
948
949     if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
950
951     while (ptr < end)
952     {
953         if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
954                 || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
955         {
956             ptr += sizeof(DWORD);
957             chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
958             ptr += sizeof(DWORD);
959             if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
960             chunk->data = ptr;
961
962             return;
963         }
964
965         ptr += sizeof(DWORD);
966         ptr += (*(const DWORD *)ptr + 1) & ~1;
967         ptr += sizeof(DWORD);
968     }
969 }
970
971
972 /*
973  * .ANI layout:
974  *
975  * RIFF:'ACON'                  RIFF chunk
976  *     |- CHUNK:'anih'          Header
977  *     |- CHUNK:'seq '          Sequence information (optional)
978  *     \- LIST:'fram'           Frame list
979  *            |- CHUNK:icon     Cursor frames
980  *            |- CHUNK:icon
981  *            |- ...
982  *            \- CHUNK:icon
983  */
984 static HCURSOR CURSORICON_CreateIconFromANI( const LPBYTE bits, DWORD bits_size,
985                                              INT width, INT height, INT depth, UINT loadflags )
986 {
987     struct cursoricon_object *info;
988     ani_header header = {0};
989     HCURSOR cursor = 0;
990     UINT i, error = 0;
991
992     riff_chunk_t root_chunk = { bits_size, bits };
993     riff_chunk_t ACON_chunk = {0};
994     riff_chunk_t anih_chunk = {0};
995     riff_chunk_t fram_chunk = {0};
996     const unsigned char *icon_chunk;
997     const unsigned char *icon_data;
998
999     TRACE("bits %p, bits_size %d\n", bits, bits_size);
1000
1001     riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1002     if (!ACON_chunk.data)
1003     {
1004         ERR("Failed to get root chunk.\n");
1005         return 0;
1006     }
1007
1008     riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1009     if (!anih_chunk.data)
1010     {
1011         ERR("Failed to get 'anih' chunk.\n");
1012         return 0;
1013     }
1014     memcpy( &header, anih_chunk.data, sizeof(header) );
1015     dump_ani_header( &header );
1016
1017     riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1018     if (!fram_chunk.data)
1019     {
1020         ERR("Failed to get icon list.\n");
1021         return 0;
1022     }
1023
1024     cursor = alloc_icon_handle( header.num_frames );
1025     if (!cursor) return 0;
1026
1027     info = get_icon_ptr( cursor );
1028     info->is_icon = FALSE;
1029
1030     /* The .ANI stores the display rate in 1/60s, we store the delay between frames in ms */
1031     info->ms_delay = (100 * header.display_rate) / 6;
1032
1033     icon_chunk = fram_chunk.data;
1034     icon_data = fram_chunk.data + (2 * sizeof(DWORD));
1035     for (i=0; i<header.num_frames; i++)
1036     {
1037         const DWORD chunk_size = *(const DWORD *)(icon_chunk + sizeof(DWORD));
1038         struct cursoricon_frame *frame = &info->frames[i];
1039         const CURSORICONFILEDIRENTRY *entry;
1040         const BITMAPINFO *bmi;
1041
1042         entry = CURSORICON_FindBestIconFile((const CURSORICONFILEDIR *) icon_data,
1043                                             width, height, depth, loadflags );
1044
1045         bmi = (const BITMAPINFO *) (icon_data + entry->dwDIBOffset);
1046         info->hotspot.x = entry->xHotspot;
1047         info->hotspot.y = entry->yHotspot;
1048         if (!header.width || !header.height)
1049         {
1050             header.width = entry->bWidth;
1051             header.height = entry->bHeight;
1052         }
1053
1054         /* Grab a frame from the animation */
1055         if (!create_icon_bitmaps( bmi, header.width, header.height,
1056             &frame->color, &frame->mask, &frame->alpha ))
1057         {
1058             FIXME_(cursor)("failed to convert animated cursor frame.\n");
1059             error = TRUE;
1060             if (i == 0)
1061             {
1062                 FIXME_(cursor)("Completely failed to create animated cursor!\n");
1063                 info->num_frames = 0;
1064                 release_icon_ptr( cursor, info );
1065                 free_icon_handle( cursor );
1066                 return 0;
1067             }
1068             break;
1069         }
1070
1071         /* Advance to the next chunk */
1072         icon_chunk += chunk_size + (2 * sizeof(DWORD));
1073         icon_data = icon_chunk + (2 * sizeof(DWORD));
1074     }
1075
1076     /* There was an error but we at least decoded the first frame, so just use that frame */
1077     if (error)
1078     {
1079         FIXME_(cursor)("Error creating animated cursor, only using first frame!\n");
1080         for (i=1; i<info->num_frames; i++)
1081         {
1082             if (info->frames[i].mask) DeleteObject( info->frames[i].mask );
1083             if (info->frames[i].color) DeleteObject( info->frames[i].color );
1084             if (info->frames[i].alpha) DeleteObject( info->frames[i].alpha );
1085         }
1086         info->num_frames = 1;
1087         info->ms_delay = 0;
1088     }
1089     info->width = header.width;
1090     info->height = header.height;
1091     release_icon_ptr( cursor, info );
1092
1093     return cursor;
1094 }
1095
1096
1097 /**********************************************************************
1098  *              CreateIconFromResourceEx (USER32.@)
1099  *
1100  * FIXME: Convert to mono when cFlag is LR_MONOCHROME. Do something
1101  *        with cbSize parameter as well.
1102  */
1103 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1104                                        BOOL bIcon, DWORD dwVersion,
1105                                        INT width, INT height,
1106                                        UINT cFlag )
1107 {
1108     POINT hotspot;
1109     BITMAPINFO *bmi;
1110
1111     TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s %s\n",
1112                    bits, cbSize, dwVersion, width, height,
1113                    bIcon ? "icon" : "cursor", (cFlag & LR_MONOCHROME) ? "mono" : "" );
1114
1115     if (!bits) return 0;
1116
1117     if (dwVersion == 0x00020000)
1118     {
1119         FIXME_(cursor)("\t2.xx resources are not supported\n");
1120         return 0;
1121     }
1122
1123     if (bIcon)
1124     {
1125         hotspot.x = width / 2;
1126         hotspot.y = height / 2;
1127         bmi = (BITMAPINFO *)bits;
1128     }
1129     else /* get the hotspot */
1130     {
1131         SHORT *pt = (SHORT *)bits;
1132         hotspot.x = pt[0];
1133         hotspot.y = pt[1];
1134         bmi = (BITMAPINFO *)(pt + 2);
1135     }
1136
1137     return CURSORICON_CreateIconFromBMI( bmi, NULL, NULL, NULL, hotspot, bIcon, width, height, cFlag );
1138 }
1139
1140
1141 /**********************************************************************
1142  *              CreateIconFromResource (USER32.@)
1143  */
1144 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1145                                            BOOL bIcon, DWORD dwVersion)
1146 {
1147     return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
1148 }
1149
1150
1151 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1152                              INT width, INT height, INT depth,
1153                              BOOL fCursor, UINT loadflags)
1154 {
1155     const CURSORICONFILEDIRENTRY *entry;
1156     const CURSORICONFILEDIR *dir;
1157     DWORD filesize = 0;
1158     HICON hIcon = 0;
1159     LPBYTE bits;
1160     POINT hotspot;
1161
1162     TRACE("loading %s\n", debugstr_w( filename ));
1163
1164     bits = map_fileW( filename, &filesize );
1165     if (!bits)
1166         return hIcon;
1167
1168     /* Check for .ani. */
1169     if (memcmp( bits, "RIFF", 4 ) == 0)
1170     {
1171         hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height, depth, loadflags );
1172         goto end;
1173     }
1174
1175     dir = (const CURSORICONFILEDIR*) bits;
1176     if ( filesize < sizeof(*dir) )
1177         goto end;
1178
1179     if ( filesize < (sizeof(*dir) + sizeof(dir->idEntries[0])*(dir->idCount-1)) )
1180         goto end;
1181
1182     if ( fCursor )
1183         entry = CURSORICON_FindBestCursorFile( dir, width, height, depth, loadflags );
1184     else
1185         entry = CURSORICON_FindBestIconFile( dir, width, height, depth, loadflags );
1186
1187     if ( !entry )
1188         goto end;
1189
1190     /* check that we don't run off the end of the file */
1191     if ( entry->dwDIBOffset > filesize )
1192         goto end;
1193     if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1194         goto end;
1195
1196     hotspot.x = entry->xHotspot;
1197     hotspot.y = entry->yHotspot;
1198     hIcon = CURSORICON_CreateIconFromBMI( (BITMAPINFO *)&bits[entry->dwDIBOffset], NULL, NULL, NULL,
1199                                           hotspot, !fCursor, width, height, loadflags );
1200 end:
1201     TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1202     UnmapViewOfFile( bits );
1203     return hIcon;
1204 }
1205
1206 /**********************************************************************
1207  *          CURSORICON_Load
1208  *
1209  * Load a cursor or icon from resource or file.
1210  */
1211 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1212                              INT width, INT height, INT depth,
1213                              BOOL fCursor, UINT loadflags)
1214 {
1215     HANDLE handle = 0;
1216     HICON hIcon = 0;
1217     HRSRC hRsrc;
1218     const CURSORICONDIR *dir;
1219     const CURSORICONDIRENTRY *dirEntry;
1220     LPBYTE bits;
1221     WORD wResId;
1222     POINT hotspot;
1223
1224     TRACE("%p, %s, %dx%d, depth %d, fCursor %d, flags 0x%04x\n",
1225           hInstance, debugstr_w(name), width, height, depth, fCursor, loadflags);
1226
1227     if ( loadflags & LR_LOADFROMFILE )    /* Load from file */
1228         return CURSORICON_LoadFromFile( name, width, height, depth, fCursor, loadflags );
1229
1230     if (!hInstance) hInstance = user32_module;  /* Load OEM cursor/icon */
1231
1232     /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1233     if ((ULONG_PTR)hInstance >> 16 == 0) loadflags &= ~LR_SHARED;
1234
1235     /* Get directory resource ID */
1236
1237     if (!(hRsrc = FindResourceW( hInstance, name,
1238                                  (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1239         return 0;
1240
1241     /* Find the best entry in the directory */
1242
1243     if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1244     if (!(dir = LockResource( handle ))) return 0;
1245     if (fCursor)
1246         dirEntry = CURSORICON_FindBestCursorRes( dir, width, height, depth, loadflags );
1247     else
1248         dirEntry = CURSORICON_FindBestIconRes( dir, width, height, depth, loadflags );
1249     if (!dirEntry) return 0;
1250     wResId = dirEntry->wResId;
1251     FreeResource( handle );
1252
1253     /* Load the resource */
1254
1255     if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1256                                 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1257
1258     /* If shared icon, check whether it was already loaded */
1259     if (loadflags & LR_SHARED)
1260     {
1261         struct cursoricon_object *ptr;
1262
1263         USER_Lock();
1264         LIST_FOR_EACH_ENTRY( ptr, &icon_cache, struct cursoricon_object, entry )
1265         {
1266             if (ptr->module != hInstance) continue;
1267             if (ptr->rsrc != hRsrc) continue;
1268             hIcon = ptr->obj.handle;
1269             break;
1270         }
1271         USER_Unlock();
1272         if (hIcon) return hIcon;
1273     }
1274
1275     if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1276     bits = LockResource( handle );
1277
1278     if (!fCursor)
1279     {
1280         hotspot.x = width / 2;
1281         hotspot.y = height / 2;
1282     }
1283     else /* get the hotspot */
1284     {
1285         SHORT *pt = (SHORT *)bits;
1286         hotspot.x = pt[0];
1287         hotspot.y = pt[1];
1288         bits += 2 * sizeof(SHORT);
1289     }
1290     hIcon = CURSORICON_CreateIconFromBMI( (BITMAPINFO *)bits, hInstance, name, hRsrc,
1291                                           hotspot, !fCursor, width, height, loadflags );
1292     FreeResource( handle );
1293     return hIcon;
1294 }
1295
1296
1297 /***********************************************************************
1298  *              CreateCursor (USER32.@)
1299  */
1300 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
1301                                  INT xHotSpot, INT yHotSpot,
1302                                  INT nWidth, INT nHeight,
1303                                  LPCVOID lpANDbits, LPCVOID lpXORbits )
1304 {
1305     ICONINFO info;
1306     HCURSOR hCursor;
1307
1308     TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
1309                     nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1310
1311     info.fIcon = FALSE;
1312     info.xHotspot = xHotSpot;
1313     info.yHotspot = yHotSpot;
1314     info.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1315     info.hbmColor = CreateBitmap( nWidth, nHeight, 1, 1, lpXORbits );
1316     hCursor = CreateIconIndirect( &info );
1317     DeleteObject( info.hbmMask );
1318     DeleteObject( info.hbmColor );
1319     return hCursor;
1320 }
1321
1322
1323 /***********************************************************************
1324  *              CreateIcon (USER32.@)
1325  *
1326  *  Creates an icon based on the specified bitmaps. The bitmaps must be
1327  *  provided in a device dependent format and will be resized to
1328  *  (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1329  *  depth. The provided bitmaps must be top-down bitmaps.
1330  *  Although Windows does not support 15bpp(*) this API must support it
1331  *  for Winelib applications.
1332  *
1333  *  (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1334  *      format!
1335  *
1336  * RETURNS
1337  *  Success: handle to an icon
1338  *  Failure: NULL
1339  *
1340  * FIXME: Do we need to resize the bitmaps?
1341  */
1342 HICON WINAPI CreateIcon(
1343     HINSTANCE hInstance,  /* [in] the application's hInstance */
1344     INT       nWidth,     /* [in] the width of the provided bitmaps */
1345     INT       nHeight,    /* [in] the height of the provided bitmaps */
1346     BYTE      bPlanes,    /* [in] the number of planes in the provided bitmaps */
1347     BYTE      bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1348     LPCVOID   lpANDbits,  /* [in] a monochrome bitmap representing the icon's mask */
1349     LPCVOID   lpXORbits)  /* [in] the icon's 'color' bitmap */
1350 {
1351     ICONINFO iinfo;
1352     HICON hIcon;
1353
1354     TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
1355                  nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1356
1357     iinfo.fIcon = TRUE;
1358     iinfo.xHotspot = nWidth / 2;
1359     iinfo.yHotspot = nHeight / 2;
1360     iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1361     iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );
1362
1363     hIcon = CreateIconIndirect( &iinfo );
1364
1365     DeleteObject( iinfo.hbmMask );
1366     DeleteObject( iinfo.hbmColor );
1367
1368     return hIcon;
1369 }
1370
1371
1372 /***********************************************************************
1373  *              CopyIcon (USER32.@)
1374  */
1375 HICON WINAPI CopyIcon( HICON hIcon )
1376 {
1377     struct cursoricon_object *ptrOld, *ptrNew;
1378     HICON hNew;
1379
1380     if (!(ptrOld = get_icon_ptr( hIcon )))
1381     {
1382         SetLastError( ERROR_INVALID_CURSOR_HANDLE );
1383         return 0;
1384     }
1385     if ((hNew = alloc_icon_handle(1)))
1386     {
1387         ptrNew = get_icon_ptr( hNew );
1388         ptrNew->is_icon = ptrOld->is_icon;
1389         ptrNew->width   = ptrOld->width;
1390         ptrNew->height  = ptrOld->height;
1391         ptrNew->hotspot = ptrOld->hotspot;
1392         ptrNew->frames[0].mask  = copy_bitmap( ptrOld->frames[0].mask );
1393         ptrNew->frames[0].color = copy_bitmap( ptrOld->frames[0].color );
1394         ptrNew->frames[0].alpha = copy_bitmap( ptrOld->frames[0].alpha );
1395         release_icon_ptr( hNew, ptrNew );
1396     }
1397     release_icon_ptr( hIcon, ptrOld );
1398     if (hNew) USER_Driver->pCreateCursorIcon( hNew );
1399     return hNew;
1400 }
1401
1402
1403 /***********************************************************************
1404  *              DestroyIcon (USER32.@)
1405  */
1406 BOOL WINAPI DestroyIcon( HICON hIcon )
1407 {
1408     BOOL ret = FALSE;
1409     struct cursoricon_object *obj = get_icon_ptr( hIcon );
1410
1411     TRACE_(icon)("%p\n", hIcon );
1412
1413     if (obj)
1414     {
1415         BOOL shared = (obj->rsrc != NULL);
1416         release_icon_ptr( hIcon, obj );
1417         ret = (GetCursor() != hIcon);
1418         if (!shared) free_icon_handle( hIcon );
1419     }
1420     return ret;
1421 }
1422
1423
1424 /***********************************************************************
1425  *              DestroyCursor (USER32.@)
1426  */
1427 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
1428 {
1429     return DestroyIcon( hCursor );
1430 }
1431
1432 /***********************************************************************
1433  *              DrawIcon (USER32.@)
1434  */
1435 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
1436 {
1437     return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
1438 }
1439
1440 /***********************************************************************
1441  *              SetCursor (USER32.@)
1442  *
1443  * Set the cursor shape.
1444  *
1445  * RETURNS
1446  *      A handle to the previous cursor shape.
1447  */
1448 HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1449 {
1450     struct cursoricon_object *obj;
1451     HCURSOR hOldCursor;
1452     int show_count;
1453     BOOL ret;
1454
1455     TRACE("%p\n", hCursor);
1456
1457     SERVER_START_REQ( set_cursor )
1458     {
1459         req->flags = SET_CURSOR_HANDLE;
1460         req->handle = wine_server_user_handle( hCursor );
1461         if ((ret = !wine_server_call_err( req )))
1462         {
1463             hOldCursor = wine_server_ptr_handle( reply->prev_handle );
1464             show_count = reply->prev_count;
1465         }
1466     }
1467     SERVER_END_REQ;
1468
1469     if (!ret) return 0;
1470
1471     /* Change the cursor shape only if it is visible */
1472     if (show_count >= 0 && hOldCursor != hCursor) USER_Driver->pSetCursor( hCursor );
1473
1474     if (!(obj = get_icon_ptr( hOldCursor ))) return 0;
1475     release_icon_ptr( hOldCursor, obj );
1476     return hOldCursor;
1477 }
1478
1479 /***********************************************************************
1480  *              ShowCursor (USER32.@)
1481  */
1482 INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
1483 {
1484     HCURSOR cursor;
1485     int increment = bShow ? 1 : -1;
1486     int count;
1487
1488     SERVER_START_REQ( set_cursor )
1489     {
1490         req->flags = SET_CURSOR_COUNT;
1491         req->show_count = increment;
1492         wine_server_call( req );
1493         cursor = wine_server_ptr_handle( reply->prev_handle );
1494         count = reply->prev_count + increment;
1495     }
1496     SERVER_END_REQ;
1497
1498     TRACE("%d, count=%d\n", bShow, count );
1499
1500     if (bShow && !count) USER_Driver->pSetCursor( cursor );
1501     else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
1502
1503     return count;
1504 }
1505
1506 /***********************************************************************
1507  *              GetCursor (USER32.@)
1508  */
1509 HCURSOR WINAPI GetCursor(void)
1510 {
1511     HCURSOR ret;
1512
1513     SERVER_START_REQ( set_cursor )
1514     {
1515         req->flags = 0;
1516         wine_server_call( req );
1517         ret = wine_server_ptr_handle( reply->prev_handle );
1518     }
1519     SERVER_END_REQ;
1520     return ret;
1521 }
1522
1523
1524 /***********************************************************************
1525  *              ClipCursor (USER32.@)
1526  */
1527 BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
1528 {
1529     RECT virt;
1530
1531     SetRect( &virt, 0, 0, GetSystemMetrics( SM_CXVIRTUALSCREEN ),
1532                           GetSystemMetrics( SM_CYVIRTUALSCREEN ) );
1533     OffsetRect( &virt, GetSystemMetrics( SM_XVIRTUALSCREEN ),
1534                        GetSystemMetrics( SM_YVIRTUALSCREEN ) );
1535
1536     TRACE( "Clipping to: %s was: %s screen: %s\n", wine_dbgstr_rect(rect),
1537            wine_dbgstr_rect(&CURSOR_ClipRect), wine_dbgstr_rect(&virt) );
1538
1539     if (!IntersectRect( &CURSOR_ClipRect, &virt, rect ))
1540         CURSOR_ClipRect = virt;
1541
1542     USER_Driver->pClipCursor( rect );
1543     return TRUE;
1544 }
1545
1546
1547 /***********************************************************************
1548  *              GetClipCursor (USER32.@)
1549  */
1550 BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
1551 {
1552     /* If this is first time - initialize the rect */
1553     if (IsRectEmpty( &CURSOR_ClipRect )) ClipCursor( NULL );
1554
1555     return CopyRect( rect, &CURSOR_ClipRect );
1556 }
1557
1558
1559 /***********************************************************************
1560  *              SetSystemCursor (USER32.@)
1561  */
1562 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
1563 {
1564     FIXME("(%p,%08x),stub!\n",  hcur, id);
1565     return TRUE;
1566 }
1567
1568
1569 /**********************************************************************
1570  *              LookupIconIdFromDirectoryEx (USER32.@)
1571  */
1572 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
1573              INT width, INT height, UINT cFlag )
1574 {
1575     const CURSORICONDIR *dir = (const CURSORICONDIR*)xdir;
1576     UINT retVal = 0;
1577     if( dir && !dir->idReserved && (dir->idType & 3) )
1578     {
1579         const CURSORICONDIRENTRY* entry;
1580
1581         const HDC hdc = GetDC(0);
1582         const int depth = (cFlag & LR_MONOCHROME) ?
1583             1 : GetDeviceCaps(hdc, BITSPIXEL);
1584         ReleaseDC(0, hdc);
1585
1586         if( bIcon )
1587             entry = CURSORICON_FindBestIconRes( dir, width, height, depth, LR_DEFAULTSIZE );
1588         else
1589             entry = CURSORICON_FindBestCursorRes( dir, width, height, depth, LR_DEFAULTSIZE );
1590
1591         if( entry ) retVal = entry->wResId;
1592     }
1593     else WARN_(cursor)("invalid resource directory\n");
1594     return retVal;
1595 }
1596
1597 /**********************************************************************
1598  *              LookupIconIdFromDirectory (USER32.@)
1599  */
1600 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
1601 {
1602     return LookupIconIdFromDirectoryEx( dir, bIcon, 0, 0, bIcon ? 0 : LR_MONOCHROME );
1603 }
1604
1605 /***********************************************************************
1606  *              LoadCursorW (USER32.@)
1607  */
1608 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
1609 {
1610     TRACE("%p, %s\n", hInstance, debugstr_w(name));
1611
1612     return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1613                        LR_SHARED | LR_DEFAULTSIZE );
1614 }
1615
1616 /***********************************************************************
1617  *              LoadCursorA (USER32.@)
1618  */
1619 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
1620 {
1621     TRACE("%p, %s\n", hInstance, debugstr_a(name));
1622
1623     return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1624                        LR_SHARED | LR_DEFAULTSIZE );
1625 }
1626
1627 /***********************************************************************
1628  *              LoadCursorFromFileW (USER32.@)
1629  */
1630 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1631 {
1632     TRACE("%s\n", debugstr_w(name));
1633
1634     return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1635                        LR_LOADFROMFILE | LR_DEFAULTSIZE );
1636 }
1637
1638 /***********************************************************************
1639  *              LoadCursorFromFileA (USER32.@)
1640  */
1641 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1642 {
1643     TRACE("%s\n", debugstr_a(name));
1644
1645     return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1646                        LR_LOADFROMFILE | LR_DEFAULTSIZE );
1647 }
1648
1649 /***********************************************************************
1650  *              LoadIconW (USER32.@)
1651  */
1652 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
1653 {
1654     TRACE("%p, %s\n", hInstance, debugstr_w(name));
1655
1656     return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1657                        LR_SHARED | LR_DEFAULTSIZE );
1658 }
1659
1660 /***********************************************************************
1661  *              LoadIconA (USER32.@)
1662  */
1663 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
1664 {
1665     TRACE("%p, %s\n", hInstance, debugstr_a(name));
1666
1667     return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1668                        LR_SHARED | LR_DEFAULTSIZE );
1669 }
1670
1671 /**********************************************************************
1672  *              GetIconInfo (USER32.@)
1673  */
1674 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
1675 {
1676     ICONINFOEXW infoW;
1677
1678     infoW.cbSize = sizeof(infoW);
1679     if (!GetIconInfoExW( hIcon, &infoW )) return FALSE;
1680     iconinfo->fIcon    = infoW.fIcon;
1681     iconinfo->xHotspot = infoW.xHotspot;
1682     iconinfo->yHotspot = infoW.yHotspot;
1683     iconinfo->hbmColor = infoW.hbmColor;
1684     iconinfo->hbmMask  = infoW.hbmMask;
1685     return TRUE;
1686 }
1687
1688 /**********************************************************************
1689  *              GetIconInfoExA (USER32.@)
1690  */
1691 BOOL WINAPI GetIconInfoExA( HICON icon, ICONINFOEXA *info )
1692 {
1693     ICONINFOEXW infoW;
1694
1695     if (info->cbSize != sizeof(*info))
1696     {
1697         SetLastError( ERROR_INVALID_PARAMETER );
1698         return FALSE;
1699     }
1700     infoW.cbSize = sizeof(infoW);
1701     if (!GetIconInfoExW( icon, &infoW )) return FALSE;
1702     info->fIcon    = infoW.fIcon;
1703     info->xHotspot = infoW.xHotspot;
1704     info->yHotspot = infoW.yHotspot;
1705     info->hbmColor = infoW.hbmColor;
1706     info->hbmMask  = infoW.hbmMask;
1707     info->wResID   = infoW.wResID;
1708     WideCharToMultiByte( CP_ACP, 0, infoW.szModName, -1, info->szModName, MAX_PATH, NULL, NULL );
1709     WideCharToMultiByte( CP_ACP, 0, infoW.szResName, -1, info->szResName, MAX_PATH, NULL, NULL );
1710     return TRUE;
1711 }
1712
1713 /**********************************************************************
1714  *              GetIconInfoExW (USER32.@)
1715  */
1716 BOOL WINAPI GetIconInfoExW( HICON icon, ICONINFOEXW *info )
1717 {
1718     struct cursoricon_object *ptr;
1719     HMODULE module;
1720     BOOL ret = TRUE;
1721
1722     if (info->cbSize != sizeof(*info))
1723     {
1724         SetLastError( ERROR_INVALID_PARAMETER );
1725         return FALSE;
1726     }
1727     if (!(ptr = get_icon_ptr( icon )))
1728     {
1729         SetLastError( ERROR_INVALID_CURSOR_HANDLE );
1730         return FALSE;
1731     }
1732
1733     TRACE("%p => %dx%d\n", icon, ptr->width, ptr->height);
1734
1735     info->fIcon        = ptr->is_icon;
1736     info->xHotspot     = ptr->hotspot.x;
1737     info->yHotspot     = ptr->hotspot.y;
1738     info->hbmColor     = copy_bitmap( ptr->frames[0].color );
1739     info->hbmMask      = copy_bitmap( ptr->frames[0].mask );
1740     info->wResID       = 0;
1741     info->szModName[0] = 0;
1742     info->szResName[0] = 0;
1743     if (ptr->module)
1744     {
1745         if (IS_INTRESOURCE( ptr->resname )) info->wResID = LOWORD( ptr->resname );
1746         else lstrcpynW( info->szResName, ptr->resname, MAX_PATH );
1747     }
1748     if (!info->hbmMask || (!info->hbmColor && ptr->frames[0].color))
1749     {
1750         DeleteObject( info->hbmMask );
1751         DeleteObject( info->hbmColor );
1752         ret = FALSE;
1753     }
1754     module = ptr->module;
1755     release_icon_ptr( icon, ptr );
1756     if (ret && module) GetModuleFileNameW( module, info->szModName, MAX_PATH );
1757     return ret;
1758 }
1759
1760 /* copy an icon bitmap, even when it can't be selected into a DC */
1761 /* helper for CreateIconIndirect */
1762 static void stretch_blt_icon( HDC hdc_dst, int dst_x, int dst_y, int dst_width, int dst_height,
1763                               HBITMAP src, int width, int height )
1764 {
1765     HDC hdc = CreateCompatibleDC( 0 );
1766
1767     if (!SelectObject( hdc, src ))  /* do it the hard way */
1768     {
1769         BITMAPINFO *info;
1770         void *bits;
1771
1772         if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) return;
1773         info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1774         info->bmiHeader.biWidth = width;
1775         info->bmiHeader.biHeight = height;
1776         info->bmiHeader.biPlanes = GetDeviceCaps( hdc_dst, PLANES );
1777         info->bmiHeader.biBitCount = GetDeviceCaps( hdc_dst, BITSPIXEL );
1778         info->bmiHeader.biCompression = BI_RGB;
1779         info->bmiHeader.biSizeImage = height * get_dib_width_bytes( width, info->bmiHeader.biBitCount );
1780         info->bmiHeader.biXPelsPerMeter = 0;
1781         info->bmiHeader.biYPelsPerMeter = 0;
1782         info->bmiHeader.biClrUsed = 0;
1783         info->bmiHeader.biClrImportant = 0;
1784         bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
1785         if (bits && GetDIBits( hdc, src, 0, height, bits, info, DIB_RGB_COLORS ))
1786             StretchDIBits( hdc_dst, dst_x, dst_y, dst_width, dst_height,
1787                            0, 0, width, height, bits, info, DIB_RGB_COLORS, SRCCOPY );
1788
1789         HeapFree( GetProcessHeap(), 0, bits );
1790         HeapFree( GetProcessHeap(), 0, info );
1791     }
1792     else StretchBlt( hdc_dst, dst_x, dst_y, dst_width, dst_height, hdc, 0, 0, width, height, SRCCOPY );
1793
1794     DeleteDC( hdc );
1795 }
1796
1797 /**********************************************************************
1798  *              CreateIconIndirect (USER32.@)
1799  */
1800 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
1801 {
1802     BITMAP bmpXor, bmpAnd;
1803     HICON hObj;
1804     HBITMAP color = 0, mask;
1805     int width, height;
1806     HDC hdc;
1807
1808     TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
1809            iconinfo->hbmColor, iconinfo->hbmMask,
1810            iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
1811
1812     if (!iconinfo->hbmMask) return 0;
1813
1814     GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
1815     TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
1816            bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
1817            bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
1818
1819     if (iconinfo->hbmColor)
1820     {
1821         GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
1822         TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
1823                bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
1824                bmpXor.bmPlanes, bmpXor.bmBitsPixel);
1825
1826         width = bmpXor.bmWidth;
1827         height = bmpXor.bmHeight;
1828         if (bmpXor.bmPlanes * bmpXor.bmBitsPixel != 1)
1829         {
1830             color = CreateCompatibleBitmap( screen_dc, width, height );
1831             mask = CreateBitmap( width, height, 1, 1, NULL );
1832         }
1833         else mask = CreateBitmap( width, height * 2, 1, 1, NULL );
1834     }
1835     else
1836     {
1837         width = bmpAnd.bmWidth;
1838         height = bmpAnd.bmHeight;
1839         mask = CreateBitmap( width, height, 1, 1, NULL );
1840     }
1841
1842     hdc = CreateCompatibleDC( 0 );
1843     SelectObject( hdc, mask );
1844     stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
1845
1846     if (color)
1847     {
1848         SelectObject( hdc, color );
1849         stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
1850     }
1851     else if (iconinfo->hbmColor)
1852     {
1853         stretch_blt_icon( hdc, 0, height, width, height, iconinfo->hbmColor, width, height );
1854     }
1855     else height /= 2;
1856
1857     DeleteDC( hdc );
1858
1859     hObj = alloc_icon_handle(1);
1860     if (hObj)
1861     {
1862         struct cursoricon_object *info = get_icon_ptr( hObj );
1863
1864         info->is_icon = iconinfo->fIcon;
1865         info->width   = width;
1866         info->height  = height;
1867         info->frames[0].color = color;
1868         info->frames[0].mask  = mask;
1869         info->frames[0].alpha = create_alpha_bitmap( iconinfo->hbmColor, mask, NULL, NULL );
1870         if (info->is_icon)
1871         {
1872             info->hotspot.x = width / 2;
1873             info->hotspot.y = height / 2;
1874         }
1875         else
1876         {
1877             info->hotspot.x = iconinfo->xHotspot;
1878             info->hotspot.y = iconinfo->yHotspot;
1879         }
1880
1881         release_icon_ptr( hObj, info );
1882         USER_Driver->pCreateCursorIcon( hObj );
1883     }
1884     return hObj;
1885 }
1886
1887 /******************************************************************************
1888  *              DrawIconEx (USER32.@) Draws an icon or cursor on device context
1889  *
1890  * NOTES
1891  *    Why is this using SM_CXICON instead of SM_CXCURSOR?
1892  *
1893  * PARAMS
1894  *    hdc     [I] Handle to device context
1895  *    x0      [I] X coordinate of upper left corner
1896  *    y0      [I] Y coordinate of upper left corner
1897  *    hIcon   [I] Handle to icon to draw
1898  *    cxWidth [I] Width of icon
1899  *    cyWidth [I] Height of icon
1900  *    istep   [I] Index of frame in animated cursor
1901  *    hbr     [I] Handle to background brush
1902  *    flags   [I] Icon-drawing flags
1903  *
1904  * RETURNS
1905  *    Success: TRUE
1906  *    Failure: FALSE
1907  */
1908 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
1909                             INT cxWidth, INT cyWidth, UINT istep,
1910                             HBRUSH hbr, UINT flags )
1911 {
1912     struct cursoricon_object *ptr;
1913     HDC hdc_dest, hMemDC;
1914     BOOL result = FALSE, DoOffscreen;
1915     HBITMAP hB_off = 0;
1916     COLORREF oldFg, oldBg;
1917     INT x, y, nStretchMode;
1918
1919     TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
1920                  hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
1921
1922     if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
1923     if (istep >= ptr->num_frames)
1924     {
1925         TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
1926         release_icon_ptr( hIcon, ptr );
1927         return FALSE;
1928     }
1929     if (!(hMemDC = CreateCompatibleDC( hdc )))
1930     {
1931         release_icon_ptr( hIcon, ptr );
1932         return FALSE;
1933     }
1934
1935     if (flags & DI_NOMIRROR)
1936         FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
1937
1938     /* Calculate the size of the destination image.  */
1939     if (cxWidth == 0)
1940     {
1941         if (flags & DI_DEFAULTSIZE)
1942             cxWidth = GetSystemMetrics (SM_CXICON);
1943         else
1944             cxWidth = ptr->width;
1945     }
1946     if (cyWidth == 0)
1947     {
1948         if (flags & DI_DEFAULTSIZE)
1949             cyWidth = GetSystemMetrics (SM_CYICON);
1950         else
1951             cyWidth = ptr->height;
1952     }
1953
1954     DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
1955
1956     if (DoOffscreen) {
1957         RECT r;
1958
1959         r.left = 0;
1960         r.top = 0;
1961         r.right = cxWidth;
1962         r.bottom = cxWidth;
1963
1964         if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
1965         if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
1966         {
1967             DeleteDC( hdc_dest );
1968             goto failed;
1969         }
1970         SelectObject(hdc_dest, hB_off);
1971         FillRect(hdc_dest, &r, hbr);
1972         x = y = 0;
1973     }
1974     else
1975     {
1976         hdc_dest = hdc;
1977         x = x0;
1978         y = y0;
1979     }
1980
1981     nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
1982
1983     oldFg = SetTextColor( hdc, RGB(0,0,0) );
1984     oldBg = SetBkColor( hdc, RGB(255,255,255) );
1985
1986     if (ptr->frames[istep].alpha && (flags & DI_IMAGE))
1987     {
1988         BOOL is_mono = FALSE;
1989
1990         if (GetObjectType( hdc_dest ) == OBJ_MEMDC)
1991         {
1992             BITMAP bm;
1993             HBITMAP bmp = GetCurrentObject( hdc_dest, OBJ_BITMAP );
1994             is_mono = GetObjectW( bmp, sizeof(bm), &bm ) && bm.bmBitsPixel == 1;
1995         }
1996         if (!is_mono)
1997         {
1998             BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
1999             SelectObject( hMemDC, ptr->frames[istep].alpha );
2000             if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
2001                                0, 0, ptr->width, ptr->height, pixelblend )) goto done;
2002         }
2003     }
2004
2005     if (flags & DI_MASK)
2006     {
2007         SelectObject( hMemDC, ptr->frames[istep].mask );
2008         StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2009                     hMemDC, 0, 0, ptr->width, ptr->height, SRCAND );
2010     }
2011
2012     if (flags & DI_IMAGE)
2013     {
2014         if (ptr->frames[istep].color)
2015         {
2016             DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2017             SelectObject( hMemDC, ptr->frames[istep].color );
2018             StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2019                         hMemDC, 0, 0, ptr->width, ptr->height, rop );
2020         }
2021         else
2022         {
2023             DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2024             SelectObject( hMemDC, ptr->frames[istep].mask );
2025             StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2026                         hMemDC, 0, ptr->height, ptr->width, ptr->height, rop );
2027         }
2028     }
2029
2030 done:
2031     if (DoOffscreen) BitBlt( hdc, x0, y0, cxWidth, cyWidth, hdc_dest, 0, 0, SRCCOPY );
2032
2033     SetTextColor( hdc, oldFg );
2034     SetBkColor( hdc, oldBg );
2035     SetStretchBltMode (hdc, nStretchMode);
2036     result = TRUE;
2037     if (hdc_dest != hdc) DeleteDC( hdc_dest );
2038     if (hB_off) DeleteObject(hB_off);
2039 failed:
2040     DeleteDC( hMemDC );
2041     release_icon_ptr( hIcon, ptr );
2042     return result;
2043 }
2044
2045 /***********************************************************************
2046  *           DIB_FixColorsToLoadflags
2047  *
2048  * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2049  * are in loadflags
2050  */
2051 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2052 {
2053     int colors;
2054     COLORREF c_W, c_S, c_F, c_L, c_C;
2055     int incr,i;
2056     RGBQUAD *ptr;
2057     int bitmap_type;
2058     LONG width;
2059     LONG height;
2060     WORD bpp;
2061     DWORD compr;
2062
2063     if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2064     {
2065         WARN_(resource)("Invalid bitmap\n");
2066         return;
2067     }
2068
2069     if (bpp > 8) return;
2070
2071     if (bitmap_type == 0) /* BITMAPCOREHEADER */
2072     {
2073         incr = 3;
2074         colors = 1 << bpp;
2075     }
2076     else
2077     {
2078         incr = 4;
2079         colors = bmi->bmiHeader.biClrUsed;
2080         if (colors > 256) colors = 256;
2081         if (!colors && (bpp <= 8)) colors = 1 << bpp;
2082     }
2083
2084     c_W = GetSysColor(COLOR_WINDOW);
2085     c_S = GetSysColor(COLOR_3DSHADOW);
2086     c_F = GetSysColor(COLOR_3DFACE);
2087     c_L = GetSysColor(COLOR_3DLIGHT);
2088
2089     if (loadflags & LR_LOADTRANSPARENT) {
2090         switch (bpp) {
2091         case 1: pix = pix >> 7; break;
2092         case 4: pix = pix >> 4; break;
2093         case 8: break;
2094         default:
2095             WARN_(resource)("(%d): Unsupported depth\n", bpp);
2096             return;
2097         }
2098         if (pix >= colors) {
2099             WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2100             return;
2101         }
2102         if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2103         ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2104         ptr->rgbBlue = GetBValue(c_W);
2105         ptr->rgbGreen = GetGValue(c_W);
2106         ptr->rgbRed = GetRValue(c_W);
2107     }
2108     if (loadflags & LR_LOADMAP3DCOLORS)
2109         for (i=0; i<colors; i++) {
2110             ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2111             c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2112             if (c_C == RGB(128, 128, 128)) {
2113                 ptr->rgbRed = GetRValue(c_S);
2114                 ptr->rgbGreen = GetGValue(c_S);
2115                 ptr->rgbBlue = GetBValue(c_S);
2116             } else if (c_C == RGB(192, 192, 192)) {
2117                 ptr->rgbRed = GetRValue(c_F);
2118                 ptr->rgbGreen = GetGValue(c_F);
2119                 ptr->rgbBlue = GetBValue(c_F);
2120             } else if (c_C == RGB(223, 223, 223)) {
2121                 ptr->rgbRed = GetRValue(c_L);
2122                 ptr->rgbGreen = GetGValue(c_L);
2123                 ptr->rgbBlue = GetBValue(c_L);
2124             }
2125         }
2126 }
2127
2128
2129 /**********************************************************************
2130  *       BITMAP_Load
2131  */
2132 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2133                             INT desiredx, INT desiredy, UINT loadflags )
2134 {
2135     HBITMAP hbitmap = 0, orig_bm;
2136     HRSRC hRsrc;
2137     HGLOBAL handle;
2138     char *ptr = NULL;
2139     BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2140     int size;
2141     BYTE pix;
2142     char *bits;
2143     LONG width, height, new_width, new_height;
2144     WORD bpp_dummy;
2145     DWORD compr_dummy, offbits = 0;
2146     INT bm_type;
2147     HDC screen_mem_dc = NULL;
2148
2149     if (!(loadflags & LR_LOADFROMFILE))
2150     {
2151         if (!instance)
2152         {
2153             /* OEM bitmap: try to load the resource from user32.dll */
2154             instance = user32_module;
2155         }
2156
2157         if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2158         if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2159
2160         if ((info = LockResource( handle )) == NULL) return 0;
2161     }
2162     else
2163     {
2164         BITMAPFILEHEADER * bmfh;
2165
2166         if (!(ptr = map_fileW( name, NULL ))) return 0;
2167         info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2168         bmfh = (BITMAPFILEHEADER *)ptr;
2169         if (bmfh->bfType != 0x4d42 /* 'BM' */)
2170         {
2171             WARN("Invalid/unsupported bitmap format!\n");
2172             goto end;
2173         }
2174         if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2175     }
2176
2177     size = bitmap_info_size(info, DIB_RGB_COLORS);
2178     fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2179     scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2180
2181     if (!fix_info || !scaled_info) goto end;
2182     memcpy(fix_info, info, size);
2183
2184     pix = *((LPBYTE)info + size);
2185     DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2186
2187     memcpy(scaled_info, fix_info, size);
2188     bm_type = DIB_GetBitmapInfo( &fix_info->bmiHeader, &width, &height,
2189                                  &bpp_dummy, &compr_dummy);
2190     if (bm_type == -1)
2191     {
2192         WARN("Invalid bitmap format!\n");
2193         goto end;
2194     }
2195
2196     if(desiredx != 0)
2197         new_width = desiredx;
2198     else
2199         new_width = width;
2200
2201     if(desiredy != 0)
2202         new_height = height > 0 ? desiredy : -desiredy;
2203     else
2204         new_height = height;
2205
2206     if(bm_type == 0)
2207     {
2208         BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2209         core->bcWidth = new_width;
2210         core->bcHeight = new_height;
2211     }
2212     else
2213     {
2214         /* Some sanity checks for BITMAPINFO (not applicable to BITMAPCOREINFO) */
2215         if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
2216             WARN("Broken BitmapInfoHeader!\n");
2217             goto end;
2218         }
2219
2220         scaled_info->bmiHeader.biWidth = new_width;
2221         scaled_info->bmiHeader.biHeight = new_height;
2222     }
2223
2224     if (new_height < 0) new_height = -new_height;
2225
2226     if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2227     if (!(screen_mem_dc = CreateCompatibleDC( screen_dc ))) goto end;
2228
2229     bits = (char *)info + (offbits ? offbits : size);
2230
2231     if (loadflags & LR_CREATEDIBSECTION)
2232     {
2233         scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2234         hbitmap = CreateDIBSection(screen_dc, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2235     }
2236     else
2237     {
2238         if (is_dib_monochrome(fix_info))
2239             hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2240         else
2241             hbitmap = CreateCompatibleBitmap(screen_dc, new_width, new_height);        
2242     }
2243
2244     orig_bm = SelectObject(screen_mem_dc, hbitmap);
2245     StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2246     SelectObject(screen_mem_dc, orig_bm);
2247
2248 end:
2249     if (screen_mem_dc) DeleteDC(screen_mem_dc);
2250     HeapFree(GetProcessHeap(), 0, scaled_info);
2251     HeapFree(GetProcessHeap(), 0, fix_info);
2252     if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2253
2254     return hbitmap;
2255 }
2256
2257 /**********************************************************************
2258  *              LoadImageA (USER32.@)
2259  *
2260  * See LoadImageW.
2261  */
2262 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2263                               INT desiredx, INT desiredy, UINT loadflags)
2264 {
2265     HANDLE res;
2266     LPWSTR u_name;
2267
2268     if (IS_INTRESOURCE(name))
2269         return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2270
2271     __TRY {
2272         DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2273         u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2274         MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2275     }
2276     __EXCEPT_PAGE_FAULT {
2277         SetLastError( ERROR_INVALID_PARAMETER );
2278         return 0;
2279     }
2280     __ENDTRY
2281     res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2282     HeapFree(GetProcessHeap(), 0, u_name);
2283     return res;
2284 }
2285
2286
2287 /******************************************************************************
2288  *              LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2289  *
2290  * PARAMS
2291  *    hinst     [I] Handle of instance that contains image
2292  *    name      [I] Name of image
2293  *    type      [I] Type of image
2294  *    desiredx  [I] Desired width
2295  *    desiredy  [I] Desired height
2296  *    loadflags [I] Load flags
2297  *
2298  * RETURNS
2299  *    Success: Handle to newly loaded image
2300  *    Failure: NULL
2301  *
2302  * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2303  */
2304 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2305                 INT desiredx, INT desiredy, UINT loadflags )
2306 {
2307     TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
2308                      hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
2309
2310     if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
2311     switch (type) {
2312     case IMAGE_BITMAP:
2313         return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2314
2315     case IMAGE_ICON:
2316         if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2317         if (screen_dc)
2318         {
2319             return CURSORICON_Load(hinst, name, desiredx, desiredy,
2320                                    GetDeviceCaps(screen_dc, BITSPIXEL),
2321                                    FALSE, loadflags);
2322         }
2323         break;
2324
2325     case IMAGE_CURSOR:
2326         return CURSORICON_Load(hinst, name, desiredx, desiredy,
2327                                1, TRUE, loadflags);
2328     }
2329     return 0;
2330 }
2331
2332 /******************************************************************************
2333  *              CopyImage (USER32.@) Creates new image and copies attributes to it
2334  *
2335  * PARAMS
2336  *    hnd      [I] Handle to image to copy
2337  *    type     [I] Type of image to copy
2338  *    desiredx [I] Desired width of new image
2339  *    desiredy [I] Desired height of new image
2340  *    flags    [I] Copy flags
2341  *
2342  * RETURNS
2343  *    Success: Handle to newly created image
2344  *    Failure: NULL
2345  *
2346  * BUGS
2347  *    Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
2348  *    all other versions (95/2000/XP have been tested) ignore it.
2349  *
2350  * NOTES
2351  *    If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
2352  *    a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
2353  *    the copy will have the same depth as the screen.
2354  *    The content of the image will only be copied if the bit depth of the
2355  *    original image is compatible with the bit depth of the screen, or
2356  *    if the source is a DIB section.
2357  *    The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
2358  */
2359 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2360                              INT desiredy, UINT flags )
2361 {
2362     TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
2363           hnd, type, desiredx, desiredy, flags);
2364
2365     switch (type)
2366     {
2367         case IMAGE_BITMAP:
2368         {
2369             HBITMAP res = NULL;
2370             DIBSECTION ds;
2371             int objSize;
2372             BITMAPINFO * bi;
2373
2374             objSize = GetObjectW( hnd, sizeof(ds), &ds );
2375             if (!objSize) return 0;
2376             if ((desiredx < 0) || (desiredy < 0)) return 0;
2377
2378             if (flags & LR_COPYFROMRESOURCE)
2379             {
2380                 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
2381             }
2382
2383             if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
2384             if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
2385
2386             /* Allocate memory for a BITMAPINFOHEADER structure and a
2387                color table. The maximum number of colors in a color table
2388                is 256 which corresponds to a bitmap with depth 8.
2389                Bitmaps with higher depths don't have color tables. */
2390             bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
2391             if (!bi) return 0;
2392
2393             bi->bmiHeader.biSize        = sizeof(bi->bmiHeader);
2394             bi->bmiHeader.biPlanes      = ds.dsBm.bmPlanes;
2395             bi->bmiHeader.biBitCount    = ds.dsBm.bmBitsPixel;
2396             bi->bmiHeader.biCompression = BI_RGB;
2397
2398             if (flags & LR_CREATEDIBSECTION)
2399             {
2400                 /* Create a DIB section. LR_MONOCHROME is ignored */
2401                 void * bits;
2402                 HDC dc = CreateCompatibleDC(NULL);
2403
2404                 if (objSize == sizeof(DIBSECTION))
2405                 {
2406                     /* The source bitmap is a DIB.
2407                        Get its attributes to create an exact copy */
2408                     memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
2409                 }
2410
2411                 /* Get the color table or the color masks */
2412                 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2413
2414                 bi->bmiHeader.biWidth  = desiredx;
2415                 bi->bmiHeader.biHeight = desiredy;
2416                 bi->bmiHeader.biSizeImage = 0;
2417
2418                 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
2419                 DeleteDC(dc);
2420             }
2421             else
2422             {
2423                 /* Create a device-dependent bitmap */
2424
2425                 BOOL monochrome = (flags & LR_MONOCHROME);
2426
2427                 if (objSize == sizeof(DIBSECTION))
2428                 {
2429                     /* The source bitmap is a DIB section.
2430                        Get its attributes */
2431                     HDC dc = CreateCompatibleDC(NULL);
2432                     bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
2433                     bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
2434                     GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2435                     DeleteDC(dc);
2436
2437                     if (!monochrome && ds.dsBm.bmBitsPixel == 1)
2438                     {
2439                         /* Look if the colors of the DIB are black and white */
2440
2441                         monochrome = 
2442                               (bi->bmiColors[0].rgbRed == 0xff
2443                             && bi->bmiColors[0].rgbGreen == 0xff
2444                             && bi->bmiColors[0].rgbBlue == 0xff
2445                             && bi->bmiColors[0].rgbReserved == 0
2446                             && bi->bmiColors[1].rgbRed == 0
2447                             && bi->bmiColors[1].rgbGreen == 0
2448                             && bi->bmiColors[1].rgbBlue == 0
2449                             && bi->bmiColors[1].rgbReserved == 0)
2450                             ||
2451                               (bi->bmiColors[0].rgbRed == 0
2452                             && bi->bmiColors[0].rgbGreen == 0
2453                             && bi->bmiColors[0].rgbBlue == 0
2454                             && bi->bmiColors[0].rgbReserved == 0
2455                             && bi->bmiColors[1].rgbRed == 0xff
2456                             && bi->bmiColors[1].rgbGreen == 0xff
2457                             && bi->bmiColors[1].rgbBlue == 0xff
2458                             && bi->bmiColors[1].rgbReserved == 0);
2459                     }
2460                 }
2461                 else if (!monochrome)
2462                 {
2463                     monochrome = ds.dsBm.bmBitsPixel == 1;
2464                 }
2465
2466                 if (monochrome)
2467                 {
2468                     res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
2469                 }
2470                 else
2471                 {
2472                     HDC screenDC = GetDC(NULL);
2473                     res = CreateCompatibleBitmap(screenDC, desiredx, desiredy);
2474                     ReleaseDC(NULL, screenDC);
2475                 }
2476             }
2477
2478             if (res)
2479             {
2480                 /* Only copy the bitmap if it's a DIB section or if it's
2481                    compatible to the screen */
2482                 BOOL copyContents;
2483
2484                 if (objSize == sizeof(DIBSECTION))
2485                 {
2486                     copyContents = TRUE;
2487                 }
2488                 else
2489                 {
2490                     HDC screenDC = GetDC(NULL);
2491                     int screen_depth = GetDeviceCaps(screenDC, BITSPIXEL);
2492                     ReleaseDC(NULL, screenDC);
2493
2494                     copyContents = (ds.dsBm.bmBitsPixel == 1 || ds.dsBm.bmBitsPixel == screen_depth);
2495                 }
2496
2497                 if (copyContents)
2498                 {
2499                     /* The source bitmap may already be selected in a device context,
2500                        use GetDIBits/StretchDIBits and not StretchBlt  */
2501
2502                     HDC dc;
2503                     void * bits;
2504
2505                     dc = CreateCompatibleDC(NULL);
2506
2507                     bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
2508                     bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
2509                     bi->bmiHeader.biSizeImage = 0;
2510                     bi->bmiHeader.biClrUsed = 0;
2511                     bi->bmiHeader.biClrImportant = 0;
2512
2513                     /* Fill in biSizeImage */
2514                     GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2515                     bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
2516
2517                     if (bits)
2518                     {
2519                         HBITMAP oldBmp;
2520
2521                         /* Get the image bits of the source bitmap */
2522                         GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
2523
2524                         /* Copy it to the destination bitmap */
2525                         oldBmp = SelectObject(dc, res);
2526                         StretchDIBits(dc, 0, 0, desiredx, desiredy,
2527                                       0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
2528                                       bits, bi, DIB_RGB_COLORS, SRCCOPY);
2529                         SelectObject(dc, oldBmp);
2530
2531                         HeapFree(GetProcessHeap(), 0, bits);
2532                     }
2533
2534                     DeleteDC(dc);
2535                 }
2536
2537                 if (flags & LR_COPYDELETEORG)
2538                 {
2539                     DeleteObject(hnd);
2540                 }
2541             }
2542             HeapFree(GetProcessHeap(), 0, bi);
2543             return res;
2544         }
2545         case IMAGE_ICON:
2546         case IMAGE_CURSOR:
2547         {
2548             struct cursoricon_object *icon;
2549             HICON res = 0;
2550             int depth = (flags & LR_MONOCHROME) ? 1 : GetDeviceCaps( screen_dc, BITSPIXEL );
2551
2552             if (flags & LR_DEFAULTSIZE)
2553             {
2554                 if (!desiredx) desiredx = GetSystemMetrics( type == IMAGE_ICON ? SM_CXICON : SM_CXCURSOR );
2555                 if (!desiredy) desiredy = GetSystemMetrics( type == IMAGE_ICON ? SM_CYICON : SM_CYCURSOR );
2556             }
2557
2558             if (!(icon = get_icon_ptr( hnd ))) return 0;
2559
2560             if (icon->rsrc && (flags & LR_COPYFROMRESOURCE))
2561                 res = CURSORICON_Load( icon->module, icon->resname, desiredx, desiredy, depth,
2562                                        type == IMAGE_CURSOR, flags );
2563             else
2564                 res = CopyIcon( hnd ); /* FIXME: change size if necessary */
2565             release_icon_ptr( hnd, icon );
2566
2567             if (res && (flags & LR_COPYDELETEORG)) DeleteObject( hnd );
2568             return res;
2569         }
2570     }
2571     return 0;
2572 }
2573
2574
2575 /******************************************************************************
2576  *              LoadBitmapW (USER32.@) Loads bitmap from the executable file
2577  *
2578  * RETURNS
2579  *    Success: Handle to specified bitmap
2580  *    Failure: NULL
2581  */
2582 HBITMAP WINAPI LoadBitmapW(
2583     HINSTANCE instance, /* [in] Handle to application instance */
2584     LPCWSTR name)         /* [in] Address of bitmap resource name */
2585 {
2586     return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2587 }
2588
2589 /**********************************************************************
2590  *              LoadBitmapA (USER32.@)
2591  *
2592  * See LoadBitmapW.
2593  */
2594 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
2595 {
2596     return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2597 }