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