user32: Don't cache 16-bit instance resources on the 32-bit side.
[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     /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1181     if (!HIWORD( hInstance )) loadflags &= ~LR_SHARED;
1182
1183     /* Get directory resource ID */
1184
1185     if (!(hRsrc = FindResourceW( hInstance, name,
1186                                  (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1187         return 0;
1188     hGroupRsrc = hRsrc;
1189
1190     /* Find the best entry in the directory */
1191
1192     if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1193     if (!(dir = LockResource( handle ))) return 0;
1194     if (fCursor)
1195         dirEntry = CURSORICON_FindBestCursorRes( dir, width, height, colors );
1196     else
1197         dirEntry = CURSORICON_FindBestIconRes( dir, width, height, colors );
1198     if (!dirEntry) return 0;
1199     wResId = dirEntry->wResId;
1200     dwBytesInRes = dirEntry->dwBytesInRes;
1201     FreeResource( handle );
1202
1203     /* Load the resource */
1204
1205     if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1206                                 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1207
1208     /* If shared icon, check whether it was already loaded */
1209     if (    (loadflags & LR_SHARED)
1210          && (hIcon = CURSORICON_FindSharedIcon( hInstance, hRsrc ) ) != 0 )
1211         return hIcon;
1212
1213     if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1214     bits = LockResource( handle );
1215     hIcon = CreateIconFromResourceEx( bits, dwBytesInRes,
1216                                       !fCursor, 0x00030000, width, height, loadflags);
1217     FreeResource( handle );
1218
1219     /* If shared icon, add to icon cache */
1220
1221     if ( hIcon && (loadflags & LR_SHARED) )
1222         CURSORICON_AddSharedIcon( hInstance, hRsrc, hGroupRsrc, hIcon );
1223
1224     return hIcon;
1225 }
1226
1227
1228 /*************************************************************************
1229  * CURSORICON_ExtCopy
1230  *
1231  * Copies an Image from the Cache if LR_COPYFROMRESOURCE is specified
1232  *
1233  * PARAMS
1234  *      Handle     [I] handle to an Image
1235  *      nType      [I] Type of Handle (IMAGE_CURSOR | IMAGE_ICON)
1236  *      iDesiredCX [I] The Desired width of the Image
1237  *      iDesiredCY [I] The desired height of the Image
1238  *      nFlags     [I] The flags from CopyImage
1239  *
1240  * RETURNS
1241  *     Success: The new handle of the Image
1242  *
1243  * NOTES
1244  *     LR_COPYDELETEORG and LR_MONOCHROME are currently not implemented.
1245  *     LR_MONOCHROME should be implemented by CreateIconFromResourceEx.
1246  *     LR_COPYFROMRESOURCE will only work if the Image is in the Cache.
1247  *
1248  *
1249  */
1250
1251 static HICON CURSORICON_ExtCopy(HICON hIcon, UINT nType,
1252                                 INT iDesiredCX, INT iDesiredCY,
1253                                 UINT nFlags)
1254 {
1255     HICON hNew=0;
1256
1257     TRACE_(icon)("hIcon %p, nType %u, iDesiredCX %i, iDesiredCY %i, nFlags %u\n",
1258                  hIcon, nType, iDesiredCX, iDesiredCY, nFlags);
1259
1260     if(hIcon == 0)
1261     {
1262         return 0;
1263     }
1264
1265     /* Best Fit or Monochrome */
1266     if( (nFlags & LR_COPYFROMRESOURCE
1267         && (iDesiredCX > 0 || iDesiredCY > 0))
1268         || nFlags & LR_MONOCHROME)
1269     {
1270         ICONCACHE* pIconCache = CURSORICON_FindCache(hIcon);
1271
1272         /* Not Found in Cache, then do a straight copy
1273         */
1274         if(pIconCache == NULL)
1275         {
1276             hNew = CopyIcon( hIcon );
1277             if(nFlags & LR_COPYFROMRESOURCE)
1278             {
1279                 TRACE_(icon)("LR_COPYFROMRESOURCE: Failed to load from cache\n");
1280             }
1281         }
1282         else
1283         {
1284             int iTargetCY = iDesiredCY, iTargetCX = iDesiredCX;
1285             LPBYTE pBits;
1286             HANDLE hMem;
1287             HRSRC hRsrc;
1288             DWORD dwBytesInRes;
1289             WORD wResId;
1290             CURSORICONDIR *pDir;
1291             CURSORICONDIRENTRY *pDirEntry;
1292             BOOL bIsIcon = (nType == IMAGE_ICON);
1293
1294             /* Completing iDesiredCX CY for Monochrome Bitmaps if needed
1295             */
1296             if(((nFlags & LR_MONOCHROME) && !(nFlags & LR_COPYFROMRESOURCE))
1297                 || (iDesiredCX == 0 && iDesiredCY == 0))
1298             {
1299                 iDesiredCY = GetSystemMetrics(bIsIcon ?
1300                     SM_CYICON : SM_CYCURSOR);
1301                 iDesiredCX = GetSystemMetrics(bIsIcon ?
1302                     SM_CXICON : SM_CXCURSOR);
1303             }
1304
1305             /* Retrieve the CURSORICONDIRENTRY
1306             */
1307             if (!(hMem = LoadResource( pIconCache->hModule ,
1308                             pIconCache->hGroupRsrc)))
1309             {
1310                 return 0;
1311             }
1312             if (!(pDir = LockResource( hMem )))
1313             {
1314                 return 0;
1315             }
1316
1317             /* Find Best Fit
1318             */
1319             if(bIsIcon)
1320             {
1321                 pDirEntry = CURSORICON_FindBestIconRes(
1322                                 pDir, iDesiredCX, iDesiredCY, 256 );
1323             }
1324             else
1325             {
1326                 pDirEntry = CURSORICON_FindBestCursorRes(
1327                                 pDir, iDesiredCX, iDesiredCY, 1);
1328             }
1329
1330             wResId = pDirEntry->wResId;
1331             dwBytesInRes = pDirEntry->dwBytesInRes;
1332             FreeResource(hMem);
1333
1334             TRACE_(icon)("ResID %u, BytesInRes %u, Width %d, Height %d DX %d, DY %d\n",
1335                 wResId, dwBytesInRes,  pDirEntry->ResInfo.icon.bWidth,
1336                 pDirEntry->ResInfo.icon.bHeight, iDesiredCX, iDesiredCY);
1337
1338             /* Get the Best Fit
1339             */
1340             if (!(hRsrc = FindResourceW(pIconCache->hModule ,
1341                 MAKEINTRESOURCEW(wResId), (LPWSTR)(bIsIcon ? RT_ICON : RT_CURSOR))))
1342             {
1343                 return 0;
1344             }
1345             if (!(hMem = LoadResource( pIconCache->hModule , hRsrc )))
1346             {
1347                 return 0;
1348             }
1349
1350             pBits = LockResource( hMem );
1351
1352             if(nFlags & LR_DEFAULTSIZE)
1353             {
1354                 iTargetCY = GetSystemMetrics(SM_CYICON);
1355                 iTargetCX = GetSystemMetrics(SM_CXICON);
1356             }
1357
1358             /* Create a New Icon with the proper dimension
1359             */
1360             hNew = CreateIconFromResourceEx( pBits, dwBytesInRes,
1361                        bIsIcon, 0x00030000, iTargetCX, iTargetCY, nFlags);
1362             FreeResource(hMem);
1363         }
1364     }
1365     else hNew = CopyIcon( hIcon );
1366     return hNew;
1367 }
1368
1369
1370 /***********************************************************************
1371  *              CreateCursor (USER32.@)
1372  */
1373 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
1374                                  INT xHotSpot, INT yHotSpot,
1375                                  INT nWidth, INT nHeight,
1376                                  LPCVOID lpANDbits, LPCVOID lpXORbits )
1377 {
1378     ICONINFO info;
1379     HCURSOR hCursor;
1380
1381     TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
1382                     nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1383
1384     info.fIcon = FALSE;
1385     info.xHotspot = xHotSpot;
1386     info.yHotspot = yHotSpot;
1387     info.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1388     info.hbmColor = CreateBitmap( nWidth, nHeight, 1, 1, lpXORbits );
1389     hCursor = CreateIconIndirect( &info );
1390     DeleteObject( info.hbmMask );
1391     DeleteObject( info.hbmColor );
1392     return hCursor;
1393 }
1394
1395
1396 /***********************************************************************
1397  *              CreateIcon (USER32.@)
1398  *
1399  *  Creates an icon based on the specified bitmaps. The bitmaps must be
1400  *  provided in a device dependent format and will be resized to
1401  *  (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1402  *  depth. The provided bitmaps must be top-down bitmaps.
1403  *  Although Windows does not support 15bpp(*) this API must support it
1404  *  for Winelib applications.
1405  *
1406  *  (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1407  *      format!
1408  *
1409  * RETURNS
1410  *  Success: handle to an icon
1411  *  Failure: NULL
1412  *
1413  * FIXME: Do we need to resize the bitmaps?
1414  */
1415 HICON WINAPI CreateIcon(
1416     HINSTANCE hInstance,  /* [in] the application's hInstance */
1417     INT       nWidth,     /* [in] the width of the provided bitmaps */
1418     INT       nHeight,    /* [in] the height of the provided bitmaps */
1419     BYTE      bPlanes,    /* [in] the number of planes in the provided bitmaps */
1420     BYTE      bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1421     LPCVOID   lpANDbits,  /* [in] a monochrome bitmap representing the icon's mask */
1422     LPCVOID   lpXORbits)  /* [in] the icon's 'color' bitmap */
1423 {
1424     ICONINFO iinfo;
1425     HICON hIcon;
1426
1427     TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
1428                  nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1429
1430     iinfo.fIcon = TRUE;
1431     iinfo.xHotspot = ICON_HOTSPOT;
1432     iinfo.yHotspot = ICON_HOTSPOT;
1433     iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1434     iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );
1435
1436     hIcon = CreateIconIndirect( &iinfo );
1437
1438     DeleteObject( iinfo.hbmMask );
1439     DeleteObject( iinfo.hbmColor );
1440
1441     return hIcon;
1442 }
1443
1444
1445 /***********************************************************************
1446  *              CopyIcon (USER32.@)
1447  */
1448 HICON WINAPI CopyIcon( HICON hIcon )
1449 {
1450     CURSORICONINFO *ptrOld, *ptrNew;
1451     int size;
1452     HICON hNew;
1453
1454     if (!(ptrOld = wow_handlers.get_icon_ptr( hIcon ))) return 0;
1455     size = sizeof(CURSORICONINFO);
1456     size += ptrOld->nHeight * get_bitmap_width_bytes( ptrOld->nWidth, 1 );  /* and bitmap */
1457     size += ptrOld->nHeight * ptrOld->nWidthBytes;  /* xor bitmap */
1458     hNew = wow_handlers.alloc_icon_handle( size );
1459     ptrNew = wow_handlers.get_icon_ptr( hNew );
1460     memcpy( ptrNew, ptrOld, size );
1461     wow_handlers.release_icon_ptr( hIcon, ptrOld );
1462     wow_handlers.release_icon_ptr( hNew, ptrNew );
1463     return hNew;
1464 }
1465
1466
1467 /***********************************************************************
1468  *              DestroyIcon (USER32.@)
1469  */
1470 BOOL WINAPI DestroyIcon( HICON hIcon )
1471 {
1472     TRACE_(icon)("%p\n", hIcon );
1473
1474     if (CURSORICON_DelSharedIcon( hIcon ) == -1)
1475         wow_handlers.free_icon_handle( hIcon );
1476     return TRUE;
1477 }
1478
1479
1480 /***********************************************************************
1481  *              DestroyCursor (USER32.@)
1482  */
1483 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
1484 {
1485     if (get_user_thread_info()->cursor == hCursor)
1486     {
1487         WARN_(cursor)("Destroying active cursor!\n" );
1488         return FALSE;
1489     }
1490     return DestroyIcon( hCursor );
1491 }
1492
1493 /***********************************************************************
1494  *      bitmap_has_alpha_channel
1495  *
1496  * Analyses bits bitmap to determine if alpha data is present.
1497  *
1498  * PARAMS
1499  *      bpp          [I] The bits-per-pixel of the bitmap
1500  *      bitmapBits   [I] A pointer to the bitmap data
1501  *      bitmapLength [I] The length of the bitmap in bytes
1502  *
1503  * RETURNS
1504  *      TRUE if an alpha channel is discovered, FALSE
1505  *
1506  * NOTE
1507  *      Windows' behaviour is that if the icon bitmap is 32-bit and at
1508  *      least one pixel has a non-zero alpha, then the bitmap is a
1509  *      treated as having an alpha channel transparentcy. Otherwise,
1510  *      it's treated as being completely opaque.
1511  *
1512  */
1513 static BOOL bitmap_has_alpha_channel( int bpp, unsigned char *bitmapBits,
1514                                       unsigned int bitmapLength )
1515 {
1516     /* Detect an alpha channel by looking for non-zero alpha pixels */
1517     if(bpp == 32)
1518     {
1519         unsigned int offset;
1520         for(offset = 3; offset < bitmapLength; offset += 4)
1521         {
1522             if(bitmapBits[offset] != 0)
1523             {
1524                 return TRUE;
1525             }
1526         }
1527     }
1528     return FALSE;
1529 }
1530
1531 /***********************************************************************
1532  *          premultiply_alpha_channel
1533  *
1534  * Premultiplies the color channels of a 32-bit bitmap by the alpha
1535  * channel. This is a necessary step that must be carried out on
1536  * the image before it is passed to GdiAlphaBlend
1537  *
1538  * PARAMS
1539  *      destBitmap   [I] The destination bitmap buffer
1540  *      srcBitmap    [I] The source bitmap buffer
1541  *      bitmapLength [I] The length of the bitmap in bytes
1542  *
1543  */
1544 static void premultiply_alpha_channel( unsigned char *destBitmap,
1545                                        unsigned char *srcBitmap,
1546                                        unsigned int bitmapLength )
1547 {
1548     unsigned char *destPixel = destBitmap;
1549     unsigned char *srcPixel = srcBitmap;
1550
1551     while(destPixel < destBitmap + bitmapLength)
1552     {
1553         unsigned char alpha = srcPixel[3];
1554         *(destPixel++) = *(srcPixel++) * alpha / 255;
1555         *(destPixel++) = *(srcPixel++) * alpha / 255;
1556         *(destPixel++) = *(srcPixel++) * alpha / 255;
1557         *(destPixel++) = *(srcPixel++);
1558     }
1559 }
1560
1561 /***********************************************************************
1562  *              DrawIcon (USER32.@)
1563  */
1564 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
1565 {
1566     CURSORICONINFO *ptr;
1567     HDC hMemDC;
1568     HBITMAP hXorBits = NULL, hAndBits = NULL, hBitTemp = NULL;
1569     COLORREF oldFg, oldBg;
1570     unsigned char *xorBitmapBits;
1571     unsigned int dibLength;
1572
1573     TRACE("%p, (%d,%d), %p\n", hdc, x, y, hIcon);
1574
1575     if (!(ptr = wow_handlers.get_icon_ptr( hIcon ))) return FALSE;
1576     if (!(hMemDC = CreateCompatibleDC( hdc )))
1577     {
1578         wow_handlers.release_icon_ptr( hIcon, ptr );
1579         return FALSE;
1580     }
1581
1582     dibLength = ptr->nHeight * get_bitmap_width_bytes(
1583         ptr->nWidth, ptr->bBitsPerPixel);
1584
1585     xorBitmapBits = (unsigned char *)(ptr + 1) + ptr->nHeight *
1586                     get_bitmap_width_bytes(ptr->nWidth, 1);
1587
1588     oldFg = SetTextColor( hdc, RGB(0,0,0) );
1589     oldBg = SetBkColor( hdc, RGB(255,255,255) );
1590
1591     if(bitmap_has_alpha_channel(ptr->bBitsPerPixel, xorBitmapBits, dibLength))
1592     {
1593         BITMAPINFOHEADER bmih;
1594         unsigned char *dibBits;
1595
1596         memset(&bmih, 0, sizeof(BITMAPINFOHEADER));
1597         bmih.biSize = sizeof(BITMAPINFOHEADER);
1598         bmih.biWidth = ptr->nWidth;
1599         bmih.biHeight = -ptr->nHeight;
1600         bmih.biPlanes = ptr->bPlanes;
1601         bmih.biBitCount = 32;
1602         bmih.biCompression = BI_RGB;
1603
1604         hXorBits = CreateDIBSection(hdc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS,
1605                                     (void*)&dibBits, NULL, 0);
1606
1607         if (hXorBits && dibBits)
1608         {
1609             BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
1610
1611             /* Do the alpha blending render */
1612             premultiply_alpha_channel(dibBits, xorBitmapBits, dibLength);
1613             hBitTemp = SelectObject( hMemDC, hXorBits );
1614             /* Destination width/height has to be "System Large" size */
1615             GdiAlphaBlend(hdc, x, y, GetSystemMetrics(SM_CXICON),
1616                             GetSystemMetrics(SM_CYICON), hMemDC,
1617                             0, 0, ptr->nWidth, ptr->nHeight, pixelblend);
1618             SelectObject( hMemDC, hBitTemp );
1619         }
1620     }
1621     else
1622     {
1623         hAndBits = CreateBitmap( ptr->nWidth, ptr->nHeight, 1, 1, ptr + 1 );
1624         hXorBits = CreateBitmap( ptr->nWidth, ptr->nHeight, ptr->bPlanes,
1625                                ptr->bBitsPerPixel, xorBitmapBits);
1626
1627         if (hXorBits && hAndBits)
1628         {
1629             hBitTemp = SelectObject( hMemDC, hAndBits );
1630             StretchBlt( hdc, x, y, GetSystemMetrics(SM_CXICON),
1631                             GetSystemMetrics(SM_CYICON), hMemDC, 0, 0,
1632                             ptr->nWidth, ptr->nHeight, SRCAND );
1633             SelectObject( hMemDC, hXorBits );
1634             StretchBlt( hdc, x, y, GetSystemMetrics(SM_CXICON),
1635                             GetSystemMetrics(SM_CYICON), hMemDC, 0, 0,
1636                             ptr->nWidth, ptr->nHeight, SRCINVERT );
1637             SelectObject( hMemDC, hBitTemp );
1638         }
1639     }
1640
1641     DeleteDC( hMemDC );
1642     if (hXorBits) DeleteObject( hXorBits );
1643     if (hAndBits) DeleteObject( hAndBits );
1644     wow_handlers.release_icon_ptr( hIcon, ptr );
1645     SetTextColor( hdc, oldFg );
1646     SetBkColor( hdc, oldBg );
1647     return TRUE;
1648 }
1649
1650 /***********************************************************************
1651  *              SetCursor (USER32.@)
1652  *
1653  * Set the cursor shape.
1654  *
1655  * RETURNS
1656  *      A handle to the previous cursor shape.
1657  */
1658 HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1659 {
1660     struct user_thread_info *thread_info = get_user_thread_info();
1661     HCURSOR hOldCursor;
1662
1663     if (hCursor == thread_info->cursor) return hCursor;  /* No change */
1664     TRACE("%p\n", hCursor);
1665     hOldCursor = thread_info->cursor;
1666     thread_info->cursor = hCursor;
1667     /* Change the cursor shape only if it is visible */
1668     if (thread_info->cursor_count >= 0)
1669     {
1670         CURSORICONINFO *info = wow_handlers.get_icon_ptr( hCursor );
1671         /* release before calling driver (FIXME) */
1672         if (info) wow_handlers.release_icon_ptr( hCursor, info );
1673         USER_Driver->pSetCursor( info );
1674     }
1675     return hOldCursor;
1676 }
1677
1678 /***********************************************************************
1679  *              ShowCursor (USER32.@)
1680  */
1681 INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
1682 {
1683     struct user_thread_info *thread_info = get_user_thread_info();
1684
1685     TRACE("%d, count=%d\n", bShow, thread_info->cursor_count );
1686
1687     if (bShow)
1688     {
1689         if (++thread_info->cursor_count == 0) /* Show it */
1690         {
1691             CURSORICONINFO *info = wow_handlers.get_icon_ptr( thread_info->cursor );
1692             /* release before calling driver (FIXME) */
1693             if (info) wow_handlers.release_icon_ptr( thread_info->cursor, info );
1694             USER_Driver->pSetCursor( info );
1695         }
1696     }
1697     else
1698     {
1699         if (--thread_info->cursor_count == -1) /* Hide it */
1700             USER_Driver->pSetCursor( NULL );
1701     }
1702     return thread_info->cursor_count;
1703 }
1704
1705 /***********************************************************************
1706  *              GetCursor (USER32.@)
1707  */
1708 HCURSOR WINAPI GetCursor(void)
1709 {
1710     return get_user_thread_info()->cursor;
1711 }
1712
1713
1714 /***********************************************************************
1715  *              ClipCursor (USER32.@)
1716  */
1717 BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
1718 {
1719     RECT virt;
1720
1721     SetRect( &virt, 0, 0, GetSystemMetrics( SM_CXVIRTUALSCREEN ),
1722                           GetSystemMetrics( SM_CYVIRTUALSCREEN ) );
1723     OffsetRect( &virt, GetSystemMetrics( SM_XVIRTUALSCREEN ),
1724                        GetSystemMetrics( SM_YVIRTUALSCREEN ) );
1725
1726     TRACE( "Clipping to: %s was: %s screen: %s\n", wine_dbgstr_rect(rect),
1727            wine_dbgstr_rect(&CURSOR_ClipRect), wine_dbgstr_rect(&virt) );
1728
1729     if (!IntersectRect( &CURSOR_ClipRect, &virt, rect ))
1730         CURSOR_ClipRect = virt;
1731
1732     USER_Driver->pClipCursor( rect );
1733     return TRUE;
1734 }
1735
1736
1737 /***********************************************************************
1738  *              GetClipCursor (USER32.@)
1739  */
1740 BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
1741 {
1742     /* If this is first time - initialize the rect */
1743     if (IsRectEmpty( &CURSOR_ClipRect )) ClipCursor( NULL );
1744
1745     return CopyRect( rect, &CURSOR_ClipRect );
1746 }
1747
1748
1749 /***********************************************************************
1750  *              SetSystemCursor (USER32.@)
1751  */
1752 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
1753 {
1754     FIXME("(%p,%08x),stub!\n",  hcur, id);
1755     return TRUE;
1756 }
1757
1758
1759 /**********************************************************************
1760  *              LookupIconIdFromDirectoryEx (USER32.@)
1761  */
1762 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
1763              INT width, INT height, UINT cFlag )
1764 {
1765     CURSORICONDIR       *dir = (CURSORICONDIR*)xdir;
1766     UINT retVal = 0;
1767     if( dir && !dir->idReserved && (dir->idType & 3) )
1768     {
1769         CURSORICONDIRENTRY* entry;
1770         HDC hdc;
1771         UINT palEnts;
1772         int colors;
1773         hdc = GetDC(0);
1774         palEnts = GetSystemPaletteEntries(hdc, 0, 0, NULL);
1775         if (palEnts == 0)
1776             palEnts = 256;
1777         colors = (cFlag & LR_MONOCHROME) ? 2 : palEnts;
1778
1779         ReleaseDC(0, hdc);
1780
1781         if( bIcon )
1782             entry = CURSORICON_FindBestIconRes( dir, width, height, colors );
1783         else
1784             entry = CURSORICON_FindBestCursorRes( dir, width, height, colors );
1785
1786         if( entry ) retVal = entry->wResId;
1787     }
1788     else WARN_(cursor)("invalid resource directory\n");
1789     return retVal;
1790 }
1791
1792 /**********************************************************************
1793  *              LookupIconIdFromDirectory (USER32.@)
1794  */
1795 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
1796 {
1797     return LookupIconIdFromDirectoryEx( dir, bIcon,
1798            bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
1799            bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
1800 }
1801
1802 /***********************************************************************
1803  *              LoadCursorW (USER32.@)
1804  */
1805 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
1806 {
1807     TRACE("%p, %s\n", hInstance, debugstr_w(name));
1808
1809     return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1810                        LR_SHARED | LR_DEFAULTSIZE );
1811 }
1812
1813 /***********************************************************************
1814  *              LoadCursorA (USER32.@)
1815  */
1816 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
1817 {
1818     TRACE("%p, %s\n", hInstance, debugstr_a(name));
1819
1820     return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1821                        LR_SHARED | LR_DEFAULTSIZE );
1822 }
1823
1824 /***********************************************************************
1825  *              LoadCursorFromFileW (USER32.@)
1826  */
1827 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1828 {
1829     TRACE("%s\n", debugstr_w(name));
1830
1831     return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1832                        LR_LOADFROMFILE | LR_DEFAULTSIZE );
1833 }
1834
1835 /***********************************************************************
1836  *              LoadCursorFromFileA (USER32.@)
1837  */
1838 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1839 {
1840     TRACE("%s\n", debugstr_a(name));
1841
1842     return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1843                        LR_LOADFROMFILE | LR_DEFAULTSIZE );
1844 }
1845
1846 /***********************************************************************
1847  *              LoadIconW (USER32.@)
1848  */
1849 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
1850 {
1851     TRACE("%p, %s\n", hInstance, debugstr_w(name));
1852
1853     return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1854                        LR_SHARED | LR_DEFAULTSIZE );
1855 }
1856
1857 /***********************************************************************
1858  *              LoadIconA (USER32.@)
1859  */
1860 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
1861 {
1862     TRACE("%p, %s\n", hInstance, debugstr_a(name));
1863
1864     return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1865                        LR_SHARED | LR_DEFAULTSIZE );
1866 }
1867
1868 /**********************************************************************
1869  *              GetIconInfo (USER32.@)
1870  */
1871 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
1872 {
1873     CURSORICONINFO *ciconinfo;
1874     INT height;
1875
1876     if (!(ciconinfo = wow_handlers.get_icon_ptr( hIcon ))) return FALSE;
1877
1878     TRACE("%p => %dx%d, %d bpp\n", hIcon,
1879           ciconinfo->nWidth, ciconinfo->nHeight, ciconinfo->bBitsPerPixel);
1880
1881     if ( (ciconinfo->ptHotSpot.x == ICON_HOTSPOT) &&
1882          (ciconinfo->ptHotSpot.y == ICON_HOTSPOT) )
1883     {
1884       iconinfo->fIcon    = TRUE;
1885       iconinfo->xHotspot = ciconinfo->nWidth / 2;
1886       iconinfo->yHotspot = ciconinfo->nHeight / 2;
1887     }
1888     else
1889     {
1890       iconinfo->fIcon    = FALSE;
1891       iconinfo->xHotspot = ciconinfo->ptHotSpot.x;
1892       iconinfo->yHotspot = ciconinfo->ptHotSpot.y;
1893     }
1894
1895     height = ciconinfo->nHeight;
1896
1897     if (ciconinfo->bBitsPerPixel > 1)
1898     {
1899         iconinfo->hbmColor = CreateBitmap( ciconinfo->nWidth, ciconinfo->nHeight,
1900                                 ciconinfo->bPlanes, ciconinfo->bBitsPerPixel,
1901                                 (char *)(ciconinfo + 1)
1902                                 + ciconinfo->nHeight *
1903                                 get_bitmap_width_bytes (ciconinfo->nWidth,1) );
1904     }
1905     else
1906     {
1907         iconinfo->hbmColor = 0;
1908         height *= 2;
1909     }
1910
1911     iconinfo->hbmMask = CreateBitmap ( ciconinfo->nWidth, height,
1912                                 1, 1, ciconinfo + 1);
1913     wow_handlers.release_icon_ptr( hIcon, ciconinfo );
1914
1915     return TRUE;
1916 }
1917
1918 /**********************************************************************
1919  *              CreateIconIndirect (USER32.@)
1920  */
1921 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
1922 {
1923     DIBSECTION bmpXor;
1924     BITMAP bmpAnd;
1925     HICON hObj;
1926     int xor_objsize = 0, sizeXor = 0, sizeAnd, planes, bpp;
1927
1928     TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
1929            iconinfo->hbmColor, iconinfo->hbmMask,
1930            iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
1931
1932     if (!iconinfo->hbmMask) return 0;
1933
1934     planes = GetDeviceCaps( screen_dc, PLANES );
1935     bpp = GetDeviceCaps( screen_dc, BITSPIXEL );
1936
1937     if (iconinfo->hbmColor)
1938     {
1939         xor_objsize = GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
1940         TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
1941                bmpXor.dsBm.bmWidth, bmpXor.dsBm.bmHeight, bmpXor.dsBm.bmWidthBytes,
1942                bmpXor.dsBm.bmPlanes, bmpXor.dsBm.bmBitsPixel);
1943         /* we can use either depth 1 or screen depth for xor bitmap */
1944         if (bmpXor.dsBm.bmPlanes == 1 && bmpXor.dsBm.bmBitsPixel == 1) planes = bpp = 1;
1945         sizeXor = bmpXor.dsBm.bmHeight * planes * get_bitmap_width_bytes( bmpXor.dsBm.bmWidth, bpp );
1946     }
1947     GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
1948     TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
1949            bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
1950            bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
1951
1952     sizeAnd = bmpAnd.bmHeight * get_bitmap_width_bytes(bmpAnd.bmWidth, 1);
1953
1954     hObj = wow_handlers.alloc_icon_handle( sizeof(CURSORICONINFO) + sizeXor + sizeAnd );
1955     if (hObj)
1956     {
1957         CURSORICONINFO *info = wow_handlers.get_icon_ptr( hObj );
1958
1959         /* If we are creating an icon, the hotspot is unused */
1960         if (iconinfo->fIcon)
1961         {
1962             info->ptHotSpot.x   = ICON_HOTSPOT;
1963             info->ptHotSpot.y   = ICON_HOTSPOT;
1964         }
1965         else
1966         {
1967             info->ptHotSpot.x   = iconinfo->xHotspot;
1968             info->ptHotSpot.y   = iconinfo->yHotspot;
1969         }
1970
1971         if (iconinfo->hbmColor)
1972         {
1973             info->nWidth        = bmpXor.dsBm.bmWidth;
1974             info->nHeight       = bmpXor.dsBm.bmHeight;
1975             info->nWidthBytes   = bmpXor.dsBm.bmWidthBytes;
1976             info->bPlanes       = planes;
1977             info->bBitsPerPixel = bpp;
1978         }
1979         else
1980         {
1981             info->nWidth        = bmpAnd.bmWidth;
1982             info->nHeight       = bmpAnd.bmHeight / 2;
1983             info->nWidthBytes   = get_bitmap_width_bytes(bmpAnd.bmWidth, 1);
1984             info->bPlanes       = 1;
1985             info->bBitsPerPixel = 1;
1986         }
1987
1988         /* Transfer the bitmap bits to the CURSORICONINFO structure */
1989
1990         /* Some apps pass a color bitmap as a mask, convert it to b/w */
1991         if (bmpAnd.bmBitsPixel == 1)
1992         {
1993             GetBitmapBits( iconinfo->hbmMask, sizeAnd, info + 1 );
1994         }
1995         else
1996         {
1997             HDC hdc_mem, hdc_mem2;
1998             HBITMAP hbmp_mem_old, hbmp_mem2_old, hbmp_mono;
1999
2000             hdc_mem = CreateCompatibleDC( 0 );
2001             hdc_mem2 = CreateCompatibleDC( 0 );
2002
2003             hbmp_mono = CreateBitmap( bmpAnd.bmWidth, bmpAnd.bmHeight, 1, 1, NULL );
2004
2005             hbmp_mem_old = SelectObject( hdc_mem, iconinfo->hbmMask );
2006             hbmp_mem2_old = SelectObject( hdc_mem2, hbmp_mono );
2007
2008             BitBlt( hdc_mem2, 0, 0, bmpAnd.bmWidth, bmpAnd.bmHeight, hdc_mem, 0, 0, SRCCOPY );
2009
2010             SelectObject( hdc_mem, hbmp_mem_old );
2011             SelectObject( hdc_mem2, hbmp_mem2_old );
2012
2013             DeleteDC( hdc_mem );
2014             DeleteDC( hdc_mem2 );
2015
2016             GetBitmapBits( hbmp_mono, sizeAnd, info + 1 );
2017             DeleteObject( hbmp_mono );
2018         }
2019
2020         if (iconinfo->hbmColor)
2021         {
2022             char *dst_bits = (char*)(info + 1) + sizeAnd;
2023
2024             if (bmpXor.dsBm.bmPlanes == planes && bmpXor.dsBm.bmBitsPixel == bpp)
2025                 GetBitmapBits( iconinfo->hbmColor, sizeXor, dst_bits );
2026             else
2027             {
2028                 BITMAPINFO bminfo;
2029                 int dib_width = get_dib_width_bytes( info->nWidth, info->bBitsPerPixel );
2030                 int bitmap_width = get_bitmap_width_bytes( info->nWidth, info->bBitsPerPixel );
2031
2032                 bminfo.bmiHeader.biSize = sizeof(bminfo);
2033                 bminfo.bmiHeader.biWidth = info->nWidth;
2034                 bminfo.bmiHeader.biHeight = info->nHeight;
2035                 bminfo.bmiHeader.biPlanes = info->bPlanes;
2036                 bminfo.bmiHeader.biBitCount = info->bBitsPerPixel;
2037                 bminfo.bmiHeader.biCompression = BI_RGB;
2038                 bminfo.bmiHeader.biSizeImage = info->nHeight * dib_width;
2039                 bminfo.bmiHeader.biXPelsPerMeter = 0;
2040                 bminfo.bmiHeader.biYPelsPerMeter = 0;
2041                 bminfo.bmiHeader.biClrUsed = 0;
2042                 bminfo.bmiHeader.biClrImportant = 0;
2043
2044                 /* swap lines for dib sections */
2045                 if (xor_objsize == sizeof(DIBSECTION))
2046                     bminfo.bmiHeader.biHeight = -bminfo.bmiHeader.biHeight;
2047
2048                 if (dib_width != bitmap_width)  /* need to fixup alignment */
2049                 {
2050                     char *src_bits = HeapAlloc( GetProcessHeap(), 0, bminfo.bmiHeader.biSizeImage );
2051
2052                     if (src_bits && GetDIBits( screen_dc, iconinfo->hbmColor, 0, info->nHeight,
2053                                                src_bits, &bminfo, DIB_RGB_COLORS ))
2054                     {
2055                         int y;
2056                         for (y = 0; y < info->nHeight; y++)
2057                             memcpy( dst_bits + y * bitmap_width, src_bits + y * dib_width, bitmap_width );
2058                     }
2059                     HeapFree( GetProcessHeap(), 0, src_bits );
2060                 }
2061                 else
2062                     GetDIBits( screen_dc, iconinfo->hbmColor, 0, info->nHeight,
2063                                dst_bits, &bminfo, DIB_RGB_COLORS );
2064             }
2065         }
2066         wow_handlers.release_icon_ptr( hObj, info );
2067     }
2068     return hObj;
2069 }
2070
2071 /******************************************************************************
2072  *              DrawIconEx (USER32.@) Draws an icon or cursor on device context
2073  *
2074  * NOTES
2075  *    Why is this using SM_CXICON instead of SM_CXCURSOR?
2076  *
2077  * PARAMS
2078  *    hdc     [I] Handle to device context
2079  *    x0      [I] X coordinate of upper left corner
2080  *    y0      [I] Y coordinate of upper left corner
2081  *    hIcon   [I] Handle to icon to draw
2082  *    cxWidth [I] Width of icon
2083  *    cyWidth [I] Height of icon
2084  *    istep   [I] Index of frame in animated cursor
2085  *    hbr     [I] Handle to background brush
2086  *    flags   [I] Icon-drawing flags
2087  *
2088  * RETURNS
2089  *    Success: TRUE
2090  *    Failure: FALSE
2091  */
2092 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2093                             INT cxWidth, INT cyWidth, UINT istep,
2094                             HBRUSH hbr, UINT flags )
2095 {
2096     CURSORICONINFO *ptr;
2097     HDC hDC_off = 0, hMemDC;
2098     BOOL result = FALSE, DoOffscreen;
2099     HBITMAP hB_off = 0, hOld = 0;
2100     unsigned char *xorBitmapBits;
2101     unsigned int xorLength;
2102     BOOL has_alpha = FALSE;
2103
2104     TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2105                  hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2106
2107     if (!(ptr = wow_handlers.get_icon_ptr( hIcon ))) return FALSE;
2108     if (!(hMemDC = CreateCompatibleDC( hdc )))
2109     {
2110         wow_handlers.release_icon_ptr( hIcon, ptr );
2111         return FALSE;
2112     }
2113
2114     if (istep)
2115         FIXME_(icon)("Ignoring istep=%d\n", istep);
2116     if (flags & DI_NOMIRROR)
2117         FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
2118
2119     xorLength = ptr->nHeight * get_bitmap_width_bytes(
2120         ptr->nWidth, ptr->bBitsPerPixel);
2121     xorBitmapBits = (unsigned char *)(ptr + 1) + ptr->nHeight *
2122                     get_bitmap_width_bytes(ptr->nWidth, 1);
2123
2124     if (flags & DI_IMAGE)
2125         has_alpha = bitmap_has_alpha_channel(
2126             ptr->bBitsPerPixel, xorBitmapBits, xorLength);
2127
2128     /* Calculate the size of the destination image.  */
2129     if (cxWidth == 0)
2130     {
2131         if (flags & DI_DEFAULTSIZE)
2132             cxWidth = GetSystemMetrics (SM_CXICON);
2133         else
2134             cxWidth = ptr->nWidth;
2135     }
2136     if (cyWidth == 0)
2137     {
2138         if (flags & DI_DEFAULTSIZE)
2139             cyWidth = GetSystemMetrics (SM_CYICON);
2140         else
2141             cyWidth = ptr->nHeight;
2142     }
2143
2144     DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2145
2146     if (DoOffscreen) {
2147         RECT r;
2148
2149         r.left = 0;
2150         r.top = 0;
2151         r.right = cxWidth;
2152         r.bottom = cxWidth;
2153
2154         hDC_off = CreateCompatibleDC(hdc);
2155         hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth);
2156         if (hDC_off && hB_off) {
2157             hOld = SelectObject(hDC_off, hB_off);
2158             FillRect(hDC_off, &r, hbr);
2159         }
2160     }
2161
2162     if (hMemDC && (!DoOffscreen || (hDC_off && hB_off)))
2163     {
2164         HBITMAP hBitTemp;
2165         HBITMAP hXorBits = NULL, hAndBits = NULL;
2166         COLORREF  oldFg, oldBg;
2167         INT     nStretchMode;
2168
2169         nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2170
2171         oldFg = SetTextColor( hdc, RGB(0,0,0) );
2172         oldBg = SetBkColor( hdc, RGB(255,255,255) );
2173
2174         if (((flags & DI_MASK) && !(flags & DI_IMAGE)) ||
2175             ((flags & DI_MASK) && !has_alpha))
2176         {
2177             hAndBits = CreateBitmap ( ptr->nWidth, ptr->nHeight, 1, 1, ptr + 1 );
2178             if (hAndBits)
2179             {
2180                 hBitTemp = SelectObject( hMemDC, hAndBits );
2181                 if (DoOffscreen)
2182                     StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
2183                                 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
2184                 else
2185                     StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
2186                                 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
2187                 SelectObject( hMemDC, hBitTemp );
2188             }
2189         }
2190
2191         if (flags & DI_IMAGE)
2192         {
2193             BITMAPINFOHEADER bmih;
2194             unsigned char *dibBits;
2195
2196             memset(&bmih, 0, sizeof(BITMAPINFOHEADER));
2197             bmih.biSize = sizeof(BITMAPINFOHEADER);
2198             bmih.biWidth = ptr->nWidth;
2199             bmih.biHeight = -ptr->nHeight;
2200             bmih.biPlanes = ptr->bPlanes;
2201             bmih.biBitCount = ptr->bBitsPerPixel;
2202             bmih.biCompression = BI_RGB;
2203
2204             hXorBits = CreateDIBSection(hdc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS,
2205                                         (void*)&dibBits, NULL, 0);
2206
2207             if (hXorBits && dibBits)
2208             {
2209                 if(has_alpha)
2210                 {
2211                     BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2212
2213                     /* Do the alpha blending render */
2214                     premultiply_alpha_channel(dibBits, xorBitmapBits, xorLength);
2215                     hBitTemp = SelectObject( hMemDC, hXorBits );
2216
2217                     if (DoOffscreen)
2218                         GdiAlphaBlend(hDC_off, 0, 0, cxWidth, cyWidth, hMemDC,
2219                                         0, 0, ptr->nWidth, ptr->nHeight, pixelblend);
2220                     else
2221                         GdiAlphaBlend(hdc, x0, y0, cxWidth, cyWidth, hMemDC,
2222                                         0, 0, ptr->nWidth, ptr->nHeight, pixelblend);
2223
2224                     SelectObject( hMemDC, hBitTemp );
2225                 }
2226                 else
2227                 {
2228                     memcpy(dibBits, xorBitmapBits, xorLength);
2229                     hBitTemp = SelectObject( hMemDC, hXorBits );
2230                     if (DoOffscreen)
2231                         StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
2232                                     hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
2233                     else
2234                         StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
2235                                     hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
2236                     SelectObject( hMemDC, hBitTemp );
2237                 }
2238
2239                 DeleteObject( hXorBits );
2240             }
2241         }
2242
2243         result = TRUE;
2244
2245         SetTextColor( hdc, oldFg );
2246         SetBkColor( hdc, oldBg );
2247
2248         if (hAndBits) DeleteObject( hAndBits );
2249         SetStretchBltMode (hdc, nStretchMode);
2250         if (DoOffscreen) {
2251             BitBlt(hdc, x0, y0, cxWidth, cyWidth, hDC_off, 0, 0, SRCCOPY);
2252             SelectObject(hDC_off, hOld);
2253         }
2254     }
2255     if (hMemDC) DeleteDC( hMemDC );
2256     if (hDC_off) DeleteDC(hDC_off);
2257     if (hB_off) DeleteObject(hB_off);
2258     wow_handlers.release_icon_ptr( hIcon, ptr );
2259     return result;
2260 }
2261
2262 /***********************************************************************
2263  *           DIB_FixColorsToLoadflags
2264  *
2265  * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2266  * are in loadflags
2267  */
2268 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2269 {
2270     int colors;
2271     COLORREF c_W, c_S, c_F, c_L, c_C;
2272     int incr,i;
2273     RGBQUAD *ptr;
2274     int bitmap_type;
2275     LONG width;
2276     LONG height;
2277     WORD bpp;
2278     DWORD compr;
2279
2280     if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2281     {
2282         WARN_(resource)("Invalid bitmap\n");
2283         return;
2284     }
2285
2286     if (bpp > 8) return;
2287
2288     if (bitmap_type == 0) /* BITMAPCOREHEADER */
2289     {
2290         incr = 3;
2291         colors = 1 << bpp;
2292     }
2293     else
2294     {
2295         incr = 4;
2296         colors = bmi->bmiHeader.biClrUsed;
2297         if (colors > 256) colors = 256;
2298         if (!colors && (bpp <= 8)) colors = 1 << bpp;
2299     }
2300
2301     c_W = GetSysColor(COLOR_WINDOW);
2302     c_S = GetSysColor(COLOR_3DSHADOW);
2303     c_F = GetSysColor(COLOR_3DFACE);
2304     c_L = GetSysColor(COLOR_3DLIGHT);
2305
2306     if (loadflags & LR_LOADTRANSPARENT) {
2307         switch (bpp) {
2308         case 1: pix = pix >> 7; break;
2309         case 4: pix = pix >> 4; break;
2310         case 8: break;
2311         default:
2312             WARN_(resource)("(%d): Unsupported depth\n", bpp);
2313             return;
2314         }
2315         if (pix >= colors) {
2316             WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2317             return;
2318         }
2319         if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2320         ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2321         ptr->rgbBlue = GetBValue(c_W);
2322         ptr->rgbGreen = GetGValue(c_W);
2323         ptr->rgbRed = GetRValue(c_W);
2324     }
2325     if (loadflags & LR_LOADMAP3DCOLORS)
2326         for (i=0; i<colors; i++) {
2327             ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2328             c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2329             if (c_C == RGB(128, 128, 128)) {
2330                 ptr->rgbRed = GetRValue(c_S);
2331                 ptr->rgbGreen = GetGValue(c_S);
2332                 ptr->rgbBlue = GetBValue(c_S);
2333             } else if (c_C == RGB(192, 192, 192)) {
2334                 ptr->rgbRed = GetRValue(c_F);
2335                 ptr->rgbGreen = GetGValue(c_F);
2336                 ptr->rgbBlue = GetBValue(c_F);
2337             } else if (c_C == RGB(223, 223, 223)) {
2338                 ptr->rgbRed = GetRValue(c_L);
2339                 ptr->rgbGreen = GetGValue(c_L);
2340                 ptr->rgbBlue = GetBValue(c_L);
2341             }
2342         }
2343 }
2344
2345
2346 /**********************************************************************
2347  *       BITMAP_Load
2348  */
2349 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2350                             INT desiredx, INT desiredy, UINT loadflags )
2351 {
2352     HBITMAP hbitmap = 0, orig_bm;
2353     HRSRC hRsrc;
2354     HGLOBAL handle;
2355     char *ptr = NULL;
2356     BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2357     int size;
2358     BYTE pix;
2359     char *bits;
2360     LONG width, height, new_width, new_height;
2361     WORD bpp_dummy;
2362     DWORD compr_dummy;
2363     INT bm_type;
2364     HDC screen_mem_dc = NULL;
2365
2366     if (!(loadflags & LR_LOADFROMFILE))
2367     {
2368         if (!instance)
2369         {
2370             /* OEM bitmap: try to load the resource from user32.dll */
2371             instance = user32_module;
2372         }
2373
2374         if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2375         if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2376
2377         if ((info = LockResource( handle )) == NULL) return 0;
2378     }
2379     else
2380     {
2381         BITMAPFILEHEADER * bmfh;
2382
2383         if (!(ptr = map_fileW( name, NULL ))) return 0;
2384         info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2385         bmfh = (BITMAPFILEHEADER *)ptr;
2386         if (!(  bmfh->bfType == 0x4d42 /* 'BM' */ &&
2387                 bmfh->bfReserved1 == 0 &&
2388                 bmfh->bfReserved2 == 0))
2389         {
2390             WARN("Invalid/unsupported bitmap format!\n");
2391             UnmapViewOfFile( ptr );
2392             return 0;
2393         }
2394     }
2395
2396     size = bitmap_info_size(info, DIB_RGB_COLORS);
2397     fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2398     scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2399
2400     if (!fix_info || !scaled_info) goto end;
2401     memcpy(fix_info, info, size);
2402
2403     pix = *((LPBYTE)info + size);
2404     DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2405
2406     memcpy(scaled_info, fix_info, size);
2407     bm_type = DIB_GetBitmapInfo( &fix_info->bmiHeader, &width, &height,
2408                                  &bpp_dummy, &compr_dummy);
2409     if(desiredx != 0)
2410         new_width = desiredx;
2411     else
2412         new_width = width;
2413
2414     if(desiredy != 0)
2415         new_height = height > 0 ? desiredy : -desiredy;
2416     else
2417         new_height = height;
2418
2419     if(bm_type == 0)
2420     {
2421         BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2422         core->bcWidth = new_width;
2423         core->bcHeight = new_height;
2424     }
2425     else
2426     {
2427         scaled_info->bmiHeader.biWidth = new_width;
2428         scaled_info->bmiHeader.biHeight = new_height;
2429     }
2430
2431     if (new_height < 0) new_height = -new_height;
2432
2433     if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2434     if (!(screen_mem_dc = CreateCompatibleDC( screen_dc ))) goto end;
2435
2436     bits = (char *)info + size;
2437
2438     if (loadflags & LR_CREATEDIBSECTION)
2439     {
2440         scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2441         hbitmap = CreateDIBSection(screen_dc, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2442     }
2443     else
2444     {
2445         if (is_dib_monochrome(fix_info))
2446             hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2447         else
2448             hbitmap = CreateCompatibleBitmap(screen_dc, new_width, new_height);        
2449     }
2450
2451     orig_bm = SelectObject(screen_mem_dc, hbitmap);
2452     StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2453     SelectObject(screen_mem_dc, orig_bm);
2454
2455 end:
2456     if (screen_mem_dc) DeleteDC(screen_mem_dc);
2457     HeapFree(GetProcessHeap(), 0, scaled_info);
2458     HeapFree(GetProcessHeap(), 0, fix_info);
2459     if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2460
2461     return hbitmap;
2462 }
2463
2464 /**********************************************************************
2465  *              LoadImageA (USER32.@)
2466  *
2467  * See LoadImageW.
2468  */
2469 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2470                               INT desiredx, INT desiredy, UINT loadflags)
2471 {
2472     HANDLE res;
2473     LPWSTR u_name;
2474
2475     if (!HIWORD(name))
2476         return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2477
2478     __TRY {
2479         DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2480         u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2481         MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2482     }
2483     __EXCEPT_PAGE_FAULT {
2484         SetLastError( ERROR_INVALID_PARAMETER );
2485         return 0;
2486     }
2487     __ENDTRY
2488     res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2489     HeapFree(GetProcessHeap(), 0, u_name);
2490     return res;
2491 }
2492
2493
2494 /******************************************************************************
2495  *              LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2496  *
2497  * PARAMS
2498  *    hinst     [I] Handle of instance that contains image
2499  *    name      [I] Name of image
2500  *    type      [I] Type of image
2501  *    desiredx  [I] Desired width
2502  *    desiredy  [I] Desired height
2503  *    loadflags [I] Load flags
2504  *
2505  * RETURNS
2506  *    Success: Handle to newly loaded image
2507  *    Failure: NULL
2508  *
2509  * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2510  */
2511 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2512                 INT desiredx, INT desiredy, UINT loadflags )
2513 {
2514     TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
2515                      hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
2516
2517     if (loadflags & LR_DEFAULTSIZE) {
2518         if (type == IMAGE_ICON) {
2519             if (!desiredx) desiredx = GetSystemMetrics(SM_CXICON);
2520             if (!desiredy) desiredy = GetSystemMetrics(SM_CYICON);
2521         } else if (type == IMAGE_CURSOR) {
2522             if (!desiredx) desiredx = GetSystemMetrics(SM_CXCURSOR);
2523             if (!desiredy) desiredy = GetSystemMetrics(SM_CYCURSOR);
2524         }
2525     }
2526     if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
2527     switch (type) {
2528     case IMAGE_BITMAP:
2529         return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2530
2531     case IMAGE_ICON:
2532         if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2533         if (screen_dc)
2534         {
2535             UINT palEnts = GetSystemPaletteEntries(screen_dc, 0, 0, NULL);
2536             if (palEnts == 0) palEnts = 256;
2537             return CURSORICON_Load(hinst, name, desiredx, desiredy,
2538                                    palEnts, FALSE, loadflags);
2539         }
2540         break;
2541
2542     case IMAGE_CURSOR:
2543         return CURSORICON_Load(hinst, name, desiredx, desiredy,
2544                                1, TRUE, loadflags);
2545     }
2546     return 0;
2547 }
2548
2549 /******************************************************************************
2550  *              CopyImage (USER32.@) Creates new image and copies attributes to it
2551  *
2552  * PARAMS
2553  *    hnd      [I] Handle to image to copy
2554  *    type     [I] Type of image to copy
2555  *    desiredx [I] Desired width of new image
2556  *    desiredy [I] Desired height of new image
2557  *    flags    [I] Copy flags
2558  *
2559  * RETURNS
2560  *    Success: Handle to newly created image
2561  *    Failure: NULL
2562  *
2563  * BUGS
2564  *    Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
2565  *    all other versions (95/2000/XP have been tested) ignore it.
2566  *
2567  * NOTES
2568  *    If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
2569  *    a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
2570  *    the copy will have the same depth as the screen.
2571  *    The content of the image will only be copied if the bit depth of the
2572  *    original image is compatible with the bit depth of the screen, or
2573  *    if the source is a DIB section.
2574  *    The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
2575  */
2576 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2577                              INT desiredy, UINT flags )
2578 {
2579     TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
2580           hnd, type, desiredx, desiredy, flags);
2581
2582     switch (type)
2583     {
2584         case IMAGE_BITMAP:
2585         {
2586             HBITMAP res = NULL;
2587             DIBSECTION ds;
2588             int objSize;
2589             BITMAPINFO * bi;
2590
2591             objSize = GetObjectW( hnd, sizeof(ds), &ds );
2592             if (!objSize) return 0;
2593             if ((desiredx < 0) || (desiredy < 0)) return 0;
2594
2595             if (flags & LR_COPYFROMRESOURCE)
2596             {
2597                 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
2598             }
2599
2600             if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
2601             if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
2602
2603             /* Allocate memory for a BITMAPINFOHEADER structure and a
2604                color table. The maximum number of colors in a color table
2605                is 256 which corresponds to a bitmap with depth 8.
2606                Bitmaps with higher depths don't have color tables. */
2607             bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
2608             if (!bi) return 0;
2609
2610             bi->bmiHeader.biSize        = sizeof(bi->bmiHeader);
2611             bi->bmiHeader.biPlanes      = ds.dsBm.bmPlanes;
2612             bi->bmiHeader.biBitCount    = ds.dsBm.bmBitsPixel;
2613             bi->bmiHeader.biCompression = BI_RGB;
2614
2615             if (flags & LR_CREATEDIBSECTION)
2616             {
2617                 /* Create a DIB section. LR_MONOCHROME is ignored */
2618                 void * bits;
2619                 HDC dc = CreateCompatibleDC(NULL);
2620
2621                 if (objSize == sizeof(DIBSECTION))
2622                 {
2623                     /* The source bitmap is a DIB.
2624                        Get its attributes to create an exact copy */
2625                     memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
2626                 }
2627
2628                 /* Get the color table or the color masks */
2629                 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2630
2631                 bi->bmiHeader.biWidth  = desiredx;
2632                 bi->bmiHeader.biHeight = desiredy;
2633                 bi->bmiHeader.biSizeImage = 0;
2634
2635                 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
2636                 DeleteDC(dc);
2637             }
2638             else
2639             {
2640                 /* Create a device-dependent bitmap */
2641
2642                 BOOL monochrome = (flags & LR_MONOCHROME);
2643
2644                 if (objSize == sizeof(DIBSECTION))
2645                 {
2646                     /* The source bitmap is a DIB section.
2647                        Get its attributes */
2648                     HDC dc = CreateCompatibleDC(NULL);
2649                     bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
2650                     bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
2651                     GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2652                     DeleteDC(dc);
2653
2654                     if (!monochrome && ds.dsBm.bmBitsPixel == 1)
2655                     {
2656                         /* Look if the colors of the DIB are black and white */
2657
2658                         monochrome = 
2659                               (bi->bmiColors[0].rgbRed == 0xff
2660                             && bi->bmiColors[0].rgbGreen == 0xff
2661                             && bi->bmiColors[0].rgbBlue == 0xff
2662                             && bi->bmiColors[0].rgbReserved == 0
2663                             && bi->bmiColors[1].rgbRed == 0
2664                             && bi->bmiColors[1].rgbGreen == 0
2665                             && bi->bmiColors[1].rgbBlue == 0
2666                             && bi->bmiColors[1].rgbReserved == 0)
2667                             ||
2668                               (bi->bmiColors[0].rgbRed == 0
2669                             && bi->bmiColors[0].rgbGreen == 0
2670                             && bi->bmiColors[0].rgbBlue == 0
2671                             && bi->bmiColors[0].rgbReserved == 0
2672                             && bi->bmiColors[1].rgbRed == 0xff
2673                             && bi->bmiColors[1].rgbGreen == 0xff
2674                             && bi->bmiColors[1].rgbBlue == 0xff
2675                             && bi->bmiColors[1].rgbReserved == 0);
2676                     }
2677                 }
2678                 else if (!monochrome)
2679                 {
2680                     monochrome = ds.dsBm.bmBitsPixel == 1;
2681                 }
2682
2683                 if (monochrome)
2684                 {
2685                     res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
2686                 }
2687                 else
2688                 {
2689                     HDC screenDC = GetDC(NULL);
2690                     res = CreateCompatibleBitmap(screenDC, desiredx, desiredy);
2691                     ReleaseDC(NULL, screenDC);
2692                 }
2693             }
2694
2695             if (res)
2696             {
2697                 /* Only copy the bitmap if it's a DIB section or if it's
2698                    compatible to the screen */
2699                 BOOL copyContents;
2700
2701                 if (objSize == sizeof(DIBSECTION))
2702                 {
2703                     copyContents = TRUE;
2704                 }
2705                 else
2706                 {
2707                     HDC screenDC = GetDC(NULL);
2708                     int screen_depth = GetDeviceCaps(screenDC, BITSPIXEL);
2709                     ReleaseDC(NULL, screenDC);
2710
2711                     copyContents = (ds.dsBm.bmBitsPixel == 1 || ds.dsBm.bmBitsPixel == screen_depth);
2712                 }
2713
2714                 if (copyContents)
2715                 {
2716                     /* The source bitmap may already be selected in a device context,
2717                        use GetDIBits/StretchDIBits and not StretchBlt  */
2718
2719                     HDC dc;
2720                     void * bits;
2721
2722                     dc = CreateCompatibleDC(NULL);
2723
2724                     bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
2725                     bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
2726                     bi->bmiHeader.biSizeImage = 0;
2727                     bi->bmiHeader.biClrUsed = 0;
2728                     bi->bmiHeader.biClrImportant = 0;
2729
2730                     /* Fill in biSizeImage */
2731                     GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2732                     bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
2733
2734                     if (bits)
2735                     {
2736                         HBITMAP oldBmp;
2737
2738                         /* Get the image bits of the source bitmap */
2739                         GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
2740
2741                         /* Copy it to the destination bitmap */
2742                         oldBmp = SelectObject(dc, res);
2743                         StretchDIBits(dc, 0, 0, desiredx, desiredy,
2744                                       0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
2745                                       bits, bi, DIB_RGB_COLORS, SRCCOPY);
2746                         SelectObject(dc, oldBmp);
2747
2748                         HeapFree(GetProcessHeap(), 0, bits);
2749                     }
2750
2751                     DeleteDC(dc);
2752                 }
2753
2754                 if (flags & LR_COPYDELETEORG)
2755                 {
2756                     DeleteObject(hnd);
2757                 }
2758             }
2759             HeapFree(GetProcessHeap(), 0, bi);
2760             return res;
2761         }
2762         case IMAGE_ICON:
2763                 return CURSORICON_ExtCopy(hnd,type, desiredx, desiredy, flags);
2764         case IMAGE_CURSOR:
2765                 /* Should call CURSORICON_ExtCopy but more testing
2766                  * needs to be done before we change this
2767                  */
2768                 if (flags) FIXME("Flags are ignored\n");
2769                 return CopyCursor(hnd);
2770     }
2771     return 0;
2772 }
2773
2774
2775 /******************************************************************************
2776  *              LoadBitmapW (USER32.@) Loads bitmap from the executable file
2777  *
2778  * RETURNS
2779  *    Success: Handle to specified bitmap
2780  *    Failure: NULL
2781  */
2782 HBITMAP WINAPI LoadBitmapW(
2783     HINSTANCE instance, /* [in] Handle to application instance */
2784     LPCWSTR name)         /* [in] Address of bitmap resource name */
2785 {
2786     return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2787 }
2788
2789 /**********************************************************************
2790  *              LoadBitmapA (USER32.@)
2791  *
2792  * See LoadBitmapW.
2793  */
2794 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
2795 {
2796     return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2797 }