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