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