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