user32/tests: Test to show that caption added for WS_EX_LAYERED as well.
[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     INT size;
769     BITMAPINFO *pSrcInfo, *pDestInfo;
770
771     if (dwVersion == 0x00020000)
772     {
773         FIXME_(cursor)("\t2.xx resources are not supported\n");
774         return 0;
775     }
776
777     /* Check bitmap header */
778
779     if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
780          (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER)  ||
781           bmi->bmiHeader.biCompression != BI_RGB) )
782     {
783           WARN_(cursor)("\tinvalid resource bitmap header.\n");
784           return 0;
785     }
786
787     size = bitmap_info_size( bmi, DIB_RGB_COLORS );
788
789     if (!width) width = bmi->bmiHeader.biWidth;
790     if (!height) height = bmi->bmiHeader.biHeight/2;
791
792     /* Scale the hotspot */
793     if (((bmi->bmiHeader.biHeight/2 != height) || (bmi->bmiHeader.biWidth != width)) &&
794         hotspot.x != ICON_HOTSPOT && hotspot.y != ICON_HOTSPOT)
795     {
796         hotspot.x = (hotspot.x * width) / bmi->bmiHeader.biWidth;
797         hotspot.y = (hotspot.y * height) / (bmi->bmiHeader.biHeight / 2);
798     }
799
800     if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
801     if (screen_dc)
802     {
803         /* Make sure we have room for the monochrome bitmap later on.
804          * Note that BITMAPINFOINFO and BITMAPCOREHEADER are the same
805          * up to and including the biBitCount. In-memory icon resource
806          * format is as follows:
807          *
808          *   BITMAPINFOHEADER   icHeader  // DIB header
809          *   RGBQUAD         icColors[]   // Color table
810          *   BYTE            icXOR[]      // DIB bits for XOR mask
811          *   BYTE            icAND[]      // DIB bits for AND mask
812          */
813
814         pSrcInfo = HeapAlloc( GetProcessHeap(), 0,
815                               max(size, sizeof(BITMAPINFOHEADER) + 2*sizeof(RGBQUAD)));
816         pDestInfo = HeapAlloc( GetProcessHeap(), 0,
817                               max(size, sizeof(BITMAPINFOHEADER) + 2*sizeof(RGBQUAD)));
818         if (pSrcInfo && pDestInfo)
819         {
820             memcpy( pSrcInfo, bmi, size );
821             pSrcInfo->bmiHeader.biHeight /= 2;
822
823             memcpy( pDestInfo, bmi, size );
824             pDestInfo->bmiHeader.biWidth = width;
825             pDestInfo->bmiHeader.biHeight = height;
826             pDestInfo->bmiHeader.biSizeImage = 0;
827
828             /* Create the XOR bitmap */
829             if(pSrcInfo->bmiHeader.biBitCount == 32)
830             {
831                 void *pDIBBuffer = NULL;
832                 hXorBits = CreateDIBSection(screen_dc, pDestInfo, DIB_RGB_COLORS, &pDIBBuffer, NULL, 0);
833
834                 if(hXorBits)
835                 {
836                     if (!stretch_blt_icon(hXorBits, pDestInfo, pSrcInfo, (char*)bmi + size))
837                     {
838                         DeleteObject(hXorBits);
839                         hXorBits = 0;
840                     }
841                 }
842             }
843             else
844             {
845                 hXorBits = CreateCompatibleBitmap(screen_dc, width, height);
846
847                 if(hXorBits)
848                 {
849                     if(!stretch_blt_icon(hXorBits, pDestInfo, pSrcInfo, (char*)bmi + size))
850                     {
851                         DeleteObject(hXorBits);
852                         hXorBits = 0;
853                     }
854                 }
855             }
856
857             if( hXorBits )
858             {
859                 char* xbits = (char *)bmi + size +
860                     get_dib_width_bytes( bmi->bmiHeader.biWidth,
861                                          bmi->bmiHeader.biBitCount ) * abs( bmi->bmiHeader.biHeight ) / 2;
862
863                 pSrcInfo->bmiHeader.biBitCount = 1;
864                 if (pSrcInfo->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
865                 {
866                     RGBQUAD *rgb = pSrcInfo->bmiColors;
867
868                     pSrcInfo->bmiHeader.biClrUsed = pSrcInfo->bmiHeader.biClrImportant = 2;
869                     rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
870                     rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
871                     rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
872                 }
873                 else
874                 {
875                     RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)pSrcInfo) + 1);
876
877                     rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
878                     rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
879                 }
880
881                 /* Create the AND bitmap */
882                 hAndBits = CreateBitmap(width, height, 1, 1, NULL);
883
884                 if(!stretch_blt_icon(hAndBits, pDestInfo, pSrcInfo, xbits))
885                 {
886                     DeleteObject(hAndBits);
887                     hAndBits = 0;
888                 }
889
890                 if( !hAndBits )
891                 {
892                     DeleteObject( hXorBits );
893                     hXorBits = 0;
894                 }
895             }
896         }
897
898         HeapFree( GetProcessHeap(), 0, pSrcInfo );
899         HeapFree( GetProcessHeap(), 0, pDestInfo );
900     }
901
902     if( !hXorBits || !hAndBits )
903     {
904         WARN_(cursor)("\tunable to create an icon bitmap.\n");
905         return 0;
906     }
907
908     /* Now create the CURSORICONINFO structure */
909     GetObjectA( hXorBits, sizeof(bmpXor), &bmpXor );
910     GetObjectA( hAndBits, sizeof(bmpAnd), &bmpAnd );
911     sizeXor = bmpXor.bmHeight * bmpXor.bmWidthBytes;
912     sizeAnd = bmpAnd.bmHeight * bmpAnd.bmWidthBytes;
913
914     hObj = alloc_icon_handle( sizeof(CURSORICONINFO) + sizeXor + sizeAnd );
915     if (hObj)
916     {
917         CURSORICONINFO *info = get_icon_ptr( hObj );
918
919         info->ptHotSpot.x   = hotspot.x;
920         info->ptHotSpot.y   = hotspot.y;
921         info->nWidth        = bmpXor.bmWidth;
922         info->nHeight       = bmpXor.bmHeight;
923         info->nWidthBytes   = bmpXor.bmWidthBytes;
924         info->bPlanes       = bmpXor.bmPlanes;
925         info->bBitsPerPixel = bmpXor.bmBitsPixel;
926
927         /* Transfer the bitmap bits to the CURSORICONINFO structure */
928
929         GetBitmapBits( hAndBits, sizeAnd, info + 1 );
930         GetBitmapBits( hXorBits, sizeXor, (char *)(info + 1) + sizeAnd );
931         release_icon_ptr( hObj, info );
932     }
933
934     DeleteObject( hAndBits );
935     DeleteObject( hXorBits );
936     return hObj;
937 }
938
939
940 /**********************************************************************
941  *          .ANI cursor support
942  */
943 #define RIFF_FOURCC( c0, c1, c2, c3 ) \
944         ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
945         ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
946
947 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
948 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
949 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
950 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
951 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
952 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
953
954 #define ANI_FLAG_ICON       0x1
955 #define ANI_FLAG_SEQUENCE   0x2
956
957 typedef struct {
958     DWORD header_size;
959     DWORD num_frames;
960     DWORD num_steps;
961     DWORD width;
962     DWORD height;
963     DWORD bpp;
964     DWORD num_planes;
965     DWORD display_rate;
966     DWORD flags;
967 } ani_header;
968
969 typedef struct {
970     DWORD           data_size;
971     const unsigned char   *data;
972 } riff_chunk_t;
973
974 static void dump_ani_header( const ani_header *header )
975 {
976     TRACE("     header size: %d\n", header->header_size);
977     TRACE("          frames: %d\n", header->num_frames);
978     TRACE("           steps: %d\n", header->num_steps);
979     TRACE("           width: %d\n", header->width);
980     TRACE("          height: %d\n", header->height);
981     TRACE("             bpp: %d\n", header->bpp);
982     TRACE("          planes: %d\n", header->num_planes);
983     TRACE("    display rate: %d\n", header->display_rate);
984     TRACE("           flags: 0x%08x\n", header->flags);
985 }
986
987
988 /*
989  * RIFF:
990  * DWORD "RIFF"
991  * DWORD size
992  * DWORD riff_id
993  * BYTE[] data
994  *
995  * LIST:
996  * DWORD "LIST"
997  * DWORD size
998  * DWORD list_id
999  * BYTE[] data
1000  *
1001  * CHUNK:
1002  * DWORD chunk_id
1003  * DWORD size
1004  * BYTE[] data
1005  */
1006 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
1007 {
1008     const unsigned char *ptr = parent_chunk->data;
1009     const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
1010
1011     if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
1012
1013     while (ptr < end)
1014     {
1015         if ((!chunk_type && *(DWORD *)ptr == chunk_id )
1016                 || (chunk_type && *(DWORD *)ptr == chunk_type && *((DWORD *)ptr + 2) == chunk_id ))
1017         {
1018             ptr += sizeof(DWORD);
1019             chunk->data_size = (*(DWORD *)ptr + 1) & ~1;
1020             ptr += sizeof(DWORD);
1021             if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
1022             chunk->data = ptr;
1023
1024             return;
1025         }
1026
1027         ptr += sizeof(DWORD);
1028         ptr += (*(DWORD *)ptr + 1) & ~1;
1029         ptr += sizeof(DWORD);
1030     }
1031 }
1032
1033
1034 /*
1035  * .ANI layout:
1036  *
1037  * RIFF:'ACON'                  RIFF chunk
1038  *     |- CHUNK:'anih'          Header
1039  *     |- CHUNK:'seq '          Sequence information (optional)
1040  *     \- LIST:'fram'           Frame list
1041  *            |- CHUNK:icon     Cursor frames
1042  *            |- CHUNK:icon
1043  *            |- ...
1044  *            \- CHUNK:icon
1045  */
1046 static HCURSOR CURSORICON_CreateIconFromANI( const LPBYTE bits, DWORD bits_size,
1047     INT width, INT height, INT depth )
1048 {
1049     HCURSOR cursor;
1050     ani_header header = {0};
1051     LPBYTE frame_bits = 0;
1052     POINT16 hotspot;
1053     CURSORICONFILEDIRENTRY *entry;
1054
1055     riff_chunk_t root_chunk = { bits_size, bits };
1056     riff_chunk_t ACON_chunk = {0};
1057     riff_chunk_t anih_chunk = {0};
1058     riff_chunk_t fram_chunk = {0};
1059     const unsigned char *icon_data;
1060
1061     TRACE("bits %p, bits_size %d\n", bits, bits_size);
1062
1063     if (!bits) return 0;
1064
1065     riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1066     if (!ACON_chunk.data)
1067     {
1068         ERR("Failed to get root chunk.\n");
1069         return 0;
1070     }
1071
1072     riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1073     if (!anih_chunk.data)
1074     {
1075         ERR("Failed to get 'anih' chunk.\n");
1076         return 0;
1077     }
1078     memcpy( &header, anih_chunk.data, sizeof(header) );
1079     dump_ani_header( &header );
1080
1081     riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1082     if (!fram_chunk.data)
1083     {
1084         ERR("Failed to get icon list.\n");
1085         return 0;
1086     }
1087
1088     /* FIXME: For now, just load the first frame.  Before we can load all the
1089      * frames, we need to write the needed code in wineserver, etc. to handle
1090      * cursors.  Once this code is written, we can extend it to support .ani
1091      * cursors and then update user32 and winex11.drv to load all frames.
1092      *
1093      * Hopefully this will at least make some games (C&C3, etc.) more playable
1094      * in the meantime.
1095      */
1096     FIXME("Loading all frames for .ani cursors not implemented.\n");
1097     icon_data = fram_chunk.data + (2 * sizeof(DWORD));
1098
1099     entry = CURSORICON_FindBestIconFile( (CURSORICONFILEDIR *) icon_data,
1100         width, height, depth );
1101
1102     frame_bits = HeapAlloc( GetProcessHeap(), 0, entry->dwDIBSize );
1103     memcpy( frame_bits, icon_data + entry->dwDIBOffset, entry->dwDIBSize );
1104
1105     if (!header.width || !header.height)
1106     {
1107         header.width = entry->bWidth;
1108         header.height = entry->bHeight;
1109     }
1110
1111     hotspot.x = entry->xHotspot;
1112     hotspot.y = entry->yHotspot;
1113
1114     cursor = CURSORICON_CreateIconFromBMI( (BITMAPINFO *) frame_bits, hotspot,
1115         FALSE, 0x00030000, header.width, header.height, 0 );
1116
1117     HeapFree( GetProcessHeap(), 0, frame_bits );
1118
1119     return cursor;
1120 }
1121
1122
1123 /**********************************************************************
1124  *              CreateIconFromResourceEx (USER32.@)
1125  *
1126  * FIXME: Convert to mono when cFlag is LR_MONOCHROME. Do something
1127  *        with cbSize parameter as well.
1128  */
1129 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1130                                        BOOL bIcon, DWORD dwVersion,
1131                                        INT width, INT height,
1132                                        UINT cFlag )
1133 {
1134     POINT16 hotspot;
1135     BITMAPINFO *bmi;
1136
1137     hotspot.x = ICON_HOTSPOT;
1138     hotspot.y = ICON_HOTSPOT;
1139
1140     TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s %s\n",
1141                    bits, cbSize, dwVersion, width, height,
1142                                   bIcon ? "icon" : "cursor", (cFlag & LR_MONOCHROME) ? "mono" : "" );
1143
1144     if (bIcon)
1145         bmi = (BITMAPINFO *)bits;
1146     else /* get the hotspot */
1147     {
1148         POINT16 *pt = (POINT16 *)bits;
1149         hotspot = *pt;
1150         bmi = (BITMAPINFO *)(pt + 1);
1151     }
1152
1153     return CURSORICON_CreateIconFromBMI( bmi, hotspot, bIcon, dwVersion,
1154                                          width, height, cFlag );
1155 }
1156
1157
1158 /**********************************************************************
1159  *              CreateIconFromResource (USER32.@)
1160  */
1161 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1162                                            BOOL bIcon, DWORD dwVersion)
1163 {
1164     return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
1165 }
1166
1167
1168 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1169                              INT width, INT height, INT depth,
1170                              BOOL fCursor, UINT loadflags)
1171 {
1172     CURSORICONFILEDIRENTRY *entry;
1173     CURSORICONFILEDIR *dir;
1174     DWORD filesize = 0;
1175     HICON hIcon = 0;
1176     LPBYTE bits;
1177     POINT16 hotspot;
1178
1179     TRACE("loading %s\n", debugstr_w( filename ));
1180
1181     bits = map_fileW( filename, &filesize );
1182     if (!bits)
1183         return hIcon;
1184
1185     /* Check for .ani. */
1186     if (memcmp( bits, "RIFF", 4 ) == 0)
1187     {
1188         hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height,
1189             depth );
1190         goto end;
1191     }
1192
1193     dir = (CURSORICONFILEDIR*) bits;
1194     if ( filesize < sizeof(*dir) )
1195         goto end;
1196
1197     if ( filesize < (sizeof(*dir) + sizeof(dir->idEntries[0])*(dir->idCount-1)) )
1198         goto end;
1199
1200     if ( fCursor )
1201         entry = CURSORICON_FindBestCursorFile( dir, width, height, depth );
1202     else
1203         entry = CURSORICON_FindBestIconFile( dir, width, height, depth );
1204
1205     if ( !entry )
1206         goto end;
1207
1208     /* check that we don't run off the end of the file */
1209     if ( entry->dwDIBOffset > filesize )
1210         goto end;
1211     if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1212         goto end;
1213
1214     /* Set the actual hotspot for cursors and ICON_HOTSPOT for icons. */
1215     if ( fCursor )
1216     {
1217         hotspot.x = entry->xHotspot;
1218         hotspot.y = entry->yHotspot;
1219     }
1220     else
1221     {
1222         hotspot.x = ICON_HOTSPOT;
1223         hotspot.y = ICON_HOTSPOT;
1224     }
1225     hIcon = CURSORICON_CreateIconFromBMI( (BITMAPINFO *)&bits[entry->dwDIBOffset],
1226                                           hotspot, !fCursor, 0x00030000,
1227                                           width, height, loadflags );
1228 end:
1229     TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1230     UnmapViewOfFile( bits );
1231     return hIcon;
1232 }
1233
1234 /**********************************************************************
1235  *          CURSORICON_Load
1236  *
1237  * Load a cursor or icon from resource or file.
1238  */
1239 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1240                              INT width, INT height, INT depth,
1241                              BOOL fCursor, UINT loadflags)
1242 {
1243     HANDLE handle = 0;
1244     HICON hIcon = 0;
1245     HRSRC hRsrc, hGroupRsrc;
1246     CURSORICONDIR *dir;
1247     CURSORICONDIRENTRY *dirEntry;
1248     LPBYTE bits;
1249     WORD wResId;
1250     DWORD dwBytesInRes;
1251
1252     TRACE("%p, %s, %dx%d, depth %d, fCursor %d, flags 0x%04x\n",
1253           hInstance, debugstr_w(name), width, height, depth, fCursor, loadflags);
1254
1255     if ( loadflags & LR_LOADFROMFILE )    /* Load from file */
1256         return CURSORICON_LoadFromFile( name, width, height, depth, fCursor, loadflags );
1257
1258     if (!hInstance) hInstance = user32_module;  /* Load OEM cursor/icon */
1259
1260     /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1261     if ((ULONG_PTR)hInstance >> 16 == 0) loadflags &= ~LR_SHARED;
1262
1263     /* Get directory resource ID */
1264
1265     if (!(hRsrc = FindResourceW( hInstance, name,
1266                                  (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1267         return 0;
1268     hGroupRsrc = hRsrc;
1269
1270     /* Find the best entry in the directory */
1271
1272     if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1273     if (!(dir = LockResource( handle ))) return 0;
1274     if (fCursor)
1275         dirEntry = CURSORICON_FindBestCursorRes( dir, width, height, depth );
1276     else
1277         dirEntry = CURSORICON_FindBestIconRes( dir, width, height, depth );
1278     if (!dirEntry) return 0;
1279     wResId = dirEntry->wResId;
1280     dwBytesInRes = dirEntry->dwBytesInRes;
1281     FreeResource( handle );
1282
1283     /* Load the resource */
1284
1285     if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1286                                 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1287
1288     /* If shared icon, check whether it was already loaded */
1289     if (    (loadflags & LR_SHARED)
1290          && (hIcon = CURSORICON_FindSharedIcon( hInstance, hRsrc ) ) != 0 )
1291         return hIcon;
1292
1293     if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1294     bits = LockResource( handle );
1295     hIcon = CreateIconFromResourceEx( bits, dwBytesInRes,
1296                                       !fCursor, 0x00030000, width, height, loadflags);
1297     FreeResource( handle );
1298
1299     /* If shared icon, add to icon cache */
1300
1301     if ( hIcon && (loadflags & LR_SHARED) )
1302         CURSORICON_AddSharedIcon( hInstance, hRsrc, hGroupRsrc, hIcon );
1303
1304     return hIcon;
1305 }
1306
1307
1308 /*************************************************************************
1309  * CURSORICON_ExtCopy
1310  *
1311  * Copies an Image from the Cache if LR_COPYFROMRESOURCE is specified
1312  *
1313  * PARAMS
1314  *      Handle     [I] handle to an Image
1315  *      nType      [I] Type of Handle (IMAGE_CURSOR | IMAGE_ICON)
1316  *      iDesiredCX [I] The Desired width of the Image
1317  *      iDesiredCY [I] The desired height of the Image
1318  *      nFlags     [I] The flags from CopyImage
1319  *
1320  * RETURNS
1321  *     Success: The new handle of the Image
1322  *
1323  * NOTES
1324  *     LR_COPYDELETEORG and LR_MONOCHROME are currently not implemented.
1325  *     LR_MONOCHROME should be implemented by CreateIconFromResourceEx.
1326  *     LR_COPYFROMRESOURCE will only work if the Image is in the Cache.
1327  *
1328  *
1329  */
1330
1331 static HICON CURSORICON_ExtCopy(HICON hIcon, UINT nType,
1332                                 INT iDesiredCX, INT iDesiredCY,
1333                                 UINT nFlags)
1334 {
1335     HICON hNew=0;
1336
1337     TRACE_(icon)("hIcon %p, nType %u, iDesiredCX %i, iDesiredCY %i, nFlags %u\n",
1338                  hIcon, nType, iDesiredCX, iDesiredCY, nFlags);
1339
1340     if(hIcon == 0)
1341     {
1342         return 0;
1343     }
1344
1345     /* Best Fit or Monochrome */
1346     if( (nFlags & LR_COPYFROMRESOURCE
1347         && (iDesiredCX > 0 || iDesiredCY > 0))
1348         || nFlags & LR_MONOCHROME)
1349     {
1350         ICONCACHE* pIconCache = CURSORICON_FindCache(hIcon);
1351
1352         /* Not Found in Cache, then do a straight copy
1353         */
1354         if(pIconCache == NULL)
1355         {
1356             hNew = CopyIcon( hIcon );
1357             if(nFlags & LR_COPYFROMRESOURCE)
1358             {
1359                 TRACE_(icon)("LR_COPYFROMRESOURCE: Failed to load from cache\n");
1360             }
1361         }
1362         else
1363         {
1364             int iTargetCY = iDesiredCY, iTargetCX = iDesiredCX;
1365             LPBYTE pBits;
1366             HANDLE hMem;
1367             HRSRC hRsrc;
1368             DWORD dwBytesInRes;
1369             WORD wResId;
1370             CURSORICONDIR *pDir;
1371             CURSORICONDIRENTRY *pDirEntry;
1372             BOOL bIsIcon = (nType == IMAGE_ICON);
1373
1374             /* Completing iDesiredCX CY for Monochrome Bitmaps if needed
1375             */
1376             if(((nFlags & LR_MONOCHROME) && !(nFlags & LR_COPYFROMRESOURCE))
1377                 || (iDesiredCX == 0 && iDesiredCY == 0))
1378             {
1379                 iDesiredCY = GetSystemMetrics(bIsIcon ?
1380                     SM_CYICON : SM_CYCURSOR);
1381                 iDesiredCX = GetSystemMetrics(bIsIcon ?
1382                     SM_CXICON : SM_CXCURSOR);
1383             }
1384
1385             /* Retrieve the CURSORICONDIRENTRY
1386             */
1387             if (!(hMem = LoadResource( pIconCache->hModule ,
1388                             pIconCache->hGroupRsrc)))
1389             {
1390                 return 0;
1391             }
1392             if (!(pDir = LockResource( hMem )))
1393             {
1394                 return 0;
1395             }
1396
1397             /* Find Best Fit
1398             */
1399             if(bIsIcon)
1400             {
1401                 pDirEntry = CURSORICON_FindBestIconRes(
1402                                 pDir, iDesiredCX, iDesiredCY, 256 );
1403             }
1404             else
1405             {
1406                 pDirEntry = CURSORICON_FindBestCursorRes(
1407                                 pDir, iDesiredCX, iDesiredCY, 1);
1408             }
1409
1410             wResId = pDirEntry->wResId;
1411             dwBytesInRes = pDirEntry->dwBytesInRes;
1412             FreeResource(hMem);
1413
1414             TRACE_(icon)("ResID %u, BytesInRes %u, Width %d, Height %d DX %d, DY %d\n",
1415                 wResId, dwBytesInRes,  pDirEntry->ResInfo.icon.bWidth,
1416                 pDirEntry->ResInfo.icon.bHeight, iDesiredCX, iDesiredCY);
1417
1418             /* Get the Best Fit
1419             */
1420             if (!(hRsrc = FindResourceW(pIconCache->hModule ,
1421                 MAKEINTRESOURCEW(wResId), (LPWSTR)(bIsIcon ? RT_ICON : RT_CURSOR))))
1422             {
1423                 return 0;
1424             }
1425             if (!(hMem = LoadResource( pIconCache->hModule , hRsrc )))
1426             {
1427                 return 0;
1428             }
1429
1430             pBits = LockResource( hMem );
1431
1432             if(nFlags & LR_DEFAULTSIZE)
1433             {
1434                 iTargetCY = GetSystemMetrics(SM_CYICON);
1435                 iTargetCX = GetSystemMetrics(SM_CXICON);
1436             }
1437
1438             /* Create a New Icon with the proper dimension
1439             */
1440             hNew = CreateIconFromResourceEx( pBits, dwBytesInRes,
1441                        bIsIcon, 0x00030000, iTargetCX, iTargetCY, nFlags);
1442             FreeResource(hMem);
1443         }
1444     }
1445     else hNew = CopyIcon( hIcon );
1446     return hNew;
1447 }
1448
1449
1450 /***********************************************************************
1451  *              CreateCursor (USER32.@)
1452  */
1453 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
1454                                  INT xHotSpot, INT yHotSpot,
1455                                  INT nWidth, INT nHeight,
1456                                  LPCVOID lpANDbits, LPCVOID lpXORbits )
1457 {
1458     ICONINFO info;
1459     HCURSOR hCursor;
1460
1461     TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
1462                     nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1463
1464     info.fIcon = FALSE;
1465     info.xHotspot = xHotSpot;
1466     info.yHotspot = yHotSpot;
1467     info.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1468     info.hbmColor = CreateBitmap( nWidth, nHeight, 1, 1, lpXORbits );
1469     hCursor = CreateIconIndirect( &info );
1470     DeleteObject( info.hbmMask );
1471     DeleteObject( info.hbmColor );
1472     return hCursor;
1473 }
1474
1475
1476 /***********************************************************************
1477  *              CreateIcon (USER32.@)
1478  *
1479  *  Creates an icon based on the specified bitmaps. The bitmaps must be
1480  *  provided in a device dependent format and will be resized to
1481  *  (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1482  *  depth. The provided bitmaps must be top-down bitmaps.
1483  *  Although Windows does not support 15bpp(*) this API must support it
1484  *  for Winelib applications.
1485  *
1486  *  (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1487  *      format!
1488  *
1489  * RETURNS
1490  *  Success: handle to an icon
1491  *  Failure: NULL
1492  *
1493  * FIXME: Do we need to resize the bitmaps?
1494  */
1495 HICON WINAPI CreateIcon(
1496     HINSTANCE hInstance,  /* [in] the application's hInstance */
1497     INT       nWidth,     /* [in] the width of the provided bitmaps */
1498     INT       nHeight,    /* [in] the height of the provided bitmaps */
1499     BYTE      bPlanes,    /* [in] the number of planes in the provided bitmaps */
1500     BYTE      bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1501     LPCVOID   lpANDbits,  /* [in] a monochrome bitmap representing the icon's mask */
1502     LPCVOID   lpXORbits)  /* [in] the icon's 'color' bitmap */
1503 {
1504     ICONINFO iinfo;
1505     HICON hIcon;
1506
1507     TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
1508                  nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1509
1510     iinfo.fIcon = TRUE;
1511     iinfo.xHotspot = ICON_HOTSPOT;
1512     iinfo.yHotspot = ICON_HOTSPOT;
1513     iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1514     iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );
1515
1516     hIcon = CreateIconIndirect( &iinfo );
1517
1518     DeleteObject( iinfo.hbmMask );
1519     DeleteObject( iinfo.hbmColor );
1520
1521     return hIcon;
1522 }
1523
1524
1525 /***********************************************************************
1526  *              CopyIcon (USER32.@)
1527  */
1528 HICON WINAPI CopyIcon( HICON hIcon )
1529 {
1530     CURSORICONINFO *ptrOld, *ptrNew;
1531     int size;
1532     HICON hNew;
1533
1534     if (!(ptrOld = get_icon_ptr( hIcon ))) return 0;
1535     size = sizeof(CURSORICONINFO);
1536     size += ptrOld->nHeight * get_bitmap_width_bytes( ptrOld->nWidth, 1 );  /* and bitmap */
1537     size += ptrOld->nHeight * ptrOld->nWidthBytes;  /* xor bitmap */
1538     hNew = alloc_icon_handle( size );
1539     ptrNew = get_icon_ptr( hNew );
1540     memcpy( ptrNew, ptrOld, size );
1541     release_icon_ptr( hIcon, ptrOld );
1542     release_icon_ptr( hNew, ptrNew );
1543     return hNew;
1544 }
1545
1546
1547 /***********************************************************************
1548  *              DestroyIcon (USER32.@)
1549  */
1550 BOOL WINAPI DestroyIcon( HICON hIcon )
1551 {
1552     TRACE_(icon)("%p\n", hIcon );
1553
1554     if (CURSORICON_DelSharedIcon( hIcon ) == -1)
1555         free_icon_handle( hIcon );
1556     return TRUE;
1557 }
1558
1559
1560 /***********************************************************************
1561  *              DestroyCursor (USER32.@)
1562  */
1563 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
1564 {
1565     if (get_user_thread_info()->cursor == hCursor)
1566     {
1567         WARN_(cursor)("Destroying active cursor!\n" );
1568         return FALSE;
1569     }
1570     return DestroyIcon( hCursor );
1571 }
1572
1573 /***********************************************************************
1574  *      bitmap_has_alpha_channel
1575  *
1576  * Analyses bits bitmap to determine if alpha data is present.
1577  *
1578  * PARAMS
1579  *      bpp          [I] The bits-per-pixel of the bitmap
1580  *      bitmapBits   [I] A pointer to the bitmap data
1581  *      bitmapLength [I] The length of the bitmap in bytes
1582  *
1583  * RETURNS
1584  *      TRUE if an alpha channel is discovered, FALSE
1585  *
1586  * NOTE
1587  *      Windows' behaviour is that if the icon bitmap is 32-bit and at
1588  *      least one pixel has a non-zero alpha, then the bitmap is a
1589  *      treated as having an alpha channel transparentcy. Otherwise,
1590  *      it's treated as being completely opaque.
1591  *
1592  */
1593 static BOOL bitmap_has_alpha_channel( int bpp, unsigned char *bitmapBits,
1594                                       unsigned int bitmapLength )
1595 {
1596     /* Detect an alpha channel by looking for non-zero alpha pixels */
1597     if(bpp == 32)
1598     {
1599         unsigned int offset;
1600         for(offset = 3; offset < bitmapLength; offset += 4)
1601         {
1602             if(bitmapBits[offset] != 0)
1603             {
1604                 return TRUE;
1605             }
1606         }
1607     }
1608     return FALSE;
1609 }
1610
1611 /***********************************************************************
1612  *          premultiply_alpha_channel
1613  *
1614  * Premultiplies the color channels of a 32-bit bitmap by the alpha
1615  * channel. This is a necessary step that must be carried out on
1616  * the image before it is passed to GdiAlphaBlend
1617  *
1618  * PARAMS
1619  *      destBitmap   [I] The destination bitmap buffer
1620  *      srcBitmap    [I] The source bitmap buffer
1621  *      bitmapLength [I] The length of the bitmap in bytes
1622  *
1623  */
1624 static void premultiply_alpha_channel( unsigned char *destBitmap,
1625                                        unsigned char *srcBitmap,
1626                                        unsigned int bitmapLength )
1627 {
1628     unsigned char *destPixel = destBitmap;
1629     unsigned char *srcPixel = srcBitmap;
1630
1631     while(destPixel < destBitmap + bitmapLength)
1632     {
1633         unsigned char alpha = srcPixel[3];
1634         *(destPixel++) = *(srcPixel++) * alpha / 255;
1635         *(destPixel++) = *(srcPixel++) * alpha / 255;
1636         *(destPixel++) = *(srcPixel++) * alpha / 255;
1637         *(destPixel++) = *(srcPixel++);
1638     }
1639 }
1640
1641 /***********************************************************************
1642  *              DrawIcon (USER32.@)
1643  */
1644 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
1645 {
1646     CURSORICONINFO *ptr;
1647     HDC hMemDC;
1648     HBITMAP hXorBits = NULL, hAndBits = NULL, hBitTemp = NULL;
1649     COLORREF oldFg, oldBg;
1650     unsigned char *xorBitmapBits;
1651     unsigned int dibLength;
1652
1653     TRACE("%p, (%d,%d), %p\n", hdc, x, y, hIcon);
1654
1655     if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
1656     if (!(hMemDC = CreateCompatibleDC( hdc )))
1657     {
1658         release_icon_ptr( hIcon, ptr );
1659         return FALSE;
1660     }
1661
1662     dibLength = ptr->nHeight * get_bitmap_width_bytes(
1663         ptr->nWidth, ptr->bBitsPerPixel);
1664
1665     xorBitmapBits = (unsigned char *)(ptr + 1) + ptr->nHeight *
1666                     get_bitmap_width_bytes(ptr->nWidth, 1);
1667
1668     oldFg = SetTextColor( hdc, RGB(0,0,0) );
1669     oldBg = SetBkColor( hdc, RGB(255,255,255) );
1670
1671     if(bitmap_has_alpha_channel(ptr->bBitsPerPixel, xorBitmapBits, dibLength))
1672     {
1673         BITMAPINFOHEADER bmih;
1674         unsigned char *dibBits;
1675
1676         memset(&bmih, 0, sizeof(BITMAPINFOHEADER));
1677         bmih.biSize = sizeof(BITMAPINFOHEADER);
1678         bmih.biWidth = ptr->nWidth;
1679         bmih.biHeight = -ptr->nHeight;
1680         bmih.biPlanes = ptr->bPlanes;
1681         bmih.biBitCount = 32;
1682         bmih.biCompression = BI_RGB;
1683
1684         hXorBits = CreateDIBSection(hdc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS,
1685                                     (void*)&dibBits, NULL, 0);
1686
1687         if (hXorBits && dibBits)
1688         {
1689             BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
1690
1691             /* Do the alpha blending render */
1692             premultiply_alpha_channel(dibBits, xorBitmapBits, dibLength);
1693             hBitTemp = SelectObject( hMemDC, hXorBits );
1694             /* Destination width/height has to be "System Large" size */
1695             GdiAlphaBlend(hdc, x, y, GetSystemMetrics(SM_CXICON),
1696                             GetSystemMetrics(SM_CYICON), hMemDC,
1697                             0, 0, ptr->nWidth, ptr->nHeight, pixelblend);
1698             SelectObject( hMemDC, hBitTemp );
1699         }
1700     }
1701     else
1702     {
1703         hAndBits = CreateBitmap( ptr->nWidth, ptr->nHeight, 1, 1, ptr + 1 );
1704         hXorBits = CreateBitmap( ptr->nWidth, ptr->nHeight, ptr->bPlanes,
1705                                ptr->bBitsPerPixel, xorBitmapBits);
1706
1707         if (hXorBits && hAndBits)
1708         {
1709             hBitTemp = SelectObject( hMemDC, hAndBits );
1710             StretchBlt( hdc, x, y, GetSystemMetrics(SM_CXICON),
1711                             GetSystemMetrics(SM_CYICON), hMemDC, 0, 0,
1712                             ptr->nWidth, ptr->nHeight, SRCAND );
1713             SelectObject( hMemDC, hXorBits );
1714             StretchBlt( hdc, x, y, GetSystemMetrics(SM_CXICON),
1715                             GetSystemMetrics(SM_CYICON), hMemDC, 0, 0,
1716                             ptr->nWidth, ptr->nHeight, SRCINVERT );
1717             SelectObject( hMemDC, hBitTemp );
1718         }
1719     }
1720
1721     DeleteDC( hMemDC );
1722     if (hXorBits) DeleteObject( hXorBits );
1723     if (hAndBits) DeleteObject( hAndBits );
1724     release_icon_ptr( hIcon, ptr );
1725     SetTextColor( hdc, oldFg );
1726     SetBkColor( hdc, oldBg );
1727     return TRUE;
1728 }
1729
1730 /***********************************************************************
1731  *              SetCursor (USER32.@)
1732  *
1733  * Set the cursor shape.
1734  *
1735  * RETURNS
1736  *      A handle to the previous cursor shape.
1737  */
1738 HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1739 {
1740     struct user_thread_info *thread_info = get_user_thread_info();
1741     HCURSOR hOldCursor;
1742
1743     if (hCursor == thread_info->cursor) return hCursor;  /* No change */
1744     TRACE("%p\n", hCursor);
1745     hOldCursor = thread_info->cursor;
1746     thread_info->cursor = hCursor;
1747     /* Change the cursor shape only if it is visible */
1748     if (thread_info->cursor_count >= 0)
1749     {
1750         CURSORICONINFO *info = get_icon_ptr( hCursor );
1751         /* release before calling driver (FIXME) */
1752         if (info) release_icon_ptr( hCursor, info );
1753         USER_Driver->pSetCursor( info );
1754     }
1755     return hOldCursor;
1756 }
1757
1758 /***********************************************************************
1759  *              ShowCursor (USER32.@)
1760  */
1761 INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
1762 {
1763     struct user_thread_info *thread_info = get_user_thread_info();
1764
1765     TRACE("%d, count=%d\n", bShow, thread_info->cursor_count );
1766
1767     if (bShow)
1768     {
1769         if (++thread_info->cursor_count == 0) /* Show it */
1770         {
1771             CURSORICONINFO *info = get_icon_ptr( thread_info->cursor );
1772             /* release before calling driver (FIXME) */
1773             if (info) release_icon_ptr( thread_info->cursor, info );
1774             USER_Driver->pSetCursor( info );
1775         }
1776     }
1777     else
1778     {
1779         if (--thread_info->cursor_count == -1) /* Hide it */
1780             USER_Driver->pSetCursor( NULL );
1781     }
1782     return thread_info->cursor_count;
1783 }
1784
1785 /***********************************************************************
1786  *              GetCursor (USER32.@)
1787  */
1788 HCURSOR WINAPI GetCursor(void)
1789 {
1790     return get_user_thread_info()->cursor;
1791 }
1792
1793
1794 /***********************************************************************
1795  *              ClipCursor (USER32.@)
1796  */
1797 BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
1798 {
1799     RECT virt;
1800
1801     SetRect( &virt, 0, 0, GetSystemMetrics( SM_CXVIRTUALSCREEN ),
1802                           GetSystemMetrics( SM_CYVIRTUALSCREEN ) );
1803     OffsetRect( &virt, GetSystemMetrics( SM_XVIRTUALSCREEN ),
1804                        GetSystemMetrics( SM_YVIRTUALSCREEN ) );
1805
1806     TRACE( "Clipping to: %s was: %s screen: %s\n", wine_dbgstr_rect(rect),
1807            wine_dbgstr_rect(&CURSOR_ClipRect), wine_dbgstr_rect(&virt) );
1808
1809     if (!IntersectRect( &CURSOR_ClipRect, &virt, rect ))
1810         CURSOR_ClipRect = virt;
1811
1812     USER_Driver->pClipCursor( rect );
1813     return TRUE;
1814 }
1815
1816
1817 /***********************************************************************
1818  *              GetClipCursor (USER32.@)
1819  */
1820 BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
1821 {
1822     /* If this is first time - initialize the rect */
1823     if (IsRectEmpty( &CURSOR_ClipRect )) ClipCursor( NULL );
1824
1825     return CopyRect( rect, &CURSOR_ClipRect );
1826 }
1827
1828
1829 /***********************************************************************
1830  *              SetSystemCursor (USER32.@)
1831  */
1832 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
1833 {
1834     FIXME("(%p,%08x),stub!\n",  hcur, id);
1835     return TRUE;
1836 }
1837
1838
1839 /**********************************************************************
1840  *              LookupIconIdFromDirectoryEx (USER32.@)
1841  */
1842 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
1843              INT width, INT height, UINT cFlag )
1844 {
1845     CURSORICONDIR       *dir = (CURSORICONDIR*)xdir;
1846     UINT retVal = 0;
1847     if( dir && !dir->idReserved && (dir->idType & 3) )
1848     {
1849         CURSORICONDIRENTRY* entry;
1850
1851         const HDC hdc = GetDC(0);
1852         const int depth = (cFlag & LR_MONOCHROME) ?
1853             1 : GetDeviceCaps(hdc, BITSPIXEL);
1854         ReleaseDC(0, hdc);
1855
1856         if( bIcon )
1857             entry = CURSORICON_FindBestIconRes( dir, width, height, depth );
1858         else
1859             entry = CURSORICON_FindBestCursorRes( dir, width, height, depth );
1860
1861         if( entry ) retVal = entry->wResId;
1862     }
1863     else WARN_(cursor)("invalid resource directory\n");
1864     return retVal;
1865 }
1866
1867 /**********************************************************************
1868  *              LookupIconIdFromDirectory (USER32.@)
1869  */
1870 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
1871 {
1872     return LookupIconIdFromDirectoryEx( dir, bIcon,
1873            bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
1874            bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
1875 }
1876
1877 /***********************************************************************
1878  *              LoadCursorW (USER32.@)
1879  */
1880 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
1881 {
1882     TRACE("%p, %s\n", hInstance, debugstr_w(name));
1883
1884     return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1885                        LR_SHARED | LR_DEFAULTSIZE );
1886 }
1887
1888 /***********************************************************************
1889  *              LoadCursorA (USER32.@)
1890  */
1891 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
1892 {
1893     TRACE("%p, %s\n", hInstance, debugstr_a(name));
1894
1895     return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1896                        LR_SHARED | LR_DEFAULTSIZE );
1897 }
1898
1899 /***********************************************************************
1900  *              LoadCursorFromFileW (USER32.@)
1901  */
1902 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1903 {
1904     TRACE("%s\n", debugstr_w(name));
1905
1906     return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1907                        LR_LOADFROMFILE | LR_DEFAULTSIZE );
1908 }
1909
1910 /***********************************************************************
1911  *              LoadCursorFromFileA (USER32.@)
1912  */
1913 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1914 {
1915     TRACE("%s\n", debugstr_a(name));
1916
1917     return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1918                        LR_LOADFROMFILE | LR_DEFAULTSIZE );
1919 }
1920
1921 /***********************************************************************
1922  *              LoadIconW (USER32.@)
1923  */
1924 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
1925 {
1926     TRACE("%p, %s\n", hInstance, debugstr_w(name));
1927
1928     return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1929                        LR_SHARED | LR_DEFAULTSIZE );
1930 }
1931
1932 /***********************************************************************
1933  *              LoadIconA (USER32.@)
1934  */
1935 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
1936 {
1937     TRACE("%p, %s\n", hInstance, debugstr_a(name));
1938
1939     return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1940                        LR_SHARED | LR_DEFAULTSIZE );
1941 }
1942
1943 /**********************************************************************
1944  *              GetIconInfo (USER32.@)
1945  */
1946 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
1947 {
1948     CURSORICONINFO *ciconinfo;
1949     INT height;
1950
1951     if (!(ciconinfo = get_icon_ptr( hIcon ))) return FALSE;
1952
1953     TRACE("%p => %dx%d, %d bpp\n", hIcon,
1954           ciconinfo->nWidth, ciconinfo->nHeight, ciconinfo->bBitsPerPixel);
1955
1956     if ( (ciconinfo->ptHotSpot.x == ICON_HOTSPOT) &&
1957          (ciconinfo->ptHotSpot.y == ICON_HOTSPOT) )
1958     {
1959       iconinfo->fIcon    = TRUE;
1960       iconinfo->xHotspot = ciconinfo->nWidth / 2;
1961       iconinfo->yHotspot = ciconinfo->nHeight / 2;
1962     }
1963     else
1964     {
1965       iconinfo->fIcon    = FALSE;
1966       iconinfo->xHotspot = ciconinfo->ptHotSpot.x;
1967       iconinfo->yHotspot = ciconinfo->ptHotSpot.y;
1968     }
1969
1970     height = ciconinfo->nHeight;
1971
1972     if (ciconinfo->bBitsPerPixel > 1)
1973     {
1974         iconinfo->hbmColor = CreateBitmap( ciconinfo->nWidth, ciconinfo->nHeight,
1975                                 ciconinfo->bPlanes, ciconinfo->bBitsPerPixel,
1976                                 (char *)(ciconinfo + 1)
1977                                 + ciconinfo->nHeight *
1978                                 get_bitmap_width_bytes (ciconinfo->nWidth,1) );
1979     }
1980     else
1981     {
1982         iconinfo->hbmColor = 0;
1983         height *= 2;
1984     }
1985
1986     iconinfo->hbmMask = CreateBitmap ( ciconinfo->nWidth, height,
1987                                 1, 1, ciconinfo + 1);
1988     release_icon_ptr( hIcon, ciconinfo );
1989
1990     return TRUE;
1991 }
1992
1993 /**********************************************************************
1994  *              CreateIconIndirect (USER32.@)
1995  */
1996 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
1997 {
1998     DIBSECTION bmpXor;
1999     BITMAP bmpAnd;
2000     HICON hObj;
2001     int xor_objsize = 0, sizeXor = 0, sizeAnd, planes, bpp;
2002
2003     TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
2004            iconinfo->hbmColor, iconinfo->hbmMask,
2005            iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
2006
2007     if (!iconinfo->hbmMask) return 0;
2008
2009     planes = GetDeviceCaps( screen_dc, PLANES );
2010     bpp = GetDeviceCaps( screen_dc, BITSPIXEL );
2011
2012     if (iconinfo->hbmColor)
2013     {
2014         xor_objsize = GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2015         TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2016                bmpXor.dsBm.bmWidth, bmpXor.dsBm.bmHeight, bmpXor.dsBm.bmWidthBytes,
2017                bmpXor.dsBm.bmPlanes, bmpXor.dsBm.bmBitsPixel);
2018         /* we can use either depth 1 or screen depth for xor bitmap */
2019         if (bmpXor.dsBm.bmPlanes == 1 && bmpXor.dsBm.bmBitsPixel == 1) planes = bpp = 1;
2020         sizeXor = bmpXor.dsBm.bmHeight * planes * get_bitmap_width_bytes( bmpXor.dsBm.bmWidth, bpp );
2021     }
2022     GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
2023     TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2024            bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
2025            bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
2026
2027     sizeAnd = bmpAnd.bmHeight * get_bitmap_width_bytes(bmpAnd.bmWidth, 1);
2028
2029     hObj = alloc_icon_handle( sizeof(CURSORICONINFO) + sizeXor + sizeAnd );
2030     if (hObj)
2031     {
2032         CURSORICONINFO *info = get_icon_ptr( hObj );
2033
2034         /* If we are creating an icon, the hotspot is unused */
2035         if (iconinfo->fIcon)
2036         {
2037             info->ptHotSpot.x   = ICON_HOTSPOT;
2038             info->ptHotSpot.y   = ICON_HOTSPOT;
2039         }
2040         else
2041         {
2042             info->ptHotSpot.x   = iconinfo->xHotspot;
2043             info->ptHotSpot.y   = iconinfo->yHotspot;
2044         }
2045
2046         if (iconinfo->hbmColor)
2047         {
2048             info->nWidth        = bmpXor.dsBm.bmWidth;
2049             info->nHeight       = bmpXor.dsBm.bmHeight;
2050             info->nWidthBytes   = bmpXor.dsBm.bmWidthBytes;
2051             info->bPlanes       = planes;
2052             info->bBitsPerPixel = bpp;
2053         }
2054         else
2055         {
2056             info->nWidth        = bmpAnd.bmWidth;
2057             info->nHeight       = bmpAnd.bmHeight / 2;
2058             info->nWidthBytes   = get_bitmap_width_bytes(bmpAnd.bmWidth, 1);
2059             info->bPlanes       = 1;
2060             info->bBitsPerPixel = 1;
2061         }
2062
2063         /* Transfer the bitmap bits to the CURSORICONINFO structure */
2064
2065         /* Some apps pass a color bitmap as a mask, convert it to b/w */
2066         if (bmpAnd.bmBitsPixel == 1)
2067         {
2068             GetBitmapBits( iconinfo->hbmMask, sizeAnd, info + 1 );
2069         }
2070         else
2071         {
2072             HDC hdc_mem, hdc_mem2;
2073             HBITMAP hbmp_mem_old, hbmp_mem2_old, hbmp_mono;
2074
2075             hdc_mem = CreateCompatibleDC( 0 );
2076             hdc_mem2 = CreateCompatibleDC( 0 );
2077
2078             hbmp_mono = CreateBitmap( bmpAnd.bmWidth, bmpAnd.bmHeight, 1, 1, NULL );
2079
2080             hbmp_mem_old = SelectObject( hdc_mem, iconinfo->hbmMask );
2081             hbmp_mem2_old = SelectObject( hdc_mem2, hbmp_mono );
2082
2083             BitBlt( hdc_mem2, 0, 0, bmpAnd.bmWidth, bmpAnd.bmHeight, hdc_mem, 0, 0, SRCCOPY );
2084
2085             SelectObject( hdc_mem, hbmp_mem_old );
2086             SelectObject( hdc_mem2, hbmp_mem2_old );
2087
2088             DeleteDC( hdc_mem );
2089             DeleteDC( hdc_mem2 );
2090
2091             GetBitmapBits( hbmp_mono, sizeAnd, info + 1 );
2092             DeleteObject( hbmp_mono );
2093         }
2094
2095         if (iconinfo->hbmColor)
2096         {
2097             char *dst_bits = (char*)(info + 1) + sizeAnd;
2098
2099             if (bmpXor.dsBm.bmPlanes == planes && bmpXor.dsBm.bmBitsPixel == bpp)
2100                 GetBitmapBits( iconinfo->hbmColor, sizeXor, dst_bits );
2101             else
2102             {
2103                 BITMAPINFO bminfo;
2104                 int dib_width = get_dib_width_bytes( info->nWidth, info->bBitsPerPixel );
2105                 int bitmap_width = get_bitmap_width_bytes( info->nWidth, info->bBitsPerPixel );
2106
2107                 bminfo.bmiHeader.biSize = sizeof(bminfo);
2108                 bminfo.bmiHeader.biWidth = info->nWidth;
2109                 bminfo.bmiHeader.biHeight = info->nHeight;
2110                 bminfo.bmiHeader.biPlanes = info->bPlanes;
2111                 bminfo.bmiHeader.biBitCount = info->bBitsPerPixel;
2112                 bminfo.bmiHeader.biCompression = BI_RGB;
2113                 bminfo.bmiHeader.biSizeImage = info->nHeight * dib_width;
2114                 bminfo.bmiHeader.biXPelsPerMeter = 0;
2115                 bminfo.bmiHeader.biYPelsPerMeter = 0;
2116                 bminfo.bmiHeader.biClrUsed = 0;
2117                 bminfo.bmiHeader.biClrImportant = 0;
2118
2119                 /* swap lines for dib sections */
2120                 if (xor_objsize == sizeof(DIBSECTION))
2121                     bminfo.bmiHeader.biHeight = -bminfo.bmiHeader.biHeight;
2122
2123                 if (dib_width != bitmap_width)  /* need to fixup alignment */
2124                 {
2125                     char *src_bits = HeapAlloc( GetProcessHeap(), 0, bminfo.bmiHeader.biSizeImage );
2126
2127                     if (src_bits && GetDIBits( screen_dc, iconinfo->hbmColor, 0, info->nHeight,
2128                                                src_bits, &bminfo, DIB_RGB_COLORS ))
2129                     {
2130                         int y;
2131                         for (y = 0; y < info->nHeight; y++)
2132                             memcpy( dst_bits + y * bitmap_width, src_bits + y * dib_width, bitmap_width );
2133                     }
2134                     HeapFree( GetProcessHeap(), 0, src_bits );
2135                 }
2136                 else
2137                     GetDIBits( screen_dc, iconinfo->hbmColor, 0, info->nHeight,
2138                                dst_bits, &bminfo, DIB_RGB_COLORS );
2139             }
2140         }
2141         release_icon_ptr( hObj, info );
2142     }
2143     return hObj;
2144 }
2145
2146 /******************************************************************************
2147  *              DrawIconEx (USER32.@) Draws an icon or cursor on device context
2148  *
2149  * NOTES
2150  *    Why is this using SM_CXICON instead of SM_CXCURSOR?
2151  *
2152  * PARAMS
2153  *    hdc     [I] Handle to device context
2154  *    x0      [I] X coordinate of upper left corner
2155  *    y0      [I] Y coordinate of upper left corner
2156  *    hIcon   [I] Handle to icon to draw
2157  *    cxWidth [I] Width of icon
2158  *    cyWidth [I] Height of icon
2159  *    istep   [I] Index of frame in animated cursor
2160  *    hbr     [I] Handle to background brush
2161  *    flags   [I] Icon-drawing flags
2162  *
2163  * RETURNS
2164  *    Success: TRUE
2165  *    Failure: FALSE
2166  */
2167 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2168                             INT cxWidth, INT cyWidth, UINT istep,
2169                             HBRUSH hbr, UINT flags )
2170 {
2171     CURSORICONINFO *ptr;
2172     HDC hDC_off = 0, hMemDC;
2173     BOOL result = FALSE, DoOffscreen;
2174     HBITMAP hB_off = 0, hOld = 0;
2175     unsigned char *xorBitmapBits;
2176     unsigned int xorLength;
2177     BOOL has_alpha = FALSE;
2178
2179     TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2180                  hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2181
2182     if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2183     if (!(hMemDC = CreateCompatibleDC( hdc )))
2184     {
2185         release_icon_ptr( hIcon, ptr );
2186         return FALSE;
2187     }
2188
2189     if (istep)
2190         FIXME_(icon)("Ignoring istep=%d\n", istep);
2191     if (flags & DI_NOMIRROR)
2192         FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
2193
2194     xorLength = ptr->nHeight * get_bitmap_width_bytes(
2195         ptr->nWidth, ptr->bBitsPerPixel);
2196     xorBitmapBits = (unsigned char *)(ptr + 1) + ptr->nHeight *
2197                     get_bitmap_width_bytes(ptr->nWidth, 1);
2198
2199     if (flags & DI_IMAGE)
2200         has_alpha = bitmap_has_alpha_channel(
2201             ptr->bBitsPerPixel, xorBitmapBits, xorLength);
2202
2203     /* Calculate the size of the destination image.  */
2204     if (cxWidth == 0)
2205     {
2206         if (flags & DI_DEFAULTSIZE)
2207             cxWidth = GetSystemMetrics (SM_CXICON);
2208         else
2209             cxWidth = ptr->nWidth;
2210     }
2211     if (cyWidth == 0)
2212     {
2213         if (flags & DI_DEFAULTSIZE)
2214             cyWidth = GetSystemMetrics (SM_CYICON);
2215         else
2216             cyWidth = ptr->nHeight;
2217     }
2218
2219     DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2220
2221     if (DoOffscreen) {
2222         RECT r;
2223
2224         r.left = 0;
2225         r.top = 0;
2226         r.right = cxWidth;
2227         r.bottom = cxWidth;
2228
2229         hDC_off = CreateCompatibleDC(hdc);
2230         hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth);
2231         if (hDC_off && hB_off) {
2232             hOld = SelectObject(hDC_off, hB_off);
2233             FillRect(hDC_off, &r, hbr);
2234         }
2235     }
2236
2237     if (hMemDC && (!DoOffscreen || (hDC_off && hB_off)))
2238     {
2239         HBITMAP hBitTemp;
2240         HBITMAP hXorBits = NULL, hAndBits = NULL;
2241         COLORREF  oldFg, oldBg;
2242         INT     nStretchMode;
2243
2244         nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2245
2246         oldFg = SetTextColor( hdc, RGB(0,0,0) );
2247         oldBg = SetBkColor( hdc, RGB(255,255,255) );
2248
2249         if (((flags & DI_MASK) && !(flags & DI_IMAGE)) ||
2250             ((flags & DI_MASK) && !has_alpha))
2251         {
2252             hAndBits = CreateBitmap ( ptr->nWidth, ptr->nHeight, 1, 1, ptr + 1 );
2253             if (hAndBits)
2254             {
2255                 hBitTemp = SelectObject( hMemDC, hAndBits );
2256                 if (DoOffscreen)
2257                     StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
2258                                 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
2259                 else
2260                     StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
2261                                 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
2262                 SelectObject( hMemDC, hBitTemp );
2263             }
2264         }
2265
2266         if (flags & DI_IMAGE)
2267         {
2268             BITMAPINFOHEADER bmih;
2269             unsigned char *dibBits;
2270
2271             memset(&bmih, 0, sizeof(BITMAPINFOHEADER));
2272             bmih.biSize = sizeof(BITMAPINFOHEADER);
2273             bmih.biWidth = ptr->nWidth;
2274             bmih.biHeight = -ptr->nHeight;
2275             bmih.biPlanes = ptr->bPlanes;
2276             bmih.biBitCount = ptr->bBitsPerPixel;
2277             bmih.biCompression = BI_RGB;
2278
2279             hXorBits = CreateDIBSection(hdc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS,
2280                                         (void*)&dibBits, NULL, 0);
2281
2282             if (hXorBits && dibBits)
2283             {
2284                 if(has_alpha)
2285                 {
2286                     BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2287
2288                     /* Do the alpha blending render */
2289                     premultiply_alpha_channel(dibBits, xorBitmapBits, xorLength);
2290                     hBitTemp = SelectObject( hMemDC, hXorBits );
2291
2292                     if (DoOffscreen)
2293                         GdiAlphaBlend(hDC_off, 0, 0, cxWidth, cyWidth, hMemDC,
2294                                         0, 0, ptr->nWidth, ptr->nHeight, pixelblend);
2295                     else
2296                         GdiAlphaBlend(hdc, x0, y0, cxWidth, cyWidth, hMemDC,
2297                                         0, 0, ptr->nWidth, ptr->nHeight, pixelblend);
2298
2299                     SelectObject( hMemDC, hBitTemp );
2300                 }
2301                 else
2302                 {
2303                     memcpy(dibBits, xorBitmapBits, xorLength);
2304                     hBitTemp = SelectObject( hMemDC, hXorBits );
2305                     if (DoOffscreen)
2306                         StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
2307                                     hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
2308                     else
2309                         StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
2310                                     hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
2311                     SelectObject( hMemDC, hBitTemp );
2312                 }
2313
2314                 DeleteObject( hXorBits );
2315             }
2316         }
2317
2318         result = TRUE;
2319
2320         SetTextColor( hdc, oldFg );
2321         SetBkColor( hdc, oldBg );
2322
2323         if (hAndBits) DeleteObject( hAndBits );
2324         SetStretchBltMode (hdc, nStretchMode);
2325         if (DoOffscreen) {
2326             BitBlt(hdc, x0, y0, cxWidth, cyWidth, hDC_off, 0, 0, SRCCOPY);
2327             SelectObject(hDC_off, hOld);
2328         }
2329     }
2330     if (hMemDC) DeleteDC( hMemDC );
2331     if (hDC_off) DeleteDC(hDC_off);
2332     if (hB_off) DeleteObject(hB_off);
2333     release_icon_ptr( hIcon, ptr );
2334     return result;
2335 }
2336
2337 /***********************************************************************
2338  *           DIB_FixColorsToLoadflags
2339  *
2340  * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2341  * are in loadflags
2342  */
2343 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2344 {
2345     int colors;
2346     COLORREF c_W, c_S, c_F, c_L, c_C;
2347     int incr,i;
2348     RGBQUAD *ptr;
2349     int bitmap_type;
2350     LONG width;
2351     LONG height;
2352     WORD bpp;
2353     DWORD compr;
2354
2355     if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2356     {
2357         WARN_(resource)("Invalid bitmap\n");
2358         return;
2359     }
2360
2361     if (bpp > 8) return;
2362
2363     if (bitmap_type == 0) /* BITMAPCOREHEADER */
2364     {
2365         incr = 3;
2366         colors = 1 << bpp;
2367     }
2368     else
2369     {
2370         incr = 4;
2371         colors = bmi->bmiHeader.biClrUsed;
2372         if (colors > 256) colors = 256;
2373         if (!colors && (bpp <= 8)) colors = 1 << bpp;
2374     }
2375
2376     c_W = GetSysColor(COLOR_WINDOW);
2377     c_S = GetSysColor(COLOR_3DSHADOW);
2378     c_F = GetSysColor(COLOR_3DFACE);
2379     c_L = GetSysColor(COLOR_3DLIGHT);
2380
2381     if (loadflags & LR_LOADTRANSPARENT) {
2382         switch (bpp) {
2383         case 1: pix = pix >> 7; break;
2384         case 4: pix = pix >> 4; break;
2385         case 8: break;
2386         default:
2387             WARN_(resource)("(%d): Unsupported depth\n", bpp);
2388             return;
2389         }
2390         if (pix >= colors) {
2391             WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2392             return;
2393         }
2394         if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2395         ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2396         ptr->rgbBlue = GetBValue(c_W);
2397         ptr->rgbGreen = GetGValue(c_W);
2398         ptr->rgbRed = GetRValue(c_W);
2399     }
2400     if (loadflags & LR_LOADMAP3DCOLORS)
2401         for (i=0; i<colors; i++) {
2402             ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2403             c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2404             if (c_C == RGB(128, 128, 128)) {
2405                 ptr->rgbRed = GetRValue(c_S);
2406                 ptr->rgbGreen = GetGValue(c_S);
2407                 ptr->rgbBlue = GetBValue(c_S);
2408             } else if (c_C == RGB(192, 192, 192)) {
2409                 ptr->rgbRed = GetRValue(c_F);
2410                 ptr->rgbGreen = GetGValue(c_F);
2411                 ptr->rgbBlue = GetBValue(c_F);
2412             } else if (c_C == RGB(223, 223, 223)) {
2413                 ptr->rgbRed = GetRValue(c_L);
2414                 ptr->rgbGreen = GetGValue(c_L);
2415                 ptr->rgbBlue = GetBValue(c_L);
2416             }
2417         }
2418 }
2419
2420
2421 /**********************************************************************
2422  *       BITMAP_Load
2423  */
2424 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2425                             INT desiredx, INT desiredy, UINT loadflags )
2426 {
2427     HBITMAP hbitmap = 0, orig_bm;
2428     HRSRC hRsrc;
2429     HGLOBAL handle;
2430     char *ptr = NULL;
2431     BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2432     int size;
2433     BYTE pix;
2434     char *bits;
2435     LONG width, height, new_width, new_height;
2436     WORD bpp_dummy;
2437     DWORD compr_dummy;
2438     INT bm_type;
2439     HDC screen_mem_dc = NULL;
2440
2441     if (!(loadflags & LR_LOADFROMFILE))
2442     {
2443         if (!instance)
2444         {
2445             /* OEM bitmap: try to load the resource from user32.dll */
2446             instance = user32_module;
2447         }
2448
2449         if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2450         if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2451
2452         if ((info = LockResource( handle )) == NULL) return 0;
2453     }
2454     else
2455     {
2456         BITMAPFILEHEADER * bmfh;
2457
2458         if (!(ptr = map_fileW( name, NULL ))) return 0;
2459         info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2460         bmfh = (BITMAPFILEHEADER *)ptr;
2461         if (!(  bmfh->bfType == 0x4d42 /* 'BM' */ &&
2462                 bmfh->bfReserved1 == 0 &&
2463                 bmfh->bfReserved2 == 0))
2464         {
2465             WARN("Invalid/unsupported bitmap format!\n");
2466             UnmapViewOfFile( ptr );
2467             return 0;
2468         }
2469     }
2470
2471     size = bitmap_info_size(info, DIB_RGB_COLORS);
2472     fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2473     scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2474
2475     if (!fix_info || !scaled_info) goto end;
2476     memcpy(fix_info, info, size);
2477
2478     pix = *((LPBYTE)info + size);
2479     DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2480
2481     memcpy(scaled_info, fix_info, size);
2482     bm_type = DIB_GetBitmapInfo( &fix_info->bmiHeader, &width, &height,
2483                                  &bpp_dummy, &compr_dummy);
2484     if(desiredx != 0)
2485         new_width = desiredx;
2486     else
2487         new_width = width;
2488
2489     if(desiredy != 0)
2490         new_height = height > 0 ? desiredy : -desiredy;
2491     else
2492         new_height = height;
2493
2494     if(bm_type == 0)
2495     {
2496         BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2497         core->bcWidth = new_width;
2498         core->bcHeight = new_height;
2499     }
2500     else
2501     {
2502         scaled_info->bmiHeader.biWidth = new_width;
2503         scaled_info->bmiHeader.biHeight = new_height;
2504     }
2505
2506     if (new_height < 0) new_height = -new_height;
2507
2508     if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2509     if (!(screen_mem_dc = CreateCompatibleDC( screen_dc ))) goto end;
2510
2511     bits = (char *)info + size;
2512
2513     if (loadflags & LR_CREATEDIBSECTION)
2514     {
2515         scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2516         hbitmap = CreateDIBSection(screen_dc, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2517     }
2518     else
2519     {
2520         if (is_dib_monochrome(fix_info))
2521             hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2522         else
2523             hbitmap = CreateCompatibleBitmap(screen_dc, new_width, new_height);        
2524     }
2525
2526     orig_bm = SelectObject(screen_mem_dc, hbitmap);
2527     StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2528     SelectObject(screen_mem_dc, orig_bm);
2529
2530 end:
2531     if (screen_mem_dc) DeleteDC(screen_mem_dc);
2532     HeapFree(GetProcessHeap(), 0, scaled_info);
2533     HeapFree(GetProcessHeap(), 0, fix_info);
2534     if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2535
2536     return hbitmap;
2537 }
2538
2539 /**********************************************************************
2540  *              LoadImageA (USER32.@)
2541  *
2542  * See LoadImageW.
2543  */
2544 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2545                               INT desiredx, INT desiredy, UINT loadflags)
2546 {
2547     HANDLE res;
2548     LPWSTR u_name;
2549
2550     if (IS_INTRESOURCE(name))
2551         return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2552
2553     __TRY {
2554         DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2555         u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2556         MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2557     }
2558     __EXCEPT_PAGE_FAULT {
2559         SetLastError( ERROR_INVALID_PARAMETER );
2560         return 0;
2561     }
2562     __ENDTRY
2563     res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2564     HeapFree(GetProcessHeap(), 0, u_name);
2565     return res;
2566 }
2567
2568
2569 /******************************************************************************
2570  *              LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2571  *
2572  * PARAMS
2573  *    hinst     [I] Handle of instance that contains image
2574  *    name      [I] Name of image
2575  *    type      [I] Type of image
2576  *    desiredx  [I] Desired width
2577  *    desiredy  [I] Desired height
2578  *    loadflags [I] Load flags
2579  *
2580  * RETURNS
2581  *    Success: Handle to newly loaded image
2582  *    Failure: NULL
2583  *
2584  * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2585  */
2586 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2587                 INT desiredx, INT desiredy, UINT loadflags )
2588 {
2589     TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
2590                      hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
2591
2592     if (loadflags & LR_DEFAULTSIZE) {
2593         if (type == IMAGE_ICON) {
2594             if (!desiredx) desiredx = GetSystemMetrics(SM_CXICON);
2595             if (!desiredy) desiredy = GetSystemMetrics(SM_CYICON);
2596         } else if (type == IMAGE_CURSOR) {
2597             if (!desiredx) desiredx = GetSystemMetrics(SM_CXCURSOR);
2598             if (!desiredy) desiredy = GetSystemMetrics(SM_CYCURSOR);
2599         }
2600     }
2601     if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
2602     switch (type) {
2603     case IMAGE_BITMAP:
2604         return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2605
2606     case IMAGE_ICON:
2607         if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2608         if (screen_dc)
2609         {
2610             return CURSORICON_Load(hinst, name, desiredx, desiredy,
2611                                    GetDeviceCaps(screen_dc, BITSPIXEL),
2612                                    FALSE, loadflags);
2613         }
2614         break;
2615
2616     case IMAGE_CURSOR:
2617         return CURSORICON_Load(hinst, name, desiredx, desiredy,
2618                                1, TRUE, loadflags);
2619     }
2620     return 0;
2621 }
2622
2623 /******************************************************************************
2624  *              CopyImage (USER32.@) Creates new image and copies attributes to it
2625  *
2626  * PARAMS
2627  *    hnd      [I] Handle to image to copy
2628  *    type     [I] Type of image to copy
2629  *    desiredx [I] Desired width of new image
2630  *    desiredy [I] Desired height of new image
2631  *    flags    [I] Copy flags
2632  *
2633  * RETURNS
2634  *    Success: Handle to newly created image
2635  *    Failure: NULL
2636  *
2637  * BUGS
2638  *    Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
2639  *    all other versions (95/2000/XP have been tested) ignore it.
2640  *
2641  * NOTES
2642  *    If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
2643  *    a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
2644  *    the copy will have the same depth as the screen.
2645  *    The content of the image will only be copied if the bit depth of the
2646  *    original image is compatible with the bit depth of the screen, or
2647  *    if the source is a DIB section.
2648  *    The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
2649  */
2650 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2651                              INT desiredy, UINT flags )
2652 {
2653     TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
2654           hnd, type, desiredx, desiredy, flags);
2655
2656     switch (type)
2657     {
2658         case IMAGE_BITMAP:
2659         {
2660             HBITMAP res = NULL;
2661             DIBSECTION ds;
2662             int objSize;
2663             BITMAPINFO * bi;
2664
2665             objSize = GetObjectW( hnd, sizeof(ds), &ds );
2666             if (!objSize) return 0;
2667             if ((desiredx < 0) || (desiredy < 0)) return 0;
2668
2669             if (flags & LR_COPYFROMRESOURCE)
2670             {
2671                 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
2672             }
2673
2674             if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
2675             if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
2676
2677             /* Allocate memory for a BITMAPINFOHEADER structure and a
2678                color table. The maximum number of colors in a color table
2679                is 256 which corresponds to a bitmap with depth 8.
2680                Bitmaps with higher depths don't have color tables. */
2681             bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
2682             if (!bi) return 0;
2683
2684             bi->bmiHeader.biSize        = sizeof(bi->bmiHeader);
2685             bi->bmiHeader.biPlanes      = ds.dsBm.bmPlanes;
2686             bi->bmiHeader.biBitCount    = ds.dsBm.bmBitsPixel;
2687             bi->bmiHeader.biCompression = BI_RGB;
2688
2689             if (flags & LR_CREATEDIBSECTION)
2690             {
2691                 /* Create a DIB section. LR_MONOCHROME is ignored */
2692                 void * bits;
2693                 HDC dc = CreateCompatibleDC(NULL);
2694
2695                 if (objSize == sizeof(DIBSECTION))
2696                 {
2697                     /* The source bitmap is a DIB.
2698                        Get its attributes to create an exact copy */
2699                     memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
2700                 }
2701
2702                 /* Get the color table or the color masks */
2703                 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2704
2705                 bi->bmiHeader.biWidth  = desiredx;
2706                 bi->bmiHeader.biHeight = desiredy;
2707                 bi->bmiHeader.biSizeImage = 0;
2708
2709                 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
2710                 DeleteDC(dc);
2711             }
2712             else
2713             {
2714                 /* Create a device-dependent bitmap */
2715
2716                 BOOL monochrome = (flags & LR_MONOCHROME);
2717
2718                 if (objSize == sizeof(DIBSECTION))
2719                 {
2720                     /* The source bitmap is a DIB section.
2721                        Get its attributes */
2722                     HDC dc = CreateCompatibleDC(NULL);
2723                     bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
2724                     bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
2725                     GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2726                     DeleteDC(dc);
2727
2728                     if (!monochrome && ds.dsBm.bmBitsPixel == 1)
2729                     {
2730                         /* Look if the colors of the DIB are black and white */
2731
2732                         monochrome = 
2733                               (bi->bmiColors[0].rgbRed == 0xff
2734                             && bi->bmiColors[0].rgbGreen == 0xff
2735                             && bi->bmiColors[0].rgbBlue == 0xff
2736                             && bi->bmiColors[0].rgbReserved == 0
2737                             && bi->bmiColors[1].rgbRed == 0
2738                             && bi->bmiColors[1].rgbGreen == 0
2739                             && bi->bmiColors[1].rgbBlue == 0
2740                             && bi->bmiColors[1].rgbReserved == 0)
2741                             ||
2742                               (bi->bmiColors[0].rgbRed == 0
2743                             && bi->bmiColors[0].rgbGreen == 0
2744                             && bi->bmiColors[0].rgbBlue == 0
2745                             && bi->bmiColors[0].rgbReserved == 0
2746                             && bi->bmiColors[1].rgbRed == 0xff
2747                             && bi->bmiColors[1].rgbGreen == 0xff
2748                             && bi->bmiColors[1].rgbBlue == 0xff
2749                             && bi->bmiColors[1].rgbReserved == 0);
2750                     }
2751                 }
2752                 else if (!monochrome)
2753                 {
2754                     monochrome = ds.dsBm.bmBitsPixel == 1;
2755                 }
2756
2757                 if (monochrome)
2758                 {
2759                     res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
2760                 }
2761                 else
2762                 {
2763                     HDC screenDC = GetDC(NULL);
2764                     res = CreateCompatibleBitmap(screenDC, desiredx, desiredy);
2765                     ReleaseDC(NULL, screenDC);
2766                 }
2767             }
2768
2769             if (res)
2770             {
2771                 /* Only copy the bitmap if it's a DIB section or if it's
2772                    compatible to the screen */
2773                 BOOL copyContents;
2774
2775                 if (objSize == sizeof(DIBSECTION))
2776                 {
2777                     copyContents = TRUE;
2778                 }
2779                 else
2780                 {
2781                     HDC screenDC = GetDC(NULL);
2782                     int screen_depth = GetDeviceCaps(screenDC, BITSPIXEL);
2783                     ReleaseDC(NULL, screenDC);
2784
2785                     copyContents = (ds.dsBm.bmBitsPixel == 1 || ds.dsBm.bmBitsPixel == screen_depth);
2786                 }
2787
2788                 if (copyContents)
2789                 {
2790                     /* The source bitmap may already be selected in a device context,
2791                        use GetDIBits/StretchDIBits and not StretchBlt  */
2792
2793                     HDC dc;
2794                     void * bits;
2795
2796                     dc = CreateCompatibleDC(NULL);
2797
2798                     bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
2799                     bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
2800                     bi->bmiHeader.biSizeImage = 0;
2801                     bi->bmiHeader.biClrUsed = 0;
2802                     bi->bmiHeader.biClrImportant = 0;
2803
2804                     /* Fill in biSizeImage */
2805                     GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2806                     bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
2807
2808                     if (bits)
2809                     {
2810                         HBITMAP oldBmp;
2811
2812                         /* Get the image bits of the source bitmap */
2813                         GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
2814
2815                         /* Copy it to the destination bitmap */
2816                         oldBmp = SelectObject(dc, res);
2817                         StretchDIBits(dc, 0, 0, desiredx, desiredy,
2818                                       0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
2819                                       bits, bi, DIB_RGB_COLORS, SRCCOPY);
2820                         SelectObject(dc, oldBmp);
2821
2822                         HeapFree(GetProcessHeap(), 0, bits);
2823                     }
2824
2825                     DeleteDC(dc);
2826                 }
2827
2828                 if (flags & LR_COPYDELETEORG)
2829                 {
2830                     DeleteObject(hnd);
2831                 }
2832             }
2833             HeapFree(GetProcessHeap(), 0, bi);
2834             return res;
2835         }
2836         case IMAGE_ICON:
2837                 return CURSORICON_ExtCopy(hnd,type, desiredx, desiredy, flags);
2838         case IMAGE_CURSOR:
2839                 /* Should call CURSORICON_ExtCopy but more testing
2840                  * needs to be done before we change this
2841                  */
2842                 if (flags) FIXME("Flags are ignored\n");
2843                 return CopyCursor(hnd);
2844     }
2845     return 0;
2846 }
2847
2848
2849 /******************************************************************************
2850  *              LoadBitmapW (USER32.@) Loads bitmap from the executable file
2851  *
2852  * RETURNS
2853  *    Success: Handle to specified bitmap
2854  *    Failure: NULL
2855  */
2856 HBITMAP WINAPI LoadBitmapW(
2857     HINSTANCE instance, /* [in] Handle to application instance */
2858     LPCWSTR name)         /* [in] Address of bitmap resource name */
2859 {
2860     return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2861 }
2862
2863 /**********************************************************************
2864  *              LoadBitmapA (USER32.@)
2865  *
2866  * See LoadBitmapW.
2867  */
2868 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
2869 {
2870     return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2871 }