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