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