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