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