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