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