kernelbase/tests: Fix the Sleep() test for non-default timer resolutions.
[wine.git] / dlls / user32 / cursoricon.c
blob7ad0a04a551bfe3dc8f1582b530cf3edc9a2344f
1 /*
2 * Cursor and icon support
4 * Copyright 1995 Alexandre Julliard
5 * Copyright 1996 Martin Von Loewis
6 * Copyright 1997 Alex Korobka
7 * Copyright 1998 Turchanov Sergey
8 * Copyright 2007 Henri Verbeet
9 * Copyright 2009 Vincent Povirk for CodeWeavers
10 * Copyright 2016 Dmitry Timoshkov
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #include <assert.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <stdlib.h>
32 #include "windef.h"
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "winerror.h"
36 #include "winnls.h"
37 #include "wine/exception.h"
38 #include "wine/server.h"
39 #include "controls.h"
40 #include "win.h"
41 #include "user_private.h"
42 #include "wine/list.h"
43 #include "wine/debug.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
46 WINE_DECLARE_DEBUG_CHANNEL(icon);
47 WINE_DECLARE_DEBUG_CHANNEL(resource);
49 #define RIFF_FOURCC( c0, c1, c2, c3 ) \
50 ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
51 ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
52 #define PNG_SIGN RIFF_FOURCC(0x89,'P','N','G')
54 static struct list icon_cache = LIST_INIT( icon_cache );
56 /**********************************************************************
57 * User objects management
60 struct cursoricon_frame
62 UINT width; /* frame-specific width */
63 UINT height; /* frame-specific height */
64 UINT delay; /* frame-specific delay between this frame and the next (in jiffies) */
65 HBITMAP color; /* color bitmap */
66 HBITMAP alpha; /* pre-multiplied alpha bitmap for 32-bpp icons */
67 HBITMAP mask; /* mask bitmap (followed by color for 1-bpp icons) */
70 struct cursoricon_object
72 struct user_object obj; /* object header */
73 struct list entry; /* entry in shared icons list */
74 ULONG_PTR param; /* opaque param used by 16-bit code */
75 HMODULE module; /* module for icons loaded from resources */
76 LPWSTR resname; /* resource name for icons loaded from resources */
77 HRSRC rsrc; /* resource for shared icons */
78 BOOL is_icon; /* whether icon or cursor */
79 BOOL is_ani; /* whether this object is a static cursor or an animated cursor */
80 UINT delay; /* delay between this frame and the next (in jiffies) */
81 POINT hotspot;
84 struct static_cursoricon_object
86 struct cursoricon_object shared;
87 struct cursoricon_frame frame; /* frame-specific icon data */
90 struct animated_cursoricon_object
92 struct cursoricon_object shared;
93 UINT num_frames; /* number of frames in the icon/cursor */
94 UINT num_steps; /* number of sequence steps in the icon/cursor */
95 HICON frames[1]; /* list of animated cursor frames */
98 static HBITMAP create_color_bitmap( int width, int height )
100 HDC hdc = get_display_dc();
101 HBITMAP ret = CreateCompatibleBitmap( hdc, width, height );
102 release_display_dc( hdc );
103 return ret;
106 static int get_display_bpp(void)
108 HDC hdc = get_display_dc();
109 int ret = GetDeviceCaps( hdc, BITSPIXEL );
110 release_display_dc( hdc );
111 return ret;
114 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
116 static const struct png_funcs *png_funcs;
118 static BOOL WINAPI load_libpng( INIT_ONCE *once, void *param, void **context )
120 __wine_init_unix_lib( user32_module, DLL_PROCESS_ATTACH, NULL, &png_funcs );
121 return TRUE;
124 static BOOL have_libpng(void)
126 return InitOnceExecuteOnce( &init_once, load_libpng, NULL, NULL ) && png_funcs;
129 static HICON alloc_icon_handle( BOOL is_ani, UINT num_steps )
131 struct cursoricon_object *obj;
132 int icon_size;
133 HICON handle;
135 if (is_ani)
136 icon_size = FIELD_OFFSET( struct animated_cursoricon_object, frames[num_steps] );
137 else
138 icon_size = sizeof( struct static_cursoricon_object );
139 obj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, icon_size );
140 if (!obj) return NULL;
142 obj->delay = 0;
143 obj->is_ani = is_ani;
144 if (is_ani)
146 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;
148 ani_icon_data->num_steps = num_steps;
149 ani_icon_data->num_frames = num_steps; /* changed later for some animated cursors */
152 if (!(handle = alloc_user_handle( &obj->obj, USER_ICON )))
153 HeapFree( GetProcessHeap(), 0, obj );
154 return handle;
157 static struct cursoricon_object *get_icon_ptr( HICON handle )
159 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
160 if (obj == OBJ_OTHER_PROCESS)
162 WARN( "icon handle %p from other process\n", handle );
163 obj = NULL;
165 return obj;
168 static struct cursoricon_frame *get_icon_frame( struct cursoricon_object *obj, int istep )
170 struct static_cursoricon_object *req_frame;
172 if (obj->is_ani)
174 struct animated_cursoricon_object *ani_icon_data;
175 struct cursoricon_object *frameobj;
177 ani_icon_data = (struct animated_cursoricon_object *) obj;
178 if (!(frameobj = get_icon_ptr( ani_icon_data->frames[istep] )))
179 return 0;
180 req_frame = (struct static_cursoricon_object *) frameobj;
182 else
183 req_frame = (struct static_cursoricon_object *) obj;
185 return &req_frame->frame;
188 static void release_icon_frame( struct cursoricon_object *obj, struct cursoricon_frame *frame )
190 if (obj->is_ani)
192 struct cursoricon_object *frameobj;
194 frameobj = (struct cursoricon_object *) (((char *)frame) - FIELD_OFFSET(struct static_cursoricon_object, frame));
195 release_user_handle_ptr( frameobj );
199 static UINT get_icon_steps( struct cursoricon_object *obj )
201 if (obj->is_ani)
203 struct animated_cursoricon_object *ani_icon_data;
205 ani_icon_data = (struct animated_cursoricon_object *) obj;
206 return ani_icon_data->num_steps;
208 return 1;
211 static BOOL free_icon_handle( HICON handle )
213 struct cursoricon_object *obj = free_user_handle( handle, USER_ICON );
215 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
216 else if (obj)
218 ULONG_PTR param = obj->param;
219 UINT i;
221 assert( !obj->rsrc ); /* shared icons can't be freed */
223 if (!obj->is_ani)
225 struct cursoricon_frame *frame = get_icon_frame( obj, 0 );
227 if (frame->alpha) DeleteObject( frame->alpha );
228 if (frame->color) DeleteObject( frame->color );
229 DeleteObject( frame->mask );
230 release_icon_frame( obj, frame );
232 else
234 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;
236 for (i=0; i<ani_icon_data->num_steps; i++)
238 HICON hFrame = ani_icon_data->frames[i];
240 if (hFrame)
242 UINT j;
244 free_icon_handle( ani_icon_data->frames[i] );
245 for (j=0; j<ani_icon_data->num_steps; j++)
247 if (ani_icon_data->frames[j] == hFrame)
248 ani_icon_data->frames[j] = 0;
253 if (!IS_INTRESOURCE( obj->resname )) HeapFree( GetProcessHeap(), 0, obj->resname );
254 HeapFree( GetProcessHeap(), 0, obj );
255 if (wow_handlers.free_icon_param && param) wow_handlers.free_icon_param( param );
256 USER_Driver->pDestroyCursorIcon( handle );
257 return TRUE;
259 return FALSE;
262 ULONG_PTR get_icon_param( HICON handle )
264 ULONG_PTR ret = 0;
265 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
267 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
268 else if (obj)
270 ret = obj->param;
271 release_user_handle_ptr( obj );
273 return ret;
276 ULONG_PTR set_icon_param( HICON handle, ULONG_PTR param )
278 ULONG_PTR ret = 0;
279 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
281 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
282 else if (obj)
284 ret = obj->param;
285 obj->param = param;
286 release_user_handle_ptr( obj );
288 return ret;
292 /***********************************************************************
293 * map_fileW
295 * Helper function to map a file to memory:
296 * name - file name
297 * [RETURN] ptr - pointer to mapped file
298 * [RETURN] filesize - pointer size of file to be stored if not NULL
300 static const void *map_fileW( LPCWSTR name, LPDWORD filesize )
302 HANDLE hFile, hMapping;
303 LPVOID ptr = NULL;
305 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
306 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
307 if (hFile != INVALID_HANDLE_VALUE)
309 hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
310 if (hMapping)
312 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
313 CloseHandle( hMapping );
314 if (filesize)
315 *filesize = GetFileSize( hFile, NULL );
317 CloseHandle( hFile );
319 return ptr;
323 /***********************************************************************
324 * get_dib_image_size
326 * Return the size of a DIB bitmap in bytes.
328 static int get_dib_image_size( int width, int height, int depth )
330 return (((width * depth + 31) / 8) & ~3) * abs( height );
334 /***********************************************************************
335 * bitmap_info_size
337 * Return the size of the bitmap info structure including color table.
339 int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
341 unsigned int colors, size, masks = 0;
343 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
345 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
346 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
347 return sizeof(BITMAPCOREHEADER) + colors *
348 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
350 else /* assume BITMAPINFOHEADER */
352 colors = info->bmiHeader.biClrUsed;
353 if (colors > 256) /* buffer overflow otherwise */
354 colors = 256;
355 if (!colors && (info->bmiHeader.biBitCount <= 8))
356 colors = 1 << info->bmiHeader.biBitCount;
357 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
358 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
359 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
364 /***********************************************************************
365 * copy_bitmap
367 * Helper function to duplicate a bitmap.
369 static HBITMAP copy_bitmap( HBITMAP bitmap )
371 HDC src, dst = 0;
372 HBITMAP new_bitmap = 0;
373 BITMAP bmp;
375 if (!bitmap) return 0;
376 if (!GetObjectW( bitmap, sizeof(bmp), &bmp )) return 0;
378 if ((src = CreateCompatibleDC( 0 )) && (dst = CreateCompatibleDC( 0 )))
380 SelectObject( src, bitmap );
381 if ((new_bitmap = CreateCompatibleBitmap( src, bmp.bmWidth, bmp.bmHeight )))
383 SelectObject( dst, new_bitmap );
384 BitBlt( dst, 0, 0, bmp.bmWidth, bmp.bmHeight, src, 0, 0, SRCCOPY );
387 DeleteDC( dst );
388 DeleteDC( src );
389 return new_bitmap;
393 /***********************************************************************
394 * is_dib_monochrome
396 * Returns whether a DIB can be converted to a monochrome DDB.
398 * A DIB can be converted if its color table contains only black and
399 * white. Black must be the first color in the color table.
401 * Note : If the first color in the color table is white followed by
402 * black, we can't convert it to a monochrome DDB with
403 * SetDIBits, because black and white would be inverted.
405 static BOOL is_dib_monochrome( const BITMAPINFO* info )
407 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
409 const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
411 if (((const BITMAPCOREINFO*)info)->bmciHeader.bcBitCount != 1) return FALSE;
413 /* Check if the first color is black */
414 if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
416 rgb++;
418 /* Check if the second color is white */
419 return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
420 && (rgb->rgbtBlue == 0xff));
422 else return FALSE;
424 else /* assume BITMAPINFOHEADER */
426 const RGBQUAD *rgb = info->bmiColors;
428 if (info->bmiHeader.biBitCount != 1) return FALSE;
430 /* Check if the first color is black */
431 if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
432 (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
434 rgb++;
436 /* Check if the second color is white */
437 return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
438 && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
440 else return FALSE;
444 /***********************************************************************
445 * DIB_GetBitmapInfo
447 * Get the info from a bitmap header.
448 * Return 1 for INFOHEADER, 0 for COREHEADER, -1 in case of failure.
450 static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
451 LONG *height, WORD *bpp, DWORD *compr )
453 if (header->biSize == sizeof(BITMAPCOREHEADER))
455 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
456 *width = core->bcWidth;
457 *height = core->bcHeight;
458 *bpp = core->bcBitCount;
459 *compr = 0;
460 return 0;
462 else if (header->biSize == sizeof(BITMAPINFOHEADER) ||
463 header->biSize == sizeof(BITMAPV4HEADER) ||
464 header->biSize == sizeof(BITMAPV5HEADER))
466 *width = header->biWidth;
467 *height = header->biHeight;
468 *bpp = header->biBitCount;
469 *compr = header->biCompression;
470 return 1;
472 WARN("unknown/wrong size (%u) for header\n", header->biSize);
473 return -1;
476 /**********************************************************************
477 * get_icon_size
479 BOOL get_icon_size( HICON handle, SIZE *size )
481 struct cursoricon_object *info;
482 struct cursoricon_frame *frame;
484 if (!(info = get_icon_ptr( handle ))) return FALSE;
485 frame = get_icon_frame( info, 0 );
486 size->cx = frame->width;
487 size->cy = frame->height;
488 release_icon_frame( info, frame);
489 release_user_handle_ptr( info );
490 return TRUE;
494 * The following macro functions account for the irregularities of
495 * accessing cursor and icon resources in files and resource entries.
497 typedef BOOL (*fnGetCIEntry)( LPCVOID dir, DWORD size, int n,
498 int *width, int *height, int *bits );
500 /**********************************************************************
501 * CURSORICON_FindBestIcon
503 * Find the icon closest to the requested size and bit depth.
505 static int CURSORICON_FindBestIcon( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
506 int width, int height, int depth, UINT loadflags )
508 int i, cx, cy, bits, bestEntry = -1;
509 UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
510 UINT iTempXDiff, iTempYDiff, iTempColorDiff;
512 /* Find Best Fit */
513 iTotalDiff = 0xFFFFFFFF;
514 iColorDiff = 0xFFFFFFFF;
516 if (loadflags & LR_DEFAULTSIZE)
518 if (!width) width = GetSystemMetrics( SM_CXICON );
519 if (!height) height = GetSystemMetrics( SM_CYICON );
521 else if (!width && !height)
523 /* use the size of the first entry */
524 if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
525 iTotalDiff = 0;
528 for ( i = 0; iTotalDiff && get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
530 iTempXDiff = abs(width - cx);
531 iTempYDiff = abs(height - cy);
533 if(iTotalDiff > (iTempXDiff + iTempYDiff))
535 iXDiff = iTempXDiff;
536 iYDiff = iTempYDiff;
537 iTotalDiff = iXDiff + iYDiff;
541 /* Find Best Colors for Best Fit */
542 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
544 TRACE("entry %d: %d x %d, %d bpp\n", i, cx, cy, bits);
546 if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
548 iTempColorDiff = abs(depth - bits);
549 if(iColorDiff > iTempColorDiff)
551 bestEntry = i;
552 iColorDiff = iTempColorDiff;
557 return bestEntry;
560 static BOOL CURSORICON_GetResIconEntry( LPCVOID dir, DWORD size, int n,
561 int *width, int *height, int *bits )
563 const CURSORICONDIR *resdir = dir;
564 const ICONRESDIR *icon;
566 if ( resdir->idCount <= n )
567 return FALSE;
568 if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
569 return FALSE;
570 icon = &resdir->idEntries[n].ResInfo.icon;
571 *width = icon->bWidth;
572 *height = icon->bHeight;
573 *bits = resdir->idEntries[n].wBitCount;
574 if (!*width && !*height && have_libpng()) *width = *height = 256;
575 return TRUE;
578 /**********************************************************************
579 * CURSORICON_FindBestCursor
581 * Find the cursor closest to the requested size.
583 * FIXME: parameter 'color' ignored.
585 static int CURSORICON_FindBestCursor( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
586 int width, int height, int depth, UINT loadflags )
588 int i, maxwidth, maxheight, maxbits, cx, cy, bits, bestEntry = -1;
590 if (loadflags & LR_DEFAULTSIZE)
592 if (!width) width = GetSystemMetrics( SM_CXCURSOR );
593 if (!height) height = GetSystemMetrics( SM_CYCURSOR );
595 else if (!width && !height)
597 /* use the first entry */
598 if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
599 return 0;
602 /* First find the largest one smaller than or equal to the requested size*/
604 maxwidth = maxheight = maxbits = 0;
605 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
607 if (cx > width || cy > height) continue;
608 if (cx < maxwidth || cy < maxheight) continue;
609 if (cx == maxwidth && cy == maxheight)
611 if (loadflags & LR_MONOCHROME)
613 if (maxbits && bits >= maxbits) continue;
615 else if (bits <= maxbits) continue;
617 bestEntry = i;
618 maxwidth = cx;
619 maxheight = cy;
620 maxbits = bits;
622 if (bestEntry != -1) return bestEntry;
624 /* Now find the smallest one larger than the requested size */
626 maxwidth = maxheight = 255;
627 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
629 if (cx > maxwidth || cy > maxheight) continue;
630 if (cx == maxwidth && cy == maxheight)
632 if (loadflags & LR_MONOCHROME)
634 if (maxbits && bits >= maxbits) continue;
636 else if (bits <= maxbits) continue;
638 bestEntry = i;
639 maxwidth = cx;
640 maxheight = cy;
641 maxbits = bits;
643 if (bestEntry == -1) bestEntry = 0;
645 return bestEntry;
648 static BOOL CURSORICON_GetResCursorEntry( LPCVOID dir, DWORD size, int n,
649 int *width, int *height, int *bits )
651 const CURSORICONDIR *resdir = dir;
652 const CURSORDIR *cursor;
654 if ( resdir->idCount <= n )
655 return FALSE;
656 if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
657 return FALSE;
658 cursor = &resdir->idEntries[n].ResInfo.cursor;
659 *width = cursor->wWidth;
660 *height = cursor->wHeight;
661 *bits = resdir->idEntries[n].wBitCount;
662 if (*height == *width * 2) *height /= 2;
663 return TRUE;
666 static const CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( const CURSORICONDIR * dir, DWORD size,
667 int width, int height, int depth,
668 UINT loadflags )
670 int n;
672 n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetResIconEntry,
673 width, height, depth, loadflags );
674 if ( n < 0 )
675 return NULL;
676 return &dir->idEntries[n];
679 static const CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( const CURSORICONDIR *dir, DWORD size,
680 int width, int height, int depth,
681 UINT loadflags )
683 int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetResCursorEntry,
684 width, height, depth, loadflags );
685 if ( n < 0 )
686 return NULL;
687 return &dir->idEntries[n];
690 static BOOL CURSORICON_GetFileEntry( LPCVOID dir, DWORD size, int n,
691 int *width, int *height, int *bits )
693 const CURSORICONFILEDIR *filedir = dir;
694 const CURSORICONFILEDIRENTRY *entry;
695 const BITMAPINFOHEADER *info;
697 if ( filedir->idCount <= n )
698 return FALSE;
699 if ((const char *)&filedir->idEntries[n + 1] - (const char *)dir > size)
700 return FALSE;
701 entry = &filedir->idEntries[n];
702 if (entry->dwDIBOffset > size - sizeof(info->biSize)) return FALSE;
703 info = (const BITMAPINFOHEADER *)((const char *)dir + entry->dwDIBOffset);
705 if (info->biSize == PNG_SIGN)
707 if (have_libpng()) return png_funcs->get_png_info(info, size, width, height, bits);
708 *width = *height = *bits = 0;
709 return TRUE;
712 if (info->biSize != sizeof(BITMAPCOREHEADER))
714 if ((const char *)(info + 1) - (const char *)dir > size) return FALSE;
715 *bits = info->biBitCount;
717 else
719 const BITMAPCOREHEADER *coreinfo = (const BITMAPCOREHEADER *)((const char *)dir + entry->dwDIBOffset);
720 if ((const char *)(coreinfo + 1) - (const char *)dir > size) return FALSE;
721 *bits = coreinfo->bcBitCount;
723 *width = entry->bWidth;
724 *height = entry->bHeight;
725 return TRUE;
728 static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( const CURSORICONFILEDIR *dir, DWORD size,
729 int width, int height, int depth,
730 UINT loadflags )
732 int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetFileEntry,
733 width, height, depth, loadflags );
734 if ( n < 0 )
735 return NULL;
736 return &dir->idEntries[n];
739 static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( const CURSORICONFILEDIR *dir, DWORD size,
740 int width, int height, int depth,
741 UINT loadflags )
743 int n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetFileEntry,
744 width, height, depth, loadflags );
745 if ( n < 0 )
746 return NULL;
747 return &dir->idEntries[n];
750 /***********************************************************************
751 * bmi_has_alpha
753 static BOOL bmi_has_alpha( const BITMAPINFO *info, const void *bits )
755 int i;
756 BOOL has_alpha = FALSE;
757 const unsigned char *ptr = bits;
759 if (info->bmiHeader.biBitCount != 32) return FALSE;
760 for (i = 0; i < info->bmiHeader.biWidth * abs(info->bmiHeader.biHeight); i++, ptr += 4)
761 if ((has_alpha = (ptr[3] != 0))) break;
762 return has_alpha;
765 /***********************************************************************
766 * create_alpha_bitmap
768 * Create the alpha bitmap for a 32-bpp icon that has an alpha channel.
770 static HBITMAP create_alpha_bitmap( HBITMAP color, const BITMAPINFO *src_info, const void *color_bits )
772 HBITMAP alpha = 0;
773 BITMAPINFO *info = NULL;
774 BITMAP bm;
775 HDC hdc;
776 void *bits;
777 unsigned char *ptr;
778 int i;
780 if (!GetObjectW( color, sizeof(bm), &bm )) return 0;
781 if (bm.bmBitsPixel != 32) return 0;
783 if (!(hdc = CreateCompatibleDC( 0 ))) return 0;
784 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto done;
785 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
786 info->bmiHeader.biWidth = bm.bmWidth;
787 info->bmiHeader.biHeight = -bm.bmHeight;
788 info->bmiHeader.biPlanes = 1;
789 info->bmiHeader.biBitCount = 32;
790 info->bmiHeader.biCompression = BI_RGB;
791 info->bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
792 info->bmiHeader.biXPelsPerMeter = 0;
793 info->bmiHeader.biYPelsPerMeter = 0;
794 info->bmiHeader.biClrUsed = 0;
795 info->bmiHeader.biClrImportant = 0;
796 if (!(alpha = CreateDIBSection( hdc, info, DIB_RGB_COLORS, &bits, NULL, 0 ))) goto done;
798 if (src_info)
800 SelectObject( hdc, alpha );
801 StretchDIBits( hdc, 0, 0, bm.bmWidth, bm.bmHeight,
802 0, 0, src_info->bmiHeader.biWidth, src_info->bmiHeader.biHeight,
803 color_bits, src_info, DIB_RGB_COLORS, SRCCOPY );
806 else
808 GetDIBits( hdc, color, 0, bm.bmHeight, bits, info, DIB_RGB_COLORS );
809 if (!bmi_has_alpha( info, bits ))
811 DeleteObject( alpha );
812 alpha = 0;
813 goto done;
817 /* pre-multiply by alpha */
818 for (i = 0, ptr = bits; i < bm.bmWidth * bm.bmHeight; i++, ptr += 4)
820 unsigned int alpha = ptr[3];
821 ptr[0] = ptr[0] * alpha / 255;
822 ptr[1] = ptr[1] * alpha / 255;
823 ptr[2] = ptr[2] * alpha / 255;
826 done:
827 DeleteDC( hdc );
828 HeapFree( GetProcessHeap(), 0, info );
829 return alpha;
833 /***********************************************************************
834 * create_icon_from_bmi
836 * Create an icon from its BITMAPINFO.
838 static HICON create_icon_from_bmi( const BITMAPINFO *bmi, DWORD maxsize, HMODULE module, LPCWSTR resname,
839 HRSRC rsrc, POINT hotspot, BOOL bIcon, INT width, INT height,
840 UINT cFlag )
842 DWORD size, color_size, mask_size;
843 HBITMAP color = 0, mask = 0, alpha = 0;
844 const void *color_bits, *mask_bits;
845 void *alpha_mask_bits = NULL;
846 BITMAPINFO *bmi_copy;
847 BOOL ret = FALSE;
848 BOOL do_stretch;
849 HICON hObj = 0;
850 HDC hdc = 0;
851 LONG bmi_width, bmi_height;
852 WORD bpp;
853 DWORD compr;
855 /* Check bitmap header */
857 if (bmi->bmiHeader.biSize == PNG_SIGN)
859 BITMAPINFO *bmi_png;
861 if (!have_libpng()) return 0;
862 bmi_png = png_funcs->load_png( (const char *)bmi, &maxsize );
863 if (bmi_png)
865 hObj = create_icon_from_bmi( bmi_png, maxsize, module, resname,
866 rsrc, hotspot, bIcon, width, height, cFlag );
867 HeapFree( GetProcessHeap(), 0, bmi_png );
868 return hObj;
870 return 0;
873 if (maxsize < sizeof(BITMAPCOREHEADER))
875 WARN( "invalid size %u\n", maxsize );
876 return 0;
878 if (maxsize < bmi->bmiHeader.biSize)
880 WARN( "invalid header size %u\n", bmi->bmiHeader.biSize );
881 return 0;
883 if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
884 (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER) ||
885 (bmi->bmiHeader.biCompression != BI_RGB &&
886 bmi->bmiHeader.biCompression != BI_BITFIELDS)) )
888 WARN( "invalid bitmap header %u\n", bmi->bmiHeader.biSize );
889 return 0;
892 size = bitmap_info_size( bmi, DIB_RGB_COLORS );
893 DIB_GetBitmapInfo(&bmi->bmiHeader, &bmi_width, &bmi_height, &bpp, &compr);
894 color_size = get_dib_image_size( bmi_width, bmi_height / 2,
895 bpp );
896 mask_size = get_dib_image_size( bmi_width, bmi_height / 2, 1 );
897 if (size > maxsize || color_size > maxsize - size)
899 WARN( "truncated file %u < %u+%u+%u\n", maxsize, size, color_size, mask_size );
900 return 0;
902 if (mask_size > maxsize - size - color_size) mask_size = 0; /* no mask */
904 if (cFlag & LR_DEFAULTSIZE)
906 if (!width) width = GetSystemMetrics( bIcon ? SM_CXICON : SM_CXCURSOR );
907 if (!height) height = GetSystemMetrics( bIcon ? SM_CYICON : SM_CYCURSOR );
909 else
911 if (!width) width = bmi_width;
912 if (!height) height = bmi_height/2;
914 do_stretch = (bmi_height/2 != height) ||
915 (bmi_width != width);
917 /* Scale the hotspot */
918 if (bIcon)
920 hotspot.x = width / 2;
921 hotspot.y = height / 2;
923 else if (do_stretch)
925 hotspot.x = (hotspot.x * width) / bmi_width;
926 hotspot.y = (hotspot.y * height) / (bmi_height / 2);
929 if (!(bmi_copy = HeapAlloc( GetProcessHeap(), 0, max( size, FIELD_OFFSET( BITMAPINFO, bmiColors[2] )))))
930 return 0;
931 if (!(hdc = CreateCompatibleDC( 0 ))) goto done;
933 memcpy( bmi_copy, bmi, size );
934 if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
935 bmi_copy->bmiHeader.biHeight /= 2;
936 else
937 ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcHeight /= 2;
938 bmi_height /= 2;
940 color_bits = (const char*)bmi + size;
941 mask_bits = (const char*)color_bits + color_size;
943 alpha = 0;
944 if (is_dib_monochrome( bmi ))
946 if (!(mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
947 color = 0;
949 /* copy color data into second half of mask bitmap */
950 SelectObject( hdc, mask );
951 StretchDIBits( hdc, 0, height, width, height,
952 0, 0, bmi_width, bmi_height,
953 color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
955 else
957 if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
958 if (!(color = create_color_bitmap( width, height )))
960 DeleteObject( mask );
961 goto done;
963 SelectObject( hdc, color );
964 StretchDIBits( hdc, 0, 0, width, height,
965 0, 0, bmi_width, bmi_height,
966 color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
968 if (bmi_has_alpha( bmi_copy, color_bits ))
970 alpha = create_alpha_bitmap( color, bmi_copy, color_bits );
971 if (!mask_size) /* generate mask from alpha */
973 LONG x, y, dst_stride = ((bmi_width + 31) / 8) & ~3;
975 if ((alpha_mask_bits = heap_calloc( bmi_height, dst_stride )))
977 static const unsigned char masks[] = { 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 };
978 const DWORD *src = color_bits;
979 unsigned char *dst = alpha_mask_bits;
981 for (y = 0; y < bmi_height; y++, src += bmi_width, dst += dst_stride)
982 for (x = 0; x < bmi_width; x++)
983 if (src[x] >> 24 != 0xff) dst[x >> 3] |= masks[x & 7];
985 mask_bits = alpha_mask_bits;
986 mask_size = bmi_height * dst_stride;
991 /* convert info to monochrome to copy the mask */
992 if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
994 RGBQUAD *rgb = bmi_copy->bmiColors;
996 bmi_copy->bmiHeader.biBitCount = 1;
997 bmi_copy->bmiHeader.biClrUsed = bmi_copy->bmiHeader.biClrImportant = 2;
998 rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
999 rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
1000 rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
1002 else
1004 RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)bmi_copy) + 1);
1006 ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcBitCount = 1;
1007 rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
1008 rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
1012 if (mask_size)
1014 SelectObject( hdc, mask );
1015 StretchDIBits( hdc, 0, 0, width, height,
1016 0, 0, bmi_width, bmi_height,
1017 mask_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1019 ret = TRUE;
1021 done:
1022 DeleteDC( hdc );
1023 HeapFree( GetProcessHeap(), 0, bmi_copy );
1024 HeapFree( GetProcessHeap(), 0, alpha_mask_bits );
1026 if (ret)
1027 hObj = alloc_icon_handle( FALSE, 0 );
1028 if (hObj)
1030 struct cursoricon_object *info = get_icon_ptr( hObj );
1031 struct cursoricon_frame *frame;
1033 info->is_icon = bIcon;
1034 info->module = module;
1035 info->hotspot = hotspot;
1036 frame = get_icon_frame( info, 0 );
1037 frame->delay = ~0;
1038 frame->width = width;
1039 frame->height = height;
1040 frame->color = color;
1041 frame->mask = mask;
1042 frame->alpha = alpha;
1043 release_icon_frame( info, frame );
1044 if (!IS_INTRESOURCE(resname))
1046 info->resname = HeapAlloc( GetProcessHeap(), 0, (lstrlenW(resname) + 1) * sizeof(WCHAR) );
1047 if (info->resname) lstrcpyW( info->resname, resname );
1049 else info->resname = MAKEINTRESOURCEW( LOWORD(resname) );
1051 if (module && (cFlag & LR_SHARED))
1053 info->rsrc = rsrc;
1054 list_add_head( &icon_cache, &info->entry );
1056 release_user_handle_ptr( info );
1058 else
1060 DeleteObject( color );
1061 DeleteObject( alpha );
1062 DeleteObject( mask );
1064 return hObj;
1068 /**********************************************************************
1069 * .ANI cursor support
1071 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
1072 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
1073 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
1074 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
1075 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
1076 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
1077 #define ANI_rate_ID RIFF_FOURCC('r', 'a', 't', 'e')
1079 #define ANI_FLAG_ICON 0x1
1080 #define ANI_FLAG_SEQUENCE 0x2
1082 typedef struct {
1083 DWORD header_size;
1084 DWORD num_frames;
1085 DWORD num_steps;
1086 DWORD width;
1087 DWORD height;
1088 DWORD bpp;
1089 DWORD num_planes;
1090 DWORD display_rate;
1091 DWORD flags;
1092 } ani_header;
1094 typedef struct {
1095 DWORD data_size;
1096 const unsigned char *data;
1097 } riff_chunk_t;
1099 static void dump_ani_header( const ani_header *header )
1101 TRACE(" header size: %d\n", header->header_size);
1102 TRACE(" frames: %d\n", header->num_frames);
1103 TRACE(" steps: %d\n", header->num_steps);
1104 TRACE(" width: %d\n", header->width);
1105 TRACE(" height: %d\n", header->height);
1106 TRACE(" bpp: %d\n", header->bpp);
1107 TRACE(" planes: %d\n", header->num_planes);
1108 TRACE(" display rate: %d\n", header->display_rate);
1109 TRACE(" flags: 0x%08x\n", header->flags);
1114 * RIFF:
1115 * DWORD "RIFF"
1116 * DWORD size
1117 * DWORD riff_id
1118 * BYTE[] data
1120 * LIST:
1121 * DWORD "LIST"
1122 * DWORD size
1123 * DWORD list_id
1124 * BYTE[] data
1126 * CHUNK:
1127 * DWORD chunk_id
1128 * DWORD size
1129 * BYTE[] data
1131 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
1133 const unsigned char *ptr = parent_chunk->data;
1134 const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
1136 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
1138 while (ptr < end)
1140 if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
1141 || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1143 ptr += sizeof(DWORD);
1144 chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1145 ptr += sizeof(DWORD);
1146 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
1147 chunk->data = ptr;
1149 return;
1152 ptr += sizeof(DWORD);
1153 if (ptr >= end)
1154 break;
1155 ptr += (*(const DWORD *)ptr + 1) & ~1;
1156 ptr += sizeof(DWORD);
1162 * .ANI layout:
1164 * RIFF:'ACON' RIFF chunk
1165 * |- CHUNK:'anih' Header
1166 * |- CHUNK:'seq ' Sequence information (optional)
1167 * \- LIST:'fram' Frame list
1168 * |- CHUNK:icon Cursor frames
1169 * |- CHUNK:icon
1170 * |- ...
1171 * \- CHUNK:icon
1173 static HCURSOR CURSORICON_CreateIconFromANI( const BYTE *bits, DWORD bits_size, INT width, INT height,
1174 INT depth, BOOL is_icon, UINT loadflags )
1176 struct animated_cursoricon_object *ani_icon_data;
1177 struct cursoricon_object *info;
1178 DWORD *frame_rates = NULL;
1179 DWORD *frame_seq = NULL;
1180 ani_header header;
1181 BOOL use_seq = FALSE;
1182 HCURSOR cursor;
1183 UINT i;
1184 BOOL error = FALSE;
1185 HICON *frames;
1187 riff_chunk_t root_chunk = { bits_size, bits };
1188 riff_chunk_t ACON_chunk = {0};
1189 riff_chunk_t anih_chunk = {0};
1190 riff_chunk_t fram_chunk = {0};
1191 riff_chunk_t rate_chunk = {0};
1192 riff_chunk_t seq_chunk = {0};
1193 const unsigned char *icon_chunk;
1194 const unsigned char *icon_data;
1196 TRACE("bits %p, bits_size %d\n", bits, bits_size);
1198 riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1199 if (!ACON_chunk.data)
1201 ERR("Failed to get root chunk.\n");
1202 return 0;
1205 riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1206 if (!anih_chunk.data)
1208 ERR("Failed to get 'anih' chunk.\n");
1209 return 0;
1211 memcpy( &header, anih_chunk.data, sizeof(header) );
1212 dump_ani_header( &header );
1214 if (!(header.flags & ANI_FLAG_ICON))
1216 FIXME("Raw animated icon/cursor data is not currently supported.\n");
1217 return 0;
1220 if (header.flags & ANI_FLAG_SEQUENCE)
1222 riff_find_chunk( ANI_seq__ID, 0, &ACON_chunk, &seq_chunk );
1223 if (seq_chunk.data)
1225 frame_seq = (DWORD *) seq_chunk.data;
1226 use_seq = TRUE;
1228 else
1230 FIXME("Sequence data expected but not found, assuming steps == frames.\n");
1231 header.num_steps = header.num_frames;
1235 riff_find_chunk( ANI_rate_ID, 0, &ACON_chunk, &rate_chunk );
1236 if (rate_chunk.data)
1237 frame_rates = (DWORD *) rate_chunk.data;
1239 riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1240 if (!fram_chunk.data)
1242 ERR("Failed to get icon list.\n");
1243 return 0;
1246 cursor = alloc_icon_handle( TRUE, header.num_steps );
1247 if (!cursor) return 0;
1248 frames = HeapAlloc( GetProcessHeap(), 0, sizeof(*frames) * header.num_frames );
1249 if (!frames)
1251 free_icon_handle( cursor );
1252 return 0;
1255 info = get_icon_ptr( cursor );
1256 ani_icon_data = (struct animated_cursoricon_object *) info;
1257 info->is_icon = is_icon;
1258 ani_icon_data->num_frames = header.num_frames;
1260 /* The .ANI stores the display rate in jiffies (1/60s) */
1261 info->delay = header.display_rate;
1263 icon_chunk = fram_chunk.data;
1264 icon_data = fram_chunk.data + (2 * sizeof(DWORD));
1265 for (i=0; i<header.num_frames; i++)
1267 const DWORD chunk_size = *(const DWORD *)(icon_chunk + sizeof(DWORD));
1268 const CURSORICONFILEDIRENTRY *entry;
1269 INT frameWidth, frameHeight;
1270 const BITMAPINFO *bmi;
1272 entry = CURSORICON_FindBestIconFile((const CURSORICONFILEDIR *) icon_data,
1273 bits + bits_size - icon_data,
1274 width, height, depth, loadflags );
1276 info->hotspot.x = entry->xHotspot;
1277 info->hotspot.y = entry->yHotspot;
1278 if (!header.width || !header.height)
1280 frameWidth = entry->bWidth;
1281 frameHeight = entry->bHeight;
1283 else
1285 frameWidth = header.width;
1286 frameHeight = header.height;
1289 frames[i] = NULL;
1290 if (entry->dwDIBOffset < bits + bits_size - icon_data)
1292 bmi = (const BITMAPINFO *) (icon_data + entry->dwDIBOffset);
1293 /* Grab a frame from the animation */
1294 frames[i] = create_icon_from_bmi( bmi, bits + bits_size - (const BYTE *)bmi,
1295 NULL, NULL, NULL, info->hotspot,
1296 is_icon, frameWidth, frameHeight, loadflags );
1299 if (!frames[i])
1301 FIXME_(cursor)("failed to convert animated cursor frame.\n");
1302 error = TRUE;
1303 if (i == 0)
1305 FIXME_(cursor)("Completely failed to create animated cursor!\n");
1306 ani_icon_data->num_frames = 0;
1307 release_user_handle_ptr( info );
1308 free_icon_handle( cursor );
1309 HeapFree( GetProcessHeap(), 0, frames );
1310 return 0;
1312 break;
1315 /* Advance to the next chunk */
1316 icon_chunk += chunk_size + (2 * sizeof(DWORD));
1317 icon_data = icon_chunk + (2 * sizeof(DWORD));
1320 /* There was an error but we at least decoded the first frame, so just use that frame */
1321 if (error)
1323 FIXME_(cursor)("Error creating animated cursor, only using first frame!\n");
1324 for (i=1; i<ani_icon_data->num_frames; i++)
1325 free_icon_handle( ani_icon_data->frames[i] );
1326 use_seq = FALSE;
1327 info->delay = 0;
1328 ani_icon_data->num_steps = 1;
1329 ani_icon_data->num_frames = 1;
1332 /* Setup the animated frames in the correct sequence */
1333 for (i=0; i<ani_icon_data->num_steps; i++)
1335 DWORD frame_id = use_seq ? frame_seq[i] : i;
1336 struct cursoricon_frame *frame;
1338 if (frame_id >= ani_icon_data->num_frames)
1340 frame_id = ani_icon_data->num_frames-1;
1341 ERR_(cursor)("Sequence indicates frame past end of list, corrupt?\n");
1343 ani_icon_data->frames[i] = frames[frame_id];
1344 frame = get_icon_frame( info, i );
1345 if (frame_rates)
1346 frame->delay = frame_rates[i];
1347 else
1348 frame->delay = ~0;
1349 release_icon_frame( info, frame );
1352 HeapFree( GetProcessHeap(), 0, frames );
1353 release_user_handle_ptr( info );
1355 return cursor;
1359 /**********************************************************************
1360 * CreateIconFromResourceEx (USER32.@)
1362 * FIXME: Convert to mono when cFlag is LR_MONOCHROME.
1364 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1365 BOOL bIcon, DWORD dwVersion,
1366 INT width, INT height,
1367 UINT cFlag )
1369 POINT hotspot;
1370 const BITMAPINFO *bmi;
1372 TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s %s\n",
1373 bits, cbSize, dwVersion, width, height,
1374 bIcon ? "icon" : "cursor", (cFlag & LR_MONOCHROME) ? "mono" : "" );
1376 if (!bits) return 0;
1378 if (dwVersion == 0x00020000)
1380 FIXME_(cursor)("\t2.xx resources are not supported\n");
1381 return 0;
1384 /* Check if the resource is an animated icon/cursor */
1385 if (!memcmp(bits, "RIFF", 4))
1386 return CURSORICON_CreateIconFromANI( bits, cbSize, width, height,
1387 0 /* default depth */, bIcon, cFlag );
1389 if (bIcon)
1391 hotspot.x = width / 2;
1392 hotspot.y = height / 2;
1393 bmi = (BITMAPINFO *)bits;
1395 else /* get the hotspot */
1397 const SHORT *pt = (const SHORT *)bits;
1398 hotspot.x = pt[0];
1399 hotspot.y = pt[1];
1400 bmi = (const BITMAPINFO *)(pt + 2);
1401 cbSize -= 2 * sizeof(*pt);
1404 return create_icon_from_bmi( bmi, cbSize, NULL, NULL, NULL, hotspot, bIcon, width, height, cFlag );
1408 /**********************************************************************
1409 * CreateIconFromResource (USER32.@)
1411 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1412 BOOL bIcon, DWORD dwVersion)
1414 return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
1418 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1419 INT width, INT height, INT depth,
1420 BOOL fCursor, UINT loadflags)
1422 const CURSORICONFILEDIRENTRY *entry;
1423 const CURSORICONFILEDIR *dir;
1424 DWORD filesize = 0;
1425 HICON hIcon = 0;
1426 const BYTE *bits;
1427 POINT hotspot;
1429 TRACE("loading %s\n", debugstr_w( filename ));
1431 bits = map_fileW( filename, &filesize );
1432 if (!bits)
1433 return hIcon;
1435 /* Check for .ani. */
1436 if (memcmp( bits, "RIFF", 4 ) == 0)
1438 hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height, depth, !fCursor, loadflags );
1439 goto end;
1442 dir = (const CURSORICONFILEDIR*) bits;
1443 if ( filesize < FIELD_OFFSET( CURSORICONFILEDIR, idEntries[dir->idCount] ))
1444 goto end;
1446 if ( fCursor )
1447 entry = CURSORICON_FindBestCursorFile( dir, filesize, width, height, depth, loadflags );
1448 else
1449 entry = CURSORICON_FindBestIconFile( dir, filesize, width, height, depth, loadflags );
1451 if ( !entry )
1452 goto end;
1454 /* check that we don't run off the end of the file */
1455 if ( entry->dwDIBOffset > filesize )
1456 goto end;
1457 if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1458 goto end;
1460 hotspot.x = entry->xHotspot;
1461 hotspot.y = entry->yHotspot;
1462 hIcon = create_icon_from_bmi( (const BITMAPINFO *)&bits[entry->dwDIBOffset], filesize - entry->dwDIBOffset,
1463 NULL, NULL, NULL, hotspot, !fCursor, width, height, loadflags );
1464 end:
1465 TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1466 UnmapViewOfFile( bits );
1467 return hIcon;
1470 /**********************************************************************
1471 * CURSORICON_Load
1473 * Load a cursor or icon from resource or file.
1475 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1476 INT width, INT height, INT depth,
1477 BOOL fCursor, UINT loadflags)
1479 HANDLE handle = 0;
1480 HICON hIcon = 0;
1481 HRSRC hRsrc;
1482 DWORD size;
1483 const CURSORICONDIR *dir;
1484 const CURSORICONDIRENTRY *dirEntry;
1485 const BYTE *bits;
1486 WORD wResId;
1487 POINT hotspot;
1489 TRACE("%p, %s, %dx%d, depth %d, fCursor %d, flags 0x%04x\n",
1490 hInstance, debugstr_w(name), width, height, depth, fCursor, loadflags);
1492 if ( loadflags & LR_LOADFROMFILE ) /* Load from file */
1493 return CURSORICON_LoadFromFile( name, width, height, depth, fCursor, loadflags );
1495 if (!hInstance) hInstance = user32_module; /* Load OEM cursor/icon */
1497 /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1498 if ((ULONG_PTR)hInstance >> 16 == 0) loadflags &= ~LR_SHARED;
1500 /* Get directory resource ID */
1502 if (!(hRsrc = FindResourceW( hInstance, name,
1503 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1505 /* try animated resource */
1506 if (!(hRsrc = FindResourceW( hInstance, name,
1507 (LPWSTR)(fCursor ? RT_ANICURSOR : RT_ANIICON) ))) return 0;
1508 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1509 bits = LockResource( handle );
1510 return CURSORICON_CreateIconFromANI( bits, SizeofResource( hInstance, handle ),
1511 width, height, depth, !fCursor, loadflags );
1514 /* Find the best entry in the directory */
1516 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1517 if (!(dir = LockResource( handle ))) return 0;
1518 size = SizeofResource( hInstance, hRsrc );
1519 if (fCursor)
1520 dirEntry = CURSORICON_FindBestCursorRes( dir, size, width, height, depth, loadflags );
1521 else
1522 dirEntry = CURSORICON_FindBestIconRes( dir, size, width, height, depth, loadflags );
1523 if (!dirEntry) return 0;
1524 wResId = dirEntry->wResId;
1525 FreeResource( handle );
1527 /* Load the resource */
1529 if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1530 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1532 /* If shared icon, check whether it was already loaded */
1533 if (loadflags & LR_SHARED)
1535 struct cursoricon_object *ptr;
1537 USER_Lock();
1538 LIST_FOR_EACH_ENTRY( ptr, &icon_cache, struct cursoricon_object, entry )
1540 if (ptr->module != hInstance) continue;
1541 if (ptr->rsrc != hRsrc) continue;
1542 hIcon = ptr->obj.handle;
1543 break;
1545 USER_Unlock();
1546 if (hIcon) return hIcon;
1549 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1550 size = SizeofResource( hInstance, hRsrc );
1551 bits = LockResource( handle );
1553 if (!fCursor)
1555 hotspot.x = width / 2;
1556 hotspot.y = height / 2;
1558 else /* get the hotspot */
1560 const SHORT *pt = (const SHORT *)bits;
1561 hotspot.x = pt[0];
1562 hotspot.y = pt[1];
1563 bits += 2 * sizeof(SHORT);
1564 size -= 2 * sizeof(SHORT);
1566 hIcon = create_icon_from_bmi( (const BITMAPINFO *)bits, size, hInstance, name, hRsrc,
1567 hotspot, !fCursor, width, height, loadflags );
1568 FreeResource( handle );
1569 return hIcon;
1573 static HBITMAP create_masked_bitmap( int width, int height, const void *and, const void *xor )
1575 HDC dc = CreateCompatibleDC( 0 );
1576 HBITMAP bitmap;
1578 const BITMAPINFO bitmap_info =
1580 .bmiHeader.biSize = sizeof(BITMAPINFOHEADER),
1581 .bmiHeader.biWidth = width,
1582 .bmiHeader.biHeight = height * 2,
1583 .bmiHeader.biPlanes = 1,
1584 .bmiHeader.biBitCount = 1,
1587 bitmap = CreateBitmap( width, height * 2, 1, 1, NULL );
1588 SetDIBits( dc, bitmap, 0, height, and, &bitmap_info, FALSE );
1589 SetDIBits( dc, bitmap, height, height, xor, &bitmap_info, FALSE );
1590 DeleteDC( dc );
1591 return bitmap;
1595 /***********************************************************************
1596 * CreateCursor (USER32.@)
1598 HCURSOR WINAPI CreateCursor( HINSTANCE instance, int hotspot_x, int hotspot_y,
1599 int width, int height, const void *and, const void *xor )
1601 ICONINFO info;
1602 HCURSOR cursor;
1604 TRACE( "hotspot (%d,%d), size %dx%d\n", hotspot_x, hotspot_y, width, height );
1606 info.fIcon = FALSE;
1607 info.xHotspot = hotspot_x;
1608 info.yHotspot = hotspot_y;
1609 info.hbmColor = NULL;
1610 info.hbmMask = create_masked_bitmap( width, height, and, xor );
1611 cursor = CreateIconIndirect( &info );
1612 DeleteObject( info.hbmMask );
1613 return cursor;
1617 /***********************************************************************
1618 * CreateIcon (USER32.@)
1620 * Creates an icon based on the specified bitmaps. The bitmaps must be
1621 * provided in a device dependent format and will be resized to
1622 * (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1623 * depth. The provided bitmaps must be top-down bitmaps.
1624 * Although Windows does not support 15bpp(*) this API must support it
1625 * for Winelib applications.
1627 * (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1628 * format!
1630 * RETURNS
1631 * Success: handle to an icon
1632 * Failure: NULL
1634 * FIXME: Do we need to resize the bitmaps?
1636 HICON WINAPI CreateIcon( HINSTANCE instance, int width, int height, BYTE planes,
1637 BYTE depth, const void *and, const void *xor )
1639 ICONINFO info;
1640 HICON icon;
1642 TRACE_(icon)( "%dx%d, planes %d, depth %d\n", width, height, planes, depth );
1644 info.fIcon = TRUE;
1645 info.xHotspot = width / 2;
1646 info.yHotspot = height / 2;
1647 if (depth == 1)
1649 info.hbmColor = NULL;
1650 info.hbmMask = create_masked_bitmap( width, height, and, xor );
1652 else
1654 info.hbmColor = CreateBitmap( width, height, planes, depth, xor );
1655 info.hbmMask = CreateBitmap( width, height, 1, 1, and );
1658 icon = CreateIconIndirect( &info );
1660 DeleteObject( info.hbmMask );
1661 DeleteObject( info.hbmColor );
1663 return icon;
1667 /***********************************************************************
1668 * CopyIcon (USER32.@)
1670 HICON WINAPI CopyIcon( HICON icon )
1672 ICONINFOEXW info;
1673 HICON res;
1675 info.cbSize = sizeof(info);
1676 if (!GetIconInfoExW( icon, &info ))
1677 return NULL;
1679 res = CopyImage( icon, info.fIcon ? IMAGE_ICON : IMAGE_CURSOR, 0, 0, 0 );
1680 DeleteObject( info.hbmColor );
1681 DeleteObject( info.hbmMask );
1682 return res;
1686 /***********************************************************************
1687 * DestroyIcon (USER32.@)
1689 BOOL WINAPI DestroyIcon( HICON hIcon )
1691 BOOL ret = FALSE;
1692 struct cursoricon_object *obj = get_icon_ptr( hIcon );
1694 TRACE_(icon)("%p\n", hIcon );
1696 if (obj)
1698 BOOL shared = (obj->rsrc != NULL);
1699 release_user_handle_ptr( obj );
1700 ret = (GetCursor() != hIcon);
1701 if (!shared) free_icon_handle( hIcon );
1703 return ret;
1707 /***********************************************************************
1708 * DestroyCursor (USER32.@)
1710 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
1712 return DestroyIcon( hCursor );
1715 /***********************************************************************
1716 * DrawIcon (USER32.@)
1718 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
1720 return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
1723 /***********************************************************************
1724 * SetCursor (USER32.@)
1726 * Set the cursor shape.
1728 * RETURNS
1729 * A handle to the previous cursor shape.
1731 HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1733 struct cursoricon_object *obj;
1734 HCURSOR hOldCursor;
1735 int show_count;
1736 BOOL ret;
1738 TRACE("%p\n", hCursor);
1740 SERVER_START_REQ( set_cursor )
1742 req->flags = SET_CURSOR_HANDLE;
1743 req->handle = wine_server_user_handle( hCursor );
1744 if ((ret = !wine_server_call_err( req )))
1746 hOldCursor = wine_server_ptr_handle( reply->prev_handle );
1747 show_count = reply->prev_count;
1750 SERVER_END_REQ;
1752 if (!ret) return 0;
1753 USER_Driver->pSetCursor( show_count >= 0 ? hCursor : 0 );
1755 if (!(obj = get_icon_ptr( hOldCursor ))) return 0;
1756 release_user_handle_ptr( obj );
1757 return hOldCursor;
1760 /***********************************************************************
1761 * ShowCursor (USER32.@)
1763 INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
1765 HCURSOR cursor;
1766 int increment = bShow ? 1 : -1;
1767 int count;
1769 SERVER_START_REQ( set_cursor )
1771 req->flags = SET_CURSOR_COUNT;
1772 req->show_count = increment;
1773 wine_server_call( req );
1774 cursor = wine_server_ptr_handle( reply->prev_handle );
1775 count = reply->prev_count + increment;
1777 SERVER_END_REQ;
1779 TRACE("%d, count=%d\n", bShow, count );
1781 if (bShow && !count) USER_Driver->pSetCursor( cursor );
1782 else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
1784 return count;
1787 /***********************************************************************
1788 * GetCursor (USER32.@)
1790 HCURSOR WINAPI GetCursor(void)
1792 HCURSOR ret;
1794 SERVER_START_REQ( set_cursor )
1796 req->flags = 0;
1797 wine_server_call( req );
1798 ret = wine_server_ptr_handle( reply->prev_handle );
1800 SERVER_END_REQ;
1801 return ret;
1805 /***********************************************************************
1806 * ClipCursor (USER32.@)
1808 BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
1810 UINT dpi;
1811 BOOL ret;
1812 RECT new_rect;
1814 TRACE( "Clipping to %s\n", wine_dbgstr_rect(rect) );
1816 if (rect)
1818 if (rect->left > rect->right || rect->top > rect->bottom) return FALSE;
1819 if ((dpi = get_thread_dpi()))
1821 new_rect = map_dpi_rect( *rect, dpi,
1822 get_monitor_dpi( MonitorFromRect( rect, MONITOR_DEFAULTTOPRIMARY )));
1823 rect = &new_rect;
1827 SERVER_START_REQ( set_cursor )
1829 req->clip_msg = WM_WINE_CLIPCURSOR;
1830 if (rect)
1832 req->flags = SET_CURSOR_CLIP;
1833 req->clip.left = rect->left;
1834 req->clip.top = rect->top;
1835 req->clip.right = rect->right;
1836 req->clip.bottom = rect->bottom;
1838 else req->flags = SET_CURSOR_NOCLIP;
1840 if ((ret = !wine_server_call( req )))
1842 new_rect.left = reply->new_clip.left;
1843 new_rect.top = reply->new_clip.top;
1844 new_rect.right = reply->new_clip.right;
1845 new_rect.bottom = reply->new_clip.bottom;
1848 SERVER_END_REQ;
1849 if (ret) USER_Driver->pClipCursor( &new_rect );
1850 return ret;
1854 /***********************************************************************
1855 * GetClipCursor (USER32.@)
1857 BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
1859 DPI_AWARENESS_CONTEXT context;
1860 UINT dpi;
1861 BOOL ret;
1863 if (!rect) return FALSE;
1865 SERVER_START_REQ( set_cursor )
1867 req->flags = 0;
1868 if ((ret = !wine_server_call( req )))
1870 rect->left = reply->new_clip.left;
1871 rect->top = reply->new_clip.top;
1872 rect->right = reply->new_clip.right;
1873 rect->bottom = reply->new_clip.bottom;
1876 SERVER_END_REQ;
1878 if (ret && (dpi = get_thread_dpi()))
1880 context = SetThreadDpiAwarenessContext( DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE );
1881 *rect = map_dpi_rect( *rect, get_monitor_dpi( MonitorFromRect( rect, MONITOR_DEFAULTTOPRIMARY )), dpi );
1882 SetThreadDpiAwarenessContext( context );
1884 return ret;
1888 /***********************************************************************
1889 * SetSystemCursor (USER32.@)
1891 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
1893 FIXME("(%p,%08x),stub!\n", hcur, id);
1894 return TRUE;
1898 /**********************************************************************
1899 * LookupIconIdFromDirectoryEx (USER32.@)
1901 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
1902 INT width, INT height, UINT cFlag )
1904 const CURSORICONDIR *dir = (const CURSORICONDIR*)xdir;
1905 UINT retVal = 0;
1906 if( dir && !dir->idReserved && (dir->idType & 3) )
1908 const CURSORICONDIRENTRY* entry;
1909 int depth = (cFlag & LR_MONOCHROME) ? 1 : get_display_bpp();
1911 if( bIcon )
1912 entry = CURSORICON_FindBestIconRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
1913 else
1914 entry = CURSORICON_FindBestCursorRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
1916 if( entry ) retVal = entry->wResId;
1918 else WARN_(cursor)("invalid resource directory\n");
1919 return retVal;
1922 /**********************************************************************
1923 * LookupIconIdFromDirectory (USER32.@)
1925 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
1927 return LookupIconIdFromDirectoryEx( dir, bIcon, 0, 0, bIcon ? 0 : LR_MONOCHROME );
1930 /***********************************************************************
1931 * LoadCursorW (USER32.@)
1933 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
1935 TRACE("%p, %s\n", hInstance, debugstr_w(name));
1937 return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1938 LR_SHARED | LR_DEFAULTSIZE );
1941 /***********************************************************************
1942 * LoadCursorA (USER32.@)
1944 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
1946 TRACE("%p, %s\n", hInstance, debugstr_a(name));
1948 return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1949 LR_SHARED | LR_DEFAULTSIZE );
1952 /***********************************************************************
1953 * LoadCursorFromFileW (USER32.@)
1955 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1957 TRACE("%s\n", debugstr_w(name));
1959 return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1960 LR_LOADFROMFILE | LR_DEFAULTSIZE );
1963 /***********************************************************************
1964 * LoadCursorFromFileA (USER32.@)
1966 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1968 TRACE("%s\n", debugstr_a(name));
1970 return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1971 LR_LOADFROMFILE | LR_DEFAULTSIZE );
1974 /***********************************************************************
1975 * LoadIconW (USER32.@)
1977 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
1979 TRACE("%p, %s\n", hInstance, debugstr_w(name));
1981 return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1982 LR_SHARED | LR_DEFAULTSIZE );
1985 /***********************************************************************
1986 * LoadIconA (USER32.@)
1988 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
1990 TRACE("%p, %s\n", hInstance, debugstr_a(name));
1992 return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1993 LR_SHARED | LR_DEFAULTSIZE );
1996 /**********************************************************************
1997 * GetCursorFrameInfo (USER32.@)
1999 * NOTES
2000 * So far no use has been found for the second parameter, it is currently presumed
2001 * that this parameter is reserved for future use.
2003 * PARAMS
2004 * hCursor [I] Handle to cursor for which to retrieve information
2005 * reserved [I] No purpose has been found for this parameter (may be NULL)
2006 * istep [I] The step of the cursor for which to retrieve information
2007 * rate_jiffies [O] Pointer to DWORD that receives the frame-specific delay (cannot be NULL)
2008 * num_steps [O] Pointer to DWORD that receives the number of steps in the cursor (cannot be NULL)
2010 * RETURNS
2011 * Success: Handle to a frame of the cursor (specified by istep)
2012 * Failure: NULL cursor (0)
2014 HCURSOR WINAPI GetCursorFrameInfo(HCURSOR hCursor, DWORD reserved, DWORD istep, DWORD *rate_jiffies, DWORD *num_steps)
2016 struct cursoricon_object *ptr;
2017 HCURSOR ret = 0;
2018 UINT icon_steps;
2020 if (rate_jiffies == NULL || num_steps == NULL) return 0;
2022 if (!(ptr = get_icon_ptr( hCursor ))) return 0;
2024 TRACE("%p => %d %d %p %p\n", hCursor, reserved, istep, rate_jiffies, num_steps);
2025 if (reserved != 0)
2026 FIXME("Second parameter non-zero (%d), please report this!\n", reserved);
2028 icon_steps = get_icon_steps(ptr);
2029 if (istep < icon_steps || !ptr->is_ani)
2031 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) ptr;
2032 UINT icon_frames = 1;
2034 if (ptr->is_ani)
2035 icon_frames = ani_icon_data->num_frames;
2036 if (ptr->is_ani && icon_frames > 1)
2037 ret = ani_icon_data->frames[istep];
2038 else
2039 ret = hCursor;
2040 if (icon_frames == 1)
2042 *rate_jiffies = 0;
2043 *num_steps = 1;
2045 else if (icon_steps == 1)
2047 *num_steps = ~0;
2048 *rate_jiffies = ptr->delay;
2050 else if (istep < icon_steps)
2052 struct cursoricon_frame *frame;
2054 *num_steps = icon_steps;
2055 frame = get_icon_frame( ptr, istep );
2056 if (get_icon_steps(ptr) == 1)
2057 *num_steps = ~0;
2058 else
2059 *num_steps = get_icon_steps(ptr);
2060 /* If this specific frame does not have a delay then use the global delay */
2061 if (frame->delay == ~0)
2062 *rate_jiffies = ptr->delay;
2063 else
2064 *rate_jiffies = frame->delay;
2065 release_icon_frame( ptr, frame );
2069 release_user_handle_ptr( ptr );
2071 return ret;
2074 /**********************************************************************
2075 * GetIconInfo (USER32.@)
2077 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
2079 ICONINFOEXW infoW;
2081 infoW.cbSize = sizeof(infoW);
2082 if (!GetIconInfoExW( hIcon, &infoW )) return FALSE;
2083 iconinfo->fIcon = infoW.fIcon;
2084 iconinfo->xHotspot = infoW.xHotspot;
2085 iconinfo->yHotspot = infoW.yHotspot;
2086 iconinfo->hbmColor = infoW.hbmColor;
2087 iconinfo->hbmMask = infoW.hbmMask;
2088 return TRUE;
2091 /**********************************************************************
2092 * GetIconInfoExA (USER32.@)
2094 BOOL WINAPI GetIconInfoExA( HICON icon, ICONINFOEXA *info )
2096 ICONINFOEXW infoW;
2098 if (info->cbSize != sizeof(*info))
2100 SetLastError( ERROR_INVALID_PARAMETER );
2101 return FALSE;
2103 infoW.cbSize = sizeof(infoW);
2104 if (!GetIconInfoExW( icon, &infoW )) return FALSE;
2105 info->fIcon = infoW.fIcon;
2106 info->xHotspot = infoW.xHotspot;
2107 info->yHotspot = infoW.yHotspot;
2108 info->hbmColor = infoW.hbmColor;
2109 info->hbmMask = infoW.hbmMask;
2110 info->wResID = infoW.wResID;
2111 WideCharToMultiByte( CP_ACP, 0, infoW.szModName, -1, info->szModName, MAX_PATH, NULL, NULL );
2112 WideCharToMultiByte( CP_ACP, 0, infoW.szResName, -1, info->szResName, MAX_PATH, NULL, NULL );
2113 return TRUE;
2116 /**********************************************************************
2117 * GetIconInfoExW (USER32.@)
2119 BOOL WINAPI GetIconInfoExW( HICON icon, ICONINFOEXW *info )
2121 struct cursoricon_frame *frame;
2122 struct cursoricon_object *ptr;
2123 HMODULE module;
2124 BOOL ret = TRUE;
2126 if (info->cbSize != sizeof(*info))
2128 SetLastError( ERROR_INVALID_PARAMETER );
2129 return FALSE;
2131 if (!(ptr = get_icon_ptr( icon )))
2133 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
2134 return FALSE;
2137 frame = get_icon_frame( ptr, 0 );
2138 if (!frame)
2140 release_user_handle_ptr( ptr );
2141 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
2142 return FALSE;
2145 TRACE("%p => %dx%d\n", icon, frame->width, frame->height);
2147 info->fIcon = ptr->is_icon;
2148 info->xHotspot = ptr->hotspot.x;
2149 info->yHotspot = ptr->hotspot.y;
2150 info->hbmColor = copy_bitmap( frame->color );
2151 info->hbmMask = copy_bitmap( frame->mask );
2152 info->wResID = 0;
2153 info->szModName[0] = 0;
2154 info->szResName[0] = 0;
2155 if (ptr->module)
2157 if (IS_INTRESOURCE( ptr->resname )) info->wResID = LOWORD( ptr->resname );
2158 else lstrcpynW( info->szResName, ptr->resname, MAX_PATH );
2160 if (!info->hbmMask || (!info->hbmColor && frame->color))
2162 DeleteObject( info->hbmMask );
2163 DeleteObject( info->hbmColor );
2164 ret = FALSE;
2166 module = ptr->module;
2167 release_icon_frame( ptr, frame );
2168 release_user_handle_ptr( ptr );
2169 if (ret && module) GetModuleFileNameW( module, info->szModName, MAX_PATH );
2170 return ret;
2173 /* copy an icon bitmap, even when it can't be selected into a DC */
2174 /* helper for CreateIconIndirect */
2175 static void stretch_blt_icon( HDC hdc_dst, int dst_x, int dst_y, int dst_width, int dst_height,
2176 HBITMAP src, int width, int height )
2178 HDC hdc = CreateCompatibleDC( 0 );
2180 if (!SelectObject( hdc, src )) /* do it the hard way */
2182 BITMAPINFO *info;
2183 void *bits;
2185 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) return;
2186 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2187 info->bmiHeader.biWidth = width;
2188 info->bmiHeader.biHeight = height;
2189 info->bmiHeader.biPlanes = GetDeviceCaps( hdc_dst, PLANES );
2190 info->bmiHeader.biBitCount = GetDeviceCaps( hdc_dst, BITSPIXEL );
2191 info->bmiHeader.biCompression = BI_RGB;
2192 info->bmiHeader.biSizeImage = get_dib_image_size( width, height, info->bmiHeader.biBitCount );
2193 info->bmiHeader.biXPelsPerMeter = 0;
2194 info->bmiHeader.biYPelsPerMeter = 0;
2195 info->bmiHeader.biClrUsed = 0;
2196 info->bmiHeader.biClrImportant = 0;
2197 bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
2198 if (bits && GetDIBits( hdc, src, 0, height, bits, info, DIB_RGB_COLORS ))
2199 StretchDIBits( hdc_dst, dst_x, dst_y, dst_width, dst_height,
2200 0, 0, width, height, bits, info, DIB_RGB_COLORS, SRCCOPY );
2202 HeapFree( GetProcessHeap(), 0, bits );
2203 HeapFree( GetProcessHeap(), 0, info );
2205 else StretchBlt( hdc_dst, dst_x, dst_y, dst_width, dst_height, hdc, 0, 0, width, height, SRCCOPY );
2207 DeleteDC( hdc );
2210 /**********************************************************************
2211 * CreateIconIndirect (USER32.@)
2213 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
2215 BITMAP bmpXor, bmpAnd;
2216 HICON hObj;
2217 HBITMAP color = 0, mask;
2218 int width, height;
2219 HDC hdc;
2221 TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
2222 iconinfo->hbmColor, iconinfo->hbmMask,
2223 iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
2225 if (!iconinfo->hbmMask) return 0;
2227 GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
2228 TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2229 bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
2230 bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
2232 if (iconinfo->hbmColor)
2234 GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2235 TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2236 bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
2237 bmpXor.bmPlanes, bmpXor.bmBitsPixel);
2239 width = bmpXor.bmWidth;
2240 height = bmpXor.bmHeight;
2241 color = create_color_bitmap( width, height );
2243 else
2245 width = bmpAnd.bmWidth;
2246 height = bmpAnd.bmHeight;
2248 mask = CreateBitmap( width, height, 1, 1, NULL );
2250 hdc = CreateCompatibleDC( 0 );
2251 SelectObject( hdc, mask );
2252 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
2254 if (color)
2256 SelectObject( hdc, color );
2257 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
2259 else height /= 2;
2261 DeleteDC( hdc );
2263 hObj = alloc_icon_handle( FALSE, 0 );
2264 if (hObj)
2266 struct cursoricon_object *info = get_icon_ptr( hObj );
2267 struct cursoricon_frame *frame;
2269 info->is_icon = iconinfo->fIcon;
2270 frame = get_icon_frame( info, 0 );
2271 frame->delay = ~0;
2272 frame->width = width;
2273 frame->height = height;
2274 frame->color = color;
2275 frame->mask = mask;
2276 frame->alpha = create_alpha_bitmap( iconinfo->hbmColor, NULL, NULL );
2277 release_icon_frame( info, frame );
2278 if (info->is_icon)
2280 info->hotspot.x = width / 2;
2281 info->hotspot.y = height / 2;
2283 else
2285 info->hotspot.x = iconinfo->xHotspot;
2286 info->hotspot.y = iconinfo->yHotspot;
2289 release_user_handle_ptr( info );
2291 return hObj;
2294 /******************************************************************************
2295 * DrawIconEx (USER32.@) Draws an icon or cursor on device context
2297 * NOTES
2298 * Why is this using SM_CXICON instead of SM_CXCURSOR?
2300 * PARAMS
2301 * hdc [I] Handle to device context
2302 * x0 [I] X coordinate of upper left corner
2303 * y0 [I] Y coordinate of upper left corner
2304 * hIcon [I] Handle to icon to draw
2305 * cxWidth [I] Width of icon
2306 * cyWidth [I] Height of icon
2307 * istep [I] Index of frame in animated cursor
2308 * hbr [I] Handle to background brush
2309 * flags [I] Icon-drawing flags
2311 * RETURNS
2312 * Success: TRUE
2313 * Failure: FALSE
2315 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2316 INT cxWidth, INT cyWidth, UINT istep,
2317 HBRUSH hbr, UINT flags )
2319 struct cursoricon_frame *frame;
2320 struct cursoricon_object *ptr;
2321 HDC hdc_dest, hMemDC;
2322 BOOL result = FALSE, DoOffscreen;
2323 HBITMAP hB_off = 0;
2324 COLORREF oldFg, oldBg;
2325 INT x, y, nStretchMode;
2327 TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2328 hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2330 if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2331 if (istep >= get_icon_steps( ptr ))
2333 TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
2334 release_user_handle_ptr( ptr );
2335 return FALSE;
2337 if (!(frame = get_icon_frame( ptr, istep )))
2339 FIXME_(icon)("Error retrieving icon frame %d\n", istep);
2340 release_user_handle_ptr( ptr );
2341 return FALSE;
2343 if (!(hMemDC = CreateCompatibleDC( hdc )))
2345 release_icon_frame( ptr, frame );
2346 release_user_handle_ptr( ptr );
2347 return FALSE;
2350 if (flags & DI_NOMIRROR)
2351 FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
2353 /* Calculate the size of the destination image. */
2354 if (cxWidth == 0)
2356 if (flags & DI_DEFAULTSIZE)
2357 cxWidth = GetSystemMetrics (SM_CXICON);
2358 else
2359 cxWidth = frame->width;
2361 if (cyWidth == 0)
2363 if (flags & DI_DEFAULTSIZE)
2364 cyWidth = GetSystemMetrics (SM_CYICON);
2365 else
2366 cyWidth = frame->height;
2369 DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2371 if (DoOffscreen) {
2372 RECT r;
2374 SetRect(&r, 0, 0, cxWidth, cxWidth);
2376 if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
2377 if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
2379 DeleteDC( hdc_dest );
2380 goto failed;
2382 SelectObject(hdc_dest, hB_off);
2383 FillRect(hdc_dest, &r, hbr);
2384 x = y = 0;
2386 else
2388 hdc_dest = hdc;
2389 x = x0;
2390 y = y0;
2393 nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2395 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2396 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2398 if (frame->alpha && (flags & DI_IMAGE))
2400 BOOL alpha_blend = TRUE;
2402 if (GetObjectType( hdc_dest ) == OBJ_MEMDC)
2404 BITMAP bm;
2405 HBITMAP bmp = GetCurrentObject( hdc_dest, OBJ_BITMAP );
2406 alpha_blend = GetObjectW( bmp, sizeof(bm), &bm ) && bm.bmBitsPixel > 8;
2408 if (alpha_blend)
2410 BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2411 SelectObject( hMemDC, frame->alpha );
2412 if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
2413 0, 0, frame->width, frame->height,
2414 pixelblend )) goto done;
2418 if (flags & DI_MASK)
2420 DWORD rop = (flags & DI_IMAGE) ? SRCAND : SRCCOPY;
2421 SelectObject( hMemDC, frame->mask );
2422 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2423 hMemDC, 0, 0, frame->width, frame->height, rop );
2426 if (flags & DI_IMAGE)
2428 if (frame->color)
2430 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2431 SelectObject( hMemDC, frame->color );
2432 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2433 hMemDC, 0, 0, frame->width, frame->height, rop );
2435 else
2437 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2438 SelectObject( hMemDC, frame->mask );
2439 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2440 hMemDC, 0, frame->height, frame->width,
2441 frame->height, rop );
2445 done:
2446 if (DoOffscreen) BitBlt( hdc, x0, y0, cxWidth, cyWidth, hdc_dest, 0, 0, SRCCOPY );
2448 SetTextColor( hdc, oldFg );
2449 SetBkColor( hdc, oldBg );
2450 SetStretchBltMode (hdc, nStretchMode);
2451 result = TRUE;
2452 if (hdc_dest != hdc) DeleteDC( hdc_dest );
2453 if (hB_off) DeleteObject(hB_off);
2454 failed:
2455 DeleteDC( hMemDC );
2456 release_icon_frame( ptr, frame );
2457 release_user_handle_ptr( ptr );
2458 return result;
2461 /***********************************************************************
2462 * DIB_FixColorsToLoadflags
2464 * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2465 * are in loadflags
2467 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2469 int colors;
2470 COLORREF c_W, c_S, c_F, c_L, c_C;
2471 int incr,i;
2472 RGBQUAD *ptr;
2473 int bitmap_type;
2474 LONG width;
2475 LONG height;
2476 WORD bpp;
2477 DWORD compr;
2479 if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2481 WARN_(resource)("Invalid bitmap\n");
2482 return;
2485 if (bpp > 8) return;
2487 if (bitmap_type == 0) /* BITMAPCOREHEADER */
2489 incr = 3;
2490 colors = 1 << bpp;
2492 else
2494 incr = 4;
2495 colors = bmi->bmiHeader.biClrUsed;
2496 if (colors > 256) colors = 256;
2497 if (!colors && (bpp <= 8)) colors = 1 << bpp;
2500 c_W = GetSysColor(COLOR_WINDOW);
2501 c_S = GetSysColor(COLOR_3DSHADOW);
2502 c_F = GetSysColor(COLOR_3DFACE);
2503 c_L = GetSysColor(COLOR_3DLIGHT);
2505 if (loadflags & LR_LOADTRANSPARENT) {
2506 switch (bpp) {
2507 case 1: pix = pix >> 7; break;
2508 case 4: pix = pix >> 4; break;
2509 case 8: break;
2510 default:
2511 WARN_(resource)("(%d): Unsupported depth\n", bpp);
2512 return;
2514 if (pix >= colors) {
2515 WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2516 return;
2518 if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2519 ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2520 ptr->rgbBlue = GetBValue(c_W);
2521 ptr->rgbGreen = GetGValue(c_W);
2522 ptr->rgbRed = GetRValue(c_W);
2524 if (loadflags & LR_LOADMAP3DCOLORS)
2525 for (i=0; i<colors; i++) {
2526 ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2527 c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2528 if (c_C == RGB(128, 128, 128)) {
2529 ptr->rgbRed = GetRValue(c_S);
2530 ptr->rgbGreen = GetGValue(c_S);
2531 ptr->rgbBlue = GetBValue(c_S);
2532 } else if (c_C == RGB(192, 192, 192)) {
2533 ptr->rgbRed = GetRValue(c_F);
2534 ptr->rgbGreen = GetGValue(c_F);
2535 ptr->rgbBlue = GetBValue(c_F);
2536 } else if (c_C == RGB(223, 223, 223)) {
2537 ptr->rgbRed = GetRValue(c_L);
2538 ptr->rgbGreen = GetGValue(c_L);
2539 ptr->rgbBlue = GetBValue(c_L);
2545 /**********************************************************************
2546 * BITMAP_Load
2548 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2549 INT desiredx, INT desiredy, UINT loadflags )
2551 HBITMAP hbitmap = 0, orig_bm;
2552 HRSRC hRsrc;
2553 HGLOBAL handle;
2554 const char *ptr = NULL;
2555 BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2556 int size;
2557 BYTE pix;
2558 char *bits;
2559 LONG width, height, new_width, new_height;
2560 WORD bpp_dummy;
2561 DWORD compr_dummy, offbits = 0;
2562 INT bm_type;
2563 HDC screen_mem_dc = NULL;
2565 if (!(loadflags & LR_LOADFROMFILE))
2567 if (!instance)
2569 /* OEM bitmap: try to load the resource from user32.dll */
2570 instance = user32_module;
2573 if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2574 if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2576 if ((info = LockResource( handle )) == NULL) return 0;
2578 else
2580 BITMAPFILEHEADER * bmfh;
2582 if (!(ptr = map_fileW( name, NULL ))) return 0;
2583 info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2584 bmfh = (BITMAPFILEHEADER *)ptr;
2585 if (bmfh->bfType != 0x4d42 /* 'BM' */)
2587 WARN("Invalid/unsupported bitmap format!\n");
2588 goto end;
2590 if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2593 bm_type = DIB_GetBitmapInfo( &info->bmiHeader, &width, &height,
2594 &bpp_dummy, &compr_dummy);
2595 if (bm_type == -1)
2597 WARN("Invalid bitmap format!\n");
2598 goto end;
2601 size = bitmap_info_size(info, DIB_RGB_COLORS);
2602 fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2603 scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2605 if (!fix_info || !scaled_info) goto end;
2606 memcpy(fix_info, info, size);
2608 pix = *((LPBYTE)info + size);
2609 DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2611 memcpy(scaled_info, fix_info, size);
2613 if(desiredx != 0)
2614 new_width = desiredx;
2615 else
2616 new_width = width;
2618 if(desiredy != 0)
2619 new_height = height > 0 ? desiredy : -desiredy;
2620 else
2621 new_height = height;
2623 if(bm_type == 0)
2625 BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2626 core->bcWidth = new_width;
2627 core->bcHeight = new_height;
2629 else
2631 /* Some sanity checks for BITMAPINFO (not applicable to BITMAPCOREINFO) */
2632 if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
2633 WARN("Broken BitmapInfoHeader!\n");
2634 goto end;
2637 scaled_info->bmiHeader.biWidth = new_width;
2638 scaled_info->bmiHeader.biHeight = new_height;
2641 if (new_height < 0) new_height = -new_height;
2643 if (!(screen_mem_dc = CreateCompatibleDC( 0 ))) goto end;
2645 bits = (char *)info + (offbits ? offbits : size);
2647 if (loadflags & LR_CREATEDIBSECTION)
2649 scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2650 hbitmap = CreateDIBSection(0, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2652 else
2654 if (is_dib_monochrome(fix_info))
2655 hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2656 else
2657 hbitmap = create_color_bitmap(new_width, new_height);
2660 orig_bm = SelectObject(screen_mem_dc, hbitmap);
2661 if (info->bmiHeader.biBitCount > 1)
2662 SetStretchBltMode(screen_mem_dc, HALFTONE);
2663 StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2664 SelectObject(screen_mem_dc, orig_bm);
2666 end:
2667 if (screen_mem_dc) DeleteDC(screen_mem_dc);
2668 HeapFree(GetProcessHeap(), 0, scaled_info);
2669 HeapFree(GetProcessHeap(), 0, fix_info);
2670 if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2672 return hbitmap;
2675 /**********************************************************************
2676 * LoadImageA (USER32.@)
2678 * See LoadImageW.
2680 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2681 INT desiredx, INT desiredy, UINT loadflags)
2683 HANDLE res;
2684 LPWSTR u_name;
2686 if (IS_INTRESOURCE(name))
2687 return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2689 __TRY {
2690 DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2691 u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2692 MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2694 __EXCEPT_PAGE_FAULT {
2695 SetLastError( ERROR_INVALID_PARAMETER );
2696 return 0;
2698 __ENDTRY
2699 res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2700 HeapFree(GetProcessHeap(), 0, u_name);
2701 return res;
2705 /******************************************************************************
2706 * LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2708 * PARAMS
2709 * hinst [I] Handle of instance that contains image
2710 * name [I] Name of image
2711 * type [I] Type of image
2712 * desiredx [I] Desired width
2713 * desiredy [I] Desired height
2714 * loadflags [I] Load flags
2716 * RETURNS
2717 * Success: Handle to newly loaded image
2718 * Failure: NULL
2720 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2722 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2723 INT desiredx, INT desiredy, UINT loadflags )
2725 int depth;
2726 WCHAR path[MAX_PATH];
2728 TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
2729 hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
2731 if (loadflags & LR_LOADFROMFILE)
2733 loadflags &= ~LR_SHARED;
2734 /* relative paths are not only relative to the current working directory */
2735 if (SearchPathW(NULL, name, NULL, ARRAY_SIZE(path), path, NULL)) name = path;
2737 switch (type) {
2738 case IMAGE_BITMAP:
2739 return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2741 case IMAGE_ICON:
2742 case IMAGE_CURSOR:
2743 depth = 1;
2744 if (!(loadflags & LR_MONOCHROME)) depth = get_display_bpp();
2745 return CURSORICON_Load(hinst, name, desiredx, desiredy, depth, (type == IMAGE_CURSOR), loadflags);
2747 return 0;
2751 /* StretchBlt from src to dest; helper for CopyImage(). */
2752 static void stretch_bitmap( HBITMAP dst, HBITMAP src, int dst_width, int dst_height, int src_width, int src_height )
2754 HDC src_dc = CreateCompatibleDC( 0 ), dst_dc = CreateCompatibleDC( 0 );
2756 SelectObject( src_dc, src );
2757 SelectObject( dst_dc, dst );
2758 StretchBlt( dst_dc, 0, 0, dst_width, dst_height, src_dc, 0, 0, src_width, src_height, SRCCOPY );
2760 DeleteDC( src_dc );
2761 DeleteDC( dst_dc );
2765 /******************************************************************************
2766 * CopyImage (USER32.@) Creates new image and copies attributes to it
2768 * PARAMS
2769 * hnd [I] Handle to image to copy
2770 * type [I] Type of image to copy
2771 * desiredx [I] Desired width of new image
2772 * desiredy [I] Desired height of new image
2773 * flags [I] Copy flags
2775 * RETURNS
2776 * Success: Handle to newly created image
2777 * Failure: NULL
2779 * BUGS
2780 * Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
2781 * all other versions (95/2000/XP have been tested) ignore it.
2783 * NOTES
2784 * If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
2785 * a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
2786 * the copy will have the same depth as the screen.
2787 * The content of the image will only be copied if the bit depth of the
2788 * original image is compatible with the bit depth of the screen, or
2789 * if the source is a DIB section.
2790 * The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
2792 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2793 INT desiredy, UINT flags )
2795 TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
2796 hnd, type, desiredx, desiredy, flags);
2798 switch (type)
2800 case IMAGE_BITMAP:
2802 HBITMAP res = NULL;
2803 DIBSECTION ds;
2804 int objSize;
2805 BITMAPINFO * bi;
2807 objSize = GetObjectW( hnd, sizeof(ds), &ds );
2808 if (!objSize) return 0;
2809 if ((desiredx < 0) || (desiredy < 0)) return 0;
2811 if (flags & LR_COPYFROMRESOURCE)
2813 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
2816 if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
2817 if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
2819 /* Allocate memory for a BITMAPINFOHEADER structure and a
2820 color table. The maximum number of colors in a color table
2821 is 256 which corresponds to a bitmap with depth 8.
2822 Bitmaps with higher depths don't have color tables. */
2823 bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
2824 if (!bi) return 0;
2826 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
2827 bi->bmiHeader.biPlanes = ds.dsBm.bmPlanes;
2828 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
2829 bi->bmiHeader.biCompression = BI_RGB;
2831 if (flags & LR_CREATEDIBSECTION)
2833 /* Create a DIB section. LR_MONOCHROME is ignored */
2834 void * bits;
2835 HDC dc = CreateCompatibleDC(NULL);
2837 if (objSize == sizeof(DIBSECTION))
2839 /* The source bitmap is a DIB.
2840 Get its attributes to create an exact copy */
2841 memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
2844 bi->bmiHeader.biWidth = desiredx;
2845 bi->bmiHeader.biHeight = desiredy;
2847 /* Get the color table or the color masks */
2848 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2850 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
2851 DeleteDC(dc);
2853 else
2855 /* Create a device-dependent bitmap */
2857 BOOL monochrome = (flags & LR_MONOCHROME);
2859 if (objSize == sizeof(DIBSECTION))
2861 /* The source bitmap is a DIB section.
2862 Get its attributes */
2863 HDC dc = CreateCompatibleDC(NULL);
2864 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
2865 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
2866 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2867 DeleteDC(dc);
2869 if (!monochrome && ds.dsBm.bmBitsPixel == 1)
2871 /* Look if the colors of the DIB are black and white */
2873 monochrome =
2874 (bi->bmiColors[0].rgbRed == 0xff
2875 && bi->bmiColors[0].rgbGreen == 0xff
2876 && bi->bmiColors[0].rgbBlue == 0xff
2877 && bi->bmiColors[0].rgbReserved == 0
2878 && bi->bmiColors[1].rgbRed == 0
2879 && bi->bmiColors[1].rgbGreen == 0
2880 && bi->bmiColors[1].rgbBlue == 0
2881 && bi->bmiColors[1].rgbReserved == 0)
2883 (bi->bmiColors[0].rgbRed == 0
2884 && bi->bmiColors[0].rgbGreen == 0
2885 && bi->bmiColors[0].rgbBlue == 0
2886 && bi->bmiColors[0].rgbReserved == 0
2887 && bi->bmiColors[1].rgbRed == 0xff
2888 && bi->bmiColors[1].rgbGreen == 0xff
2889 && bi->bmiColors[1].rgbBlue == 0xff
2890 && bi->bmiColors[1].rgbReserved == 0);
2893 else if (!monochrome)
2895 monochrome = ds.dsBm.bmBitsPixel == 1;
2898 if (monochrome)
2899 res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
2900 else
2901 res = create_color_bitmap(desiredx, desiredy);
2904 if (res)
2906 /* Only copy the bitmap if it's a DIB section or if it's
2907 compatible to the screen */
2908 if (objSize == sizeof(DIBSECTION) ||
2909 ds.dsBm.bmBitsPixel == 1 ||
2910 ds.dsBm.bmBitsPixel == get_display_bpp())
2912 /* The source bitmap may already be selected in a device context,
2913 use GetDIBits/StretchDIBits and not StretchBlt */
2915 HDC dc;
2916 void * bits;
2918 dc = CreateCompatibleDC(NULL);
2919 if (ds.dsBm.bmBitsPixel > 1)
2920 SetStretchBltMode(dc, HALFTONE);
2922 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
2923 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
2924 bi->bmiHeader.biSizeImage = 0;
2925 bi->bmiHeader.biClrUsed = 0;
2926 bi->bmiHeader.biClrImportant = 0;
2928 /* Fill in biSizeImage */
2929 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2930 bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
2932 if (bits)
2934 HBITMAP oldBmp;
2936 /* Get the image bits of the source bitmap */
2937 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
2939 /* Copy it to the destination bitmap */
2940 oldBmp = SelectObject(dc, res);
2941 StretchDIBits(dc, 0, 0, desiredx, desiredy,
2942 0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
2943 bits, bi, DIB_RGB_COLORS, SRCCOPY);
2944 SelectObject(dc, oldBmp);
2946 HeapFree(GetProcessHeap(), 0, bits);
2949 DeleteDC(dc);
2952 if (flags & LR_COPYDELETEORG)
2954 DeleteObject(hnd);
2957 HeapFree(GetProcessHeap(), 0, bi);
2958 return res;
2960 case IMAGE_ICON:
2961 case IMAGE_CURSOR:
2963 struct cursoricon_frame *frame;
2964 struct cursoricon_object *icon;
2965 int depth = (flags & LR_MONOCHROME) ? 1 : get_display_bpp();
2966 ICONINFO info;
2967 HICON res;
2969 if (!(icon = get_icon_ptr( hnd ))) return 0;
2971 if (icon->rsrc && (flags & LR_COPYFROMRESOURCE))
2973 hnd = CURSORICON_Load( icon->module, icon->resname, desiredx, desiredy, depth,
2974 !icon->is_icon, flags );
2975 release_user_handle_ptr( icon );
2976 if (!(icon = get_icon_ptr( hnd ))) return 0;
2978 frame = get_icon_frame( icon, 0 );
2980 if (flags & LR_DEFAULTSIZE)
2982 if (!desiredx) desiredx = GetSystemMetrics( type == IMAGE_ICON ? SM_CXICON : SM_CXCURSOR );
2983 if (!desiredy) desiredy = GetSystemMetrics( type == IMAGE_ICON ? SM_CYICON : SM_CYCURSOR );
2985 else
2987 if (!desiredx) desiredx = frame->width;
2988 if (!desiredy) desiredy = frame->height;
2991 info.fIcon = icon->is_icon;
2992 info.xHotspot = icon->hotspot.x;
2993 info.yHotspot = icon->hotspot.y;
2995 if (desiredx == frame->width && desiredy == frame->height)
2997 info.hbmColor = frame->color;
2998 info.hbmMask = frame->mask;
2999 res = CreateIconIndirect( &info );
3001 else
3003 if (frame->color)
3005 if (!(info.hbmColor = create_color_bitmap( desiredx, desiredy )))
3007 release_icon_frame( icon, frame );
3008 release_user_handle_ptr( icon );
3009 return 0;
3011 stretch_bitmap( info.hbmColor, frame->color, desiredx, desiredy,
3012 frame->width, frame->height );
3014 if (!(info.hbmMask = CreateBitmap( desiredx, desiredy, 1, 1, NULL )))
3016 DeleteObject( info.hbmColor );
3017 release_icon_frame( icon, frame );
3018 release_user_handle_ptr( icon );
3019 return 0;
3021 stretch_bitmap( info.hbmMask, frame->mask, desiredx, desiredy,
3022 frame->width, frame->height );
3024 else
3026 info.hbmColor = NULL;
3028 if (!(info.hbmMask = CreateBitmap( desiredx, desiredy * 2, 1, 1, NULL )))
3030 release_user_handle_ptr( icon );
3031 return 0;
3033 stretch_bitmap( info.hbmMask, frame->mask, desiredx, desiredy * 2,
3034 frame->width, frame->height * 2 );
3037 res = CreateIconIndirect( &info );
3039 DeleteObject( info.hbmColor );
3040 DeleteObject( info.hbmMask );
3043 release_icon_frame( icon, frame );
3044 release_user_handle_ptr( icon );
3046 if (res && (flags & LR_COPYDELETEORG)) DeleteObject( hnd );
3047 return res;
3050 return 0;
3054 /******************************************************************************
3055 * LoadBitmapW (USER32.@) Loads bitmap from the executable file
3057 * RETURNS
3058 * Success: Handle to specified bitmap
3059 * Failure: NULL
3061 HBITMAP WINAPI LoadBitmapW(
3062 HINSTANCE instance, /* [in] Handle to application instance */
3063 LPCWSTR name) /* [in] Address of bitmap resource name */
3065 return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
3068 /**********************************************************************
3069 * LoadBitmapA (USER32.@)
3071 * See LoadBitmapW.
3073 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
3075 return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );