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