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