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