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