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