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