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