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