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