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