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