user32: Select more appropriate stretch mode for colored images interpolation.
[wine.git] / dlls / user32 / cursoricon.c
blob3214746664c24626e94155641c71b4fcd9f918f6
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 "config.h"
28 #include "wine/port.h"
30 #include <assert.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #ifdef HAVE_PNG_H
35 #include <png.h>
36 #endif
38 #include "windef.h"
39 #include "winbase.h"
40 #include "wingdi.h"
41 #include "winerror.h"
42 #include "winnls.h"
43 #include "wine/exception.h"
44 #include "wine/server.h"
45 #include "controls.h"
46 #include "win.h"
47 #include "user_private.h"
48 #include "wine/list.h"
49 #include "wine/unicode.h"
50 #include "wine/debug.h"
51 #include "wine/library.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
54 WINE_DECLARE_DEBUG_CHANNEL(icon);
55 WINE_DECLARE_DEBUG_CHANNEL(resource);
57 #define RIFF_FOURCC( c0, c1, c2, c3 ) \
58 ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
59 ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
60 #define PNG_SIGN RIFF_FOURCC(0x89,'P','N','G')
62 static struct list icon_cache = LIST_INIT( icon_cache );
64 /**********************************************************************
65 * User objects management
68 struct cursoricon_frame
70 UINT width; /* frame-specific width */
71 UINT height; /* frame-specific height */
72 UINT delay; /* frame-specific delay between this frame and the next (in jiffies) */
73 HBITMAP color; /* color bitmap */
74 HBITMAP alpha; /* pre-multiplied alpha bitmap for 32-bpp icons */
75 HBITMAP mask; /* mask bitmap (followed by color for 1-bpp icons) */
78 struct cursoricon_object
80 struct user_object obj; /* object header */
81 struct list entry; /* entry in shared icons list */
82 ULONG_PTR param; /* opaque param used by 16-bit code */
83 HMODULE module; /* module for icons loaded from resources */
84 LPWSTR resname; /* resource name for icons loaded from resources */
85 HRSRC rsrc; /* resource for shared icons */
86 BOOL is_icon; /* whether icon or cursor */
87 BOOL is_ani; /* whether this object is a static cursor or an animated cursor */
88 UINT delay; /* delay between this frame and the next (in jiffies) */
89 POINT hotspot;
92 struct static_cursoricon_object
94 struct cursoricon_object shared;
95 struct cursoricon_frame frame; /* frame-specific icon data */
98 struct animated_cursoricon_object
100 struct cursoricon_object shared;
101 UINT num_frames; /* number of frames in the icon/cursor */
102 UINT num_steps; /* number of sequence steps in the icon/cursor */
103 HICON frames[1]; /* list of animated cursor frames */
106 static HBITMAP create_color_bitmap( int width, int height )
108 HDC hdc = get_display_dc();
109 HBITMAP ret = CreateCompatibleBitmap( hdc, width, height );
110 release_display_dc( hdc );
111 return ret;
114 static int get_display_bpp(void)
116 HDC hdc = get_display_dc();
117 int ret = GetDeviceCaps( hdc, BITSPIXEL );
118 release_display_dc( hdc );
119 return ret;
122 #ifdef SONAME_LIBPNG
124 static void *libpng_handle;
125 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
126 MAKE_FUNCPTR(png_create_read_struct);
127 MAKE_FUNCPTR(png_create_info_struct);
128 MAKE_FUNCPTR(png_destroy_read_struct);
129 MAKE_FUNCPTR(png_error);
130 MAKE_FUNCPTR(png_get_bit_depth);
131 MAKE_FUNCPTR(png_get_color_type);
132 MAKE_FUNCPTR(png_get_error_ptr);
133 MAKE_FUNCPTR(png_get_image_height);
134 MAKE_FUNCPTR(png_get_image_width);
135 MAKE_FUNCPTR(png_get_io_ptr);
136 MAKE_FUNCPTR(png_read_image);
137 MAKE_FUNCPTR(png_read_info);
138 MAKE_FUNCPTR(png_read_update_info);
139 MAKE_FUNCPTR(png_set_bgr);
140 MAKE_FUNCPTR(png_set_crc_action);
141 MAKE_FUNCPTR(png_set_error_fn);
142 MAKE_FUNCPTR(png_set_expand);
143 MAKE_FUNCPTR(png_set_gray_to_rgb);
144 MAKE_FUNCPTR(png_set_read_fn);
145 #undef MAKE_FUNCPTR
147 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
149 static BOOL WINAPI load_libpng( INIT_ONCE *once, void *param, void **context )
151 if (!(libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)))
153 WARN( "failed to load %s\n", SONAME_LIBPNG );
154 return TRUE;
156 #define LOAD_FUNCPTR(f) \
157 if ((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) \
159 WARN( "%s not found in %s\n", #f, SONAME_LIBPNG ); \
160 libpng_handle = NULL; \
161 return TRUE; \
163 LOAD_FUNCPTR(png_create_read_struct);
164 LOAD_FUNCPTR(png_create_info_struct);
165 LOAD_FUNCPTR(png_destroy_read_struct);
166 LOAD_FUNCPTR(png_error);
167 LOAD_FUNCPTR(png_get_bit_depth);
168 LOAD_FUNCPTR(png_get_color_type);
169 LOAD_FUNCPTR(png_get_error_ptr);
170 LOAD_FUNCPTR(png_get_image_height);
171 LOAD_FUNCPTR(png_get_image_width);
172 LOAD_FUNCPTR(png_get_io_ptr);
173 LOAD_FUNCPTR(png_read_image);
174 LOAD_FUNCPTR(png_read_info);
175 LOAD_FUNCPTR(png_read_update_info);
176 LOAD_FUNCPTR(png_set_bgr);
177 LOAD_FUNCPTR(png_set_crc_action);
178 LOAD_FUNCPTR(png_set_error_fn);
179 LOAD_FUNCPTR(png_set_expand);
180 LOAD_FUNCPTR(png_set_gray_to_rgb);
181 LOAD_FUNCPTR(png_set_read_fn);
182 #undef LOAD_FUNCPTR
183 return TRUE;
186 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
188 jmp_buf *pjmpbuf;
190 /* This uses setjmp/longjmp just like the default. We can't use the
191 * default because there's no way to access the jmp buffer in the png_struct
192 * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
193 WARN("PNG error: %s\n", debugstr_a(error_message));
194 pjmpbuf = ppng_get_error_ptr(png_ptr);
195 longjmp(*pjmpbuf, 1);
198 static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
200 WARN("PNG warning: %s\n", debugstr_a(warning_message));
203 struct png_wrapper
205 const char *buffer;
206 size_t size, pos;
209 static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
211 struct png_wrapper *png = ppng_get_io_ptr(png_ptr);
213 if (png->size - png->pos >= length)
215 memcpy(data, png->buffer + png->pos, length);
216 png->pos += length;
218 else
220 ppng_error(png_ptr, "failed to read PNG data");
224 static unsigned be_uint(unsigned val)
226 union
228 unsigned val;
229 unsigned char c[4];
230 } u;
232 u.val = val;
233 return (u.c[0] << 24) | (u.c[1] << 16) | (u.c[2] << 8) | u.c[3];
236 static BOOL have_libpng(void)
238 return InitOnceExecuteOnce( &init_once, load_libpng, NULL, NULL ) && libpng_handle;
241 static BOOL get_png_info(const void *png_data, DWORD size, int *width, int *height, int *bpp)
243 static const char png_sig[8] = { 0x89,'P','N','G',0x0d,0x0a,0x1a,0x0a };
244 static const char png_IHDR[8] = { 0,0,0,0x0d,'I','H','D','R' };
245 const struct
247 char png_sig[8];
248 char ihdr_sig[8];
249 unsigned width, height;
250 char bit_depth, color_type, compression, filter, interlace;
251 } *png = png_data;
253 if (size < sizeof(*png)) return FALSE;
254 if (memcmp(png->png_sig, png_sig, sizeof(png_sig)) != 0) return FALSE;
255 if (memcmp(png->ihdr_sig, png_IHDR, sizeof(png_IHDR)) != 0) return FALSE;
257 *bpp = (png->color_type == PNG_COLOR_TYPE_RGB_ALPHA) ? 32 : 24;
258 *width = be_uint(png->width);
259 *height = be_uint(png->height);
261 return TRUE;
264 static BITMAPINFO *load_png(const char *png_data, DWORD *size)
266 struct png_wrapper png;
267 png_structp png_ptr;
268 png_infop info_ptr;
269 png_bytep *row_pointers = NULL;
270 jmp_buf jmpbuf;
271 int color_type, bit_depth, bpp, width, height;
272 int rowbytes, image_size, mask_size = 0, i;
273 BITMAPINFO *info = NULL;
274 unsigned char *image_data;
276 if (!get_png_info(png_data, *size, &width, &height, &bpp))
277 return NULL;
279 if (!have_libpng()) return NULL;
281 png.buffer = png_data;
282 png.size = *size;
283 png.pos = 0;
285 /* initialize libpng */
286 png_ptr = ppng_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
287 if (!png_ptr) return NULL;
289 info_ptr = ppng_create_info_struct(png_ptr);
290 if (!info_ptr)
292 ppng_destroy_read_struct(&png_ptr, NULL, NULL);
293 return NULL;
296 /* set up setjmp/longjmp error handling */
297 if (setjmp(jmpbuf))
299 HeapFree(GetProcessHeap(), 0, row_pointers);
300 HeapFree(GetProcessHeap(), 0, info);
301 ppng_destroy_read_struct(&png_ptr, &info_ptr, NULL);
302 return NULL;
305 ppng_set_error_fn(png_ptr, jmpbuf, user_error_fn, user_warning_fn);
306 ppng_set_crc_action(png_ptr, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);
308 /* set up custom i/o handling */
309 ppng_set_read_fn(png_ptr, &png, user_read_data);
311 /* read the header */
312 ppng_read_info(png_ptr, info_ptr);
314 color_type = ppng_get_color_type(png_ptr, info_ptr);
315 bit_depth = ppng_get_bit_depth(png_ptr, info_ptr);
317 /* expand grayscale image data to rgb */
318 if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
319 ppng_set_gray_to_rgb(png_ptr);
321 /* expand palette image data to rgb */
322 if (color_type == PNG_COLOR_TYPE_PALETTE || bit_depth < 8)
323 ppng_set_expand(png_ptr);
325 /* update color type information */
326 ppng_read_update_info(png_ptr, info_ptr);
328 color_type = ppng_get_color_type(png_ptr, info_ptr);
329 bit_depth = ppng_get_bit_depth(png_ptr, info_ptr);
331 bpp = 0;
333 switch (color_type)
335 case PNG_COLOR_TYPE_RGB:
336 if (bit_depth == 8)
337 bpp = 24;
338 break;
340 case PNG_COLOR_TYPE_RGB_ALPHA:
341 if (bit_depth == 8)
343 ppng_set_bgr(png_ptr);
344 bpp = 32;
346 break;
348 default:
349 break;
352 if (!bpp)
354 FIXME("unsupported PNG color format %d, %d bpp\n", color_type, bit_depth);
355 ppng_destroy_read_struct(&png_ptr, &info_ptr, NULL);
356 return NULL;
359 width = ppng_get_image_width(png_ptr, info_ptr);
360 height = ppng_get_image_height(png_ptr, info_ptr);
362 rowbytes = (width * bpp + 7) / 8;
363 image_size = height * rowbytes;
364 if (bpp != 32) /* add a mask if there is no alpha */
365 mask_size = (width + 7) / 8 * height;
367 info = HeapAlloc(GetProcessHeap(), 0, sizeof(BITMAPINFOHEADER) + image_size + mask_size);
368 if (!info)
370 ppng_destroy_read_struct(&png_ptr, &info_ptr, NULL);
371 return NULL;
374 image_data = (unsigned char *)info + sizeof(BITMAPINFOHEADER);
375 memset(image_data + image_size, 0, mask_size);
377 row_pointers = HeapAlloc(GetProcessHeap(), 0, height * sizeof(png_bytep));
378 if (!row_pointers)
380 HeapFree(GetProcessHeap(), 0, info);
381 ppng_destroy_read_struct(&png_ptr, &info_ptr, NULL);
382 return NULL;
385 /* upside down */
386 for (i = 0; i < height; i++)
387 row_pointers[i] = image_data + (height - i - 1) * rowbytes;
389 ppng_read_image(png_ptr, row_pointers);
390 HeapFree(GetProcessHeap(), 0, row_pointers);
391 ppng_destroy_read_struct(&png_ptr, &info_ptr, NULL);
393 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
394 info->bmiHeader.biWidth = width;
395 info->bmiHeader.biHeight = height * 2;
396 info->bmiHeader.biPlanes = 1;
397 info->bmiHeader.biBitCount = bpp;
398 info->bmiHeader.biCompression = BI_RGB;
399 info->bmiHeader.biSizeImage = image_size;
400 info->bmiHeader.biXPelsPerMeter = 0;
401 info->bmiHeader.biYPelsPerMeter = 0;
402 info->bmiHeader.biClrUsed = 0;
403 info->bmiHeader.biClrImportant = 0;
405 *size = sizeof(BITMAPINFOHEADER) + image_size + mask_size;
407 return info;
410 #else /* SONAME_LIBPNG */
412 static BOOL have_libpng(void)
414 static int warned;
415 if (!warned++) WARN( "PNG support not compiled in\n" );
416 return FALSE;
419 static BOOL get_png_info(const void *png_data, DWORD size, int *width, int *height, int *bpp)
421 return FALSE;
424 static BITMAPINFO *load_png( const char *png, DWORD *max_size )
426 return NULL;
429 #endif
431 static HICON alloc_icon_handle( BOOL is_ani, UINT num_steps )
433 struct cursoricon_object *obj;
434 int icon_size;
435 HICON handle;
437 if (is_ani)
438 icon_size = FIELD_OFFSET( struct animated_cursoricon_object, frames[num_steps] );
439 else
440 icon_size = sizeof( struct static_cursoricon_object );
441 obj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, icon_size );
442 if (!obj) return NULL;
444 obj->delay = 0;
445 obj->is_ani = is_ani;
446 if (is_ani)
448 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;
450 ani_icon_data->num_steps = num_steps;
451 ani_icon_data->num_frames = num_steps; /* changed later for some animated cursors */
454 if (!(handle = alloc_user_handle( &obj->obj, USER_ICON )))
455 HeapFree( GetProcessHeap(), 0, obj );
456 return handle;
459 static struct cursoricon_object *get_icon_ptr( HICON handle )
461 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
462 if (obj == OBJ_OTHER_PROCESS)
464 WARN( "icon handle %p from other process\n", handle );
465 obj = NULL;
467 return obj;
470 static struct cursoricon_frame *get_icon_frame( struct cursoricon_object *obj, int istep )
472 struct static_cursoricon_object *req_frame;
474 if (obj->is_ani)
476 struct animated_cursoricon_object *ani_icon_data;
477 struct cursoricon_object *frameobj;
479 ani_icon_data = (struct animated_cursoricon_object *) obj;
480 if (!(frameobj = get_icon_ptr( ani_icon_data->frames[istep] )))
481 return 0;
482 req_frame = (struct static_cursoricon_object *) frameobj;
484 else
485 req_frame = (struct static_cursoricon_object *) obj;
487 return &req_frame->frame;
490 static void release_icon_frame( struct cursoricon_object *obj, struct cursoricon_frame *frame )
492 if (obj->is_ani)
494 struct cursoricon_object *frameobj;
496 frameobj = (struct cursoricon_object *) (((char *)frame) - FIELD_OFFSET(struct static_cursoricon_object, frame));
497 release_user_handle_ptr( frameobj );
501 static UINT get_icon_steps( struct cursoricon_object *obj )
503 if (obj->is_ani)
505 struct animated_cursoricon_object *ani_icon_data;
507 ani_icon_data = (struct animated_cursoricon_object *) obj;
508 return ani_icon_data->num_steps;
510 return 1;
513 static BOOL free_icon_handle( HICON handle )
515 struct cursoricon_object *obj = free_user_handle( handle, USER_ICON );
517 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
518 else if (obj)
520 ULONG_PTR param = obj->param;
521 UINT i;
523 assert( !obj->rsrc ); /* shared icons can't be freed */
525 if (!obj->is_ani)
527 struct cursoricon_frame *frame = get_icon_frame( obj, 0 );
529 if (frame->alpha) DeleteObject( frame->alpha );
530 if (frame->color) DeleteObject( frame->color );
531 DeleteObject( frame->mask );
532 release_icon_frame( obj, frame );
534 else
536 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;
538 for (i=0; i<ani_icon_data->num_steps; i++)
540 HICON hFrame = ani_icon_data->frames[i];
542 if (hFrame)
544 UINT j;
546 free_icon_handle( ani_icon_data->frames[i] );
547 for (j=0; j<ani_icon_data->num_steps; j++)
549 if (ani_icon_data->frames[j] == hFrame)
550 ani_icon_data->frames[j] = 0;
555 if (!IS_INTRESOURCE( obj->resname )) HeapFree( GetProcessHeap(), 0, obj->resname );
556 HeapFree( GetProcessHeap(), 0, obj );
557 if (wow_handlers.free_icon_param && param) wow_handlers.free_icon_param( param );
558 USER_Driver->pDestroyCursorIcon( handle );
559 return TRUE;
561 return FALSE;
564 ULONG_PTR get_icon_param( HICON handle )
566 ULONG_PTR ret = 0;
567 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
569 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
570 else if (obj)
572 ret = obj->param;
573 release_user_handle_ptr( obj );
575 return ret;
578 ULONG_PTR set_icon_param( HICON handle, ULONG_PTR param )
580 ULONG_PTR ret = 0;
581 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
583 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
584 else if (obj)
586 ret = obj->param;
587 obj->param = param;
588 release_user_handle_ptr( obj );
590 return ret;
594 /***********************************************************************
595 * map_fileW
597 * Helper function to map a file to memory:
598 * name - file name
599 * [RETURN] ptr - pointer to mapped file
600 * [RETURN] filesize - pointer size of file to be stored if not NULL
602 static const void *map_fileW( LPCWSTR name, LPDWORD filesize )
604 HANDLE hFile, hMapping;
605 LPVOID ptr = NULL;
607 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
608 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
609 if (hFile != INVALID_HANDLE_VALUE)
611 hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
612 if (hMapping)
614 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
615 CloseHandle( hMapping );
616 if (filesize)
617 *filesize = GetFileSize( hFile, NULL );
619 CloseHandle( hFile );
621 return ptr;
625 /***********************************************************************
626 * get_dib_image_size
628 * Return the size of a DIB bitmap in bytes.
630 static int get_dib_image_size( int width, int height, int depth )
632 return (((width * depth + 31) / 8) & ~3) * abs( height );
636 /***********************************************************************
637 * bitmap_info_size
639 * Return the size of the bitmap info structure including color table.
641 int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
643 unsigned int colors, size, masks = 0;
645 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
647 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
648 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
649 return sizeof(BITMAPCOREHEADER) + colors *
650 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
652 else /* assume BITMAPINFOHEADER */
654 colors = info->bmiHeader.biClrUsed;
655 if (colors > 256) /* buffer overflow otherwise */
656 colors = 256;
657 if (!colors && (info->bmiHeader.biBitCount <= 8))
658 colors = 1 << info->bmiHeader.biBitCount;
659 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
660 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
661 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
666 /***********************************************************************
667 * copy_bitmap
669 * Helper function to duplicate a bitmap.
671 static HBITMAP copy_bitmap( HBITMAP bitmap )
673 HDC src, dst = 0;
674 HBITMAP new_bitmap = 0;
675 BITMAP bmp;
677 if (!bitmap) return 0;
678 if (!GetObjectW( bitmap, sizeof(bmp), &bmp )) return 0;
680 if ((src = CreateCompatibleDC( 0 )) && (dst = CreateCompatibleDC( 0 )))
682 SelectObject( src, bitmap );
683 if ((new_bitmap = CreateCompatibleBitmap( src, bmp.bmWidth, bmp.bmHeight )))
685 SelectObject( dst, new_bitmap );
686 BitBlt( dst, 0, 0, bmp.bmWidth, bmp.bmHeight, src, 0, 0, SRCCOPY );
689 DeleteDC( dst );
690 DeleteDC( src );
691 return new_bitmap;
695 /***********************************************************************
696 * is_dib_monochrome
698 * Returns whether a DIB can be converted to a monochrome DDB.
700 * A DIB can be converted if its color table contains only black and
701 * white. Black must be the first color in the color table.
703 * Note : If the first color in the color table is white followed by
704 * black, we can't convert it to a monochrome DDB with
705 * SetDIBits, because black and white would be inverted.
707 static BOOL is_dib_monochrome( const BITMAPINFO* info )
709 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
711 const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
713 if (((const BITMAPCOREINFO*)info)->bmciHeader.bcBitCount != 1) return FALSE;
715 /* Check if the first color is black */
716 if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
718 rgb++;
720 /* Check if the second color is white */
721 return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
722 && (rgb->rgbtBlue == 0xff));
724 else return FALSE;
726 else /* assume BITMAPINFOHEADER */
728 const RGBQUAD *rgb = info->bmiColors;
730 if (info->bmiHeader.biBitCount != 1) return FALSE;
732 /* Check if the first color is black */
733 if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
734 (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
736 rgb++;
738 /* Check if the second color is white */
739 return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
740 && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
742 else return FALSE;
746 /***********************************************************************
747 * DIB_GetBitmapInfo
749 * Get the info from a bitmap header.
750 * Return 1 for INFOHEADER, 0 for COREHEADER, -1 in case of failure.
752 static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
753 LONG *height, WORD *bpp, DWORD *compr )
755 if (header->biSize == sizeof(BITMAPCOREHEADER))
757 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
758 *width = core->bcWidth;
759 *height = core->bcHeight;
760 *bpp = core->bcBitCount;
761 *compr = 0;
762 return 0;
764 else if (header->biSize == sizeof(BITMAPINFOHEADER) ||
765 header->biSize == sizeof(BITMAPV4HEADER) ||
766 header->biSize == sizeof(BITMAPV5HEADER))
768 *width = header->biWidth;
769 *height = header->biHeight;
770 *bpp = header->biBitCount;
771 *compr = header->biCompression;
772 return 1;
774 WARN("unknown/wrong size (%u) for header\n", header->biSize);
775 return -1;
778 /**********************************************************************
779 * get_icon_size
781 BOOL get_icon_size( HICON handle, SIZE *size )
783 struct cursoricon_object *info;
784 struct cursoricon_frame *frame;
786 if (!(info = get_icon_ptr( handle ))) return FALSE;
787 frame = get_icon_frame( info, 0 );
788 size->cx = frame->width;
789 size->cy = frame->height;
790 release_icon_frame( info, frame);
791 release_user_handle_ptr( info );
792 return TRUE;
796 * The following macro functions account for the irregularities of
797 * accessing cursor and icon resources in files and resource entries.
799 typedef BOOL (*fnGetCIEntry)( LPCVOID dir, DWORD size, int n,
800 int *width, int *height, int *bits );
802 /**********************************************************************
803 * CURSORICON_FindBestIcon
805 * Find the icon closest to the requested size and bit depth.
807 static int CURSORICON_FindBestIcon( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
808 int width, int height, int depth, UINT loadflags )
810 int i, cx, cy, bits, bestEntry = -1;
811 UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
812 UINT iTempXDiff, iTempYDiff, iTempColorDiff;
814 /* Find Best Fit */
815 iTotalDiff = 0xFFFFFFFF;
816 iColorDiff = 0xFFFFFFFF;
818 if (loadflags & LR_DEFAULTSIZE)
820 if (!width) width = GetSystemMetrics( SM_CXICON );
821 if (!height) height = GetSystemMetrics( SM_CYICON );
823 else if (!width && !height)
825 /* use the size of the first entry */
826 if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
827 iTotalDiff = 0;
830 for ( i = 0; iTotalDiff && get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
832 iTempXDiff = abs(width - cx);
833 iTempYDiff = abs(height - cy);
835 if(iTotalDiff > (iTempXDiff + iTempYDiff))
837 iXDiff = iTempXDiff;
838 iYDiff = iTempYDiff;
839 iTotalDiff = iXDiff + iYDiff;
843 /* Find Best Colors for Best Fit */
844 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
846 TRACE("entry %d: %d x %d, %d bpp\n", i, cx, cy, bits);
848 if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
850 iTempColorDiff = abs(depth - bits);
851 if(iColorDiff > iTempColorDiff)
853 bestEntry = i;
854 iColorDiff = iTempColorDiff;
859 return bestEntry;
862 static BOOL CURSORICON_GetResIconEntry( LPCVOID dir, DWORD size, int n,
863 int *width, int *height, int *bits )
865 const CURSORICONDIR *resdir = dir;
866 const ICONRESDIR *icon;
868 if ( resdir->idCount <= n )
869 return FALSE;
870 if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
871 return FALSE;
872 icon = &resdir->idEntries[n].ResInfo.icon;
873 *width = icon->bWidth;
874 *height = icon->bHeight;
875 *bits = resdir->idEntries[n].wBitCount;
876 if (!*width && !*height && have_libpng()) *width = *height = 256;
877 return TRUE;
880 /**********************************************************************
881 * CURSORICON_FindBestCursor
883 * Find the cursor closest to the requested size.
885 * FIXME: parameter 'color' ignored.
887 static int CURSORICON_FindBestCursor( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
888 int width, int height, int depth, UINT loadflags )
890 int i, maxwidth, maxheight, maxbits, cx, cy, bits, bestEntry = -1;
892 if (loadflags & LR_DEFAULTSIZE)
894 if (!width) width = GetSystemMetrics( SM_CXCURSOR );
895 if (!height) height = GetSystemMetrics( SM_CYCURSOR );
897 else if (!width && !height)
899 /* use the first entry */
900 if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
901 return 0;
904 /* First find the largest one smaller than or equal to the requested size*/
906 maxwidth = maxheight = maxbits = 0;
907 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
909 if (cx > width || cy > height) continue;
910 if (cx < maxwidth || cy < maxheight) continue;
911 if (cx == maxwidth && cy == maxheight)
913 if (loadflags & LR_MONOCHROME)
915 if (maxbits && bits >= maxbits) continue;
917 else if (bits <= maxbits) continue;
919 bestEntry = i;
920 maxwidth = cx;
921 maxheight = cy;
922 maxbits = bits;
924 if (bestEntry != -1) return bestEntry;
926 /* Now find the smallest one larger than the requested size */
928 maxwidth = maxheight = 255;
929 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
931 if (cx > maxwidth || cy > maxheight) continue;
932 if (cx == maxwidth && cy == maxheight)
934 if (loadflags & LR_MONOCHROME)
936 if (maxbits && bits >= maxbits) continue;
938 else if (bits <= maxbits) continue;
940 bestEntry = i;
941 maxwidth = cx;
942 maxheight = cy;
943 maxbits = bits;
945 if (bestEntry == -1) bestEntry = 0;
947 return bestEntry;
950 static BOOL CURSORICON_GetResCursorEntry( LPCVOID dir, DWORD size, int n,
951 int *width, int *height, int *bits )
953 const CURSORICONDIR *resdir = dir;
954 const CURSORDIR *cursor;
956 if ( resdir->idCount <= n )
957 return FALSE;
958 if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
959 return FALSE;
960 cursor = &resdir->idEntries[n].ResInfo.cursor;
961 *width = cursor->wWidth;
962 *height = cursor->wHeight;
963 *bits = resdir->idEntries[n].wBitCount;
964 if (*height == *width * 2) *height /= 2;
965 return TRUE;
968 static const CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( const CURSORICONDIR * dir, DWORD size,
969 int width, int height, int depth,
970 UINT loadflags )
972 int n;
974 n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetResIconEntry,
975 width, height, depth, loadflags );
976 if ( n < 0 )
977 return NULL;
978 return &dir->idEntries[n];
981 static const CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( const CURSORICONDIR *dir, DWORD size,
982 int width, int height, int depth,
983 UINT loadflags )
985 int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetResCursorEntry,
986 width, height, depth, loadflags );
987 if ( n < 0 )
988 return NULL;
989 return &dir->idEntries[n];
992 static BOOL CURSORICON_GetFileEntry( LPCVOID dir, DWORD size, int n,
993 int *width, int *height, int *bits )
995 const CURSORICONFILEDIR *filedir = dir;
996 const CURSORICONFILEDIRENTRY *entry;
997 const BITMAPINFOHEADER *info;
999 if ( filedir->idCount <= n )
1000 return FALSE;
1001 if ((const char *)&filedir->idEntries[n + 1] - (const char *)dir > size)
1002 return FALSE;
1003 entry = &filedir->idEntries[n];
1004 if (entry->dwDIBOffset > size - sizeof(info->biSize)) return FALSE;
1005 info = (const BITMAPINFOHEADER *)((const char *)dir + entry->dwDIBOffset);
1007 if (info->biSize == PNG_SIGN)
1009 if (have_libpng()) return get_png_info(info, size, width, height, bits);
1010 *width = *height = *bits = 0;
1011 return TRUE;
1014 if (info->biSize != sizeof(BITMAPCOREHEADER))
1016 if ((const char *)(info + 1) - (const char *)dir > size) return FALSE;
1017 *bits = info->biBitCount;
1019 else
1021 const BITMAPCOREHEADER *coreinfo = (const BITMAPCOREHEADER *)((const char *)dir + entry->dwDIBOffset);
1022 if ((const char *)(coreinfo + 1) - (const char *)dir > size) return FALSE;
1023 *bits = coreinfo->bcBitCount;
1025 *width = entry->bWidth;
1026 *height = entry->bHeight;
1027 return TRUE;
1030 static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( const CURSORICONFILEDIR *dir, DWORD size,
1031 int width, int height, int depth,
1032 UINT loadflags )
1034 int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetFileEntry,
1035 width, height, depth, loadflags );
1036 if ( n < 0 )
1037 return NULL;
1038 return &dir->idEntries[n];
1041 static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( const CURSORICONFILEDIR *dir, DWORD size,
1042 int width, int height, int depth,
1043 UINT loadflags )
1045 int n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetFileEntry,
1046 width, height, depth, loadflags );
1047 if ( n < 0 )
1048 return NULL;
1049 return &dir->idEntries[n];
1052 /***********************************************************************
1053 * bmi_has_alpha
1055 static BOOL bmi_has_alpha( const BITMAPINFO *info, const void *bits )
1057 int i;
1058 BOOL has_alpha = FALSE;
1059 const unsigned char *ptr = bits;
1061 if (info->bmiHeader.biBitCount != 32) return FALSE;
1062 for (i = 0; i < info->bmiHeader.biWidth * abs(info->bmiHeader.biHeight); i++, ptr += 4)
1063 if ((has_alpha = (ptr[3] != 0))) break;
1064 return has_alpha;
1067 /***********************************************************************
1068 * create_alpha_bitmap
1070 * Create the alpha bitmap for a 32-bpp icon that has an alpha channel.
1072 static HBITMAP create_alpha_bitmap( HBITMAP color, const BITMAPINFO *src_info, const void *color_bits )
1074 HBITMAP alpha = 0;
1075 BITMAPINFO *info = NULL;
1076 BITMAP bm;
1077 HDC hdc;
1078 void *bits;
1079 unsigned char *ptr;
1080 int i;
1082 if (!GetObjectW( color, sizeof(bm), &bm )) return 0;
1083 if (bm.bmBitsPixel != 32) return 0;
1085 if (!(hdc = CreateCompatibleDC( 0 ))) return 0;
1086 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto done;
1087 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1088 info->bmiHeader.biWidth = bm.bmWidth;
1089 info->bmiHeader.biHeight = -bm.bmHeight;
1090 info->bmiHeader.biPlanes = 1;
1091 info->bmiHeader.biBitCount = 32;
1092 info->bmiHeader.biCompression = BI_RGB;
1093 info->bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
1094 info->bmiHeader.biXPelsPerMeter = 0;
1095 info->bmiHeader.biYPelsPerMeter = 0;
1096 info->bmiHeader.biClrUsed = 0;
1097 info->bmiHeader.biClrImportant = 0;
1098 if (!(alpha = CreateDIBSection( hdc, info, DIB_RGB_COLORS, &bits, NULL, 0 ))) goto done;
1100 if (src_info)
1102 SelectObject( hdc, alpha );
1103 StretchDIBits( hdc, 0, 0, bm.bmWidth, bm.bmHeight,
1104 0, 0, src_info->bmiHeader.biWidth, src_info->bmiHeader.biHeight,
1105 color_bits, src_info, DIB_RGB_COLORS, SRCCOPY );
1108 else
1110 GetDIBits( hdc, color, 0, bm.bmHeight, bits, info, DIB_RGB_COLORS );
1111 if (!bmi_has_alpha( info, bits ))
1113 DeleteObject( alpha );
1114 alpha = 0;
1115 goto done;
1119 /* pre-multiply by alpha */
1120 for (i = 0, ptr = bits; i < bm.bmWidth * bm.bmHeight; i++, ptr += 4)
1122 unsigned int alpha = ptr[3];
1123 ptr[0] = ptr[0] * alpha / 255;
1124 ptr[1] = ptr[1] * alpha / 255;
1125 ptr[2] = ptr[2] * alpha / 255;
1128 done:
1129 DeleteDC( hdc );
1130 HeapFree( GetProcessHeap(), 0, info );
1131 return alpha;
1135 /***********************************************************************
1136 * create_icon_from_bmi
1138 * Create an icon from its BITMAPINFO.
1140 static HICON create_icon_from_bmi( const BITMAPINFO *bmi, DWORD maxsize, HMODULE module, LPCWSTR resname,
1141 HRSRC rsrc, POINT hotspot, BOOL bIcon, INT width, INT height,
1142 UINT cFlag )
1144 DWORD size, color_size, mask_size;
1145 HBITMAP color = 0, mask = 0, alpha = 0;
1146 const void *color_bits, *mask_bits;
1147 void *alpha_mask_bits = NULL;
1148 BITMAPINFO *bmi_copy;
1149 BOOL ret = FALSE;
1150 BOOL do_stretch;
1151 HICON hObj = 0;
1152 HDC hdc = 0;
1153 LONG bmi_width, bmi_height;
1154 WORD bpp;
1155 DWORD compr;
1157 /* Check bitmap header */
1159 if (bmi->bmiHeader.biSize == PNG_SIGN)
1161 BITMAPINFO *bmi_png;
1163 bmi_png = load_png( (const char *)bmi, &maxsize );
1164 if (bmi_png)
1166 hObj = create_icon_from_bmi( bmi_png, maxsize, module, resname,
1167 rsrc, hotspot, bIcon, width, height, cFlag );
1168 HeapFree( GetProcessHeap(), 0, bmi_png );
1169 return hObj;
1171 return 0;
1174 if (maxsize < sizeof(BITMAPCOREHEADER))
1176 WARN( "invalid size %u\n", maxsize );
1177 return 0;
1179 if (maxsize < bmi->bmiHeader.biSize)
1181 WARN( "invalid header size %u\n", bmi->bmiHeader.biSize );
1182 return 0;
1184 if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
1185 (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER) ||
1186 (bmi->bmiHeader.biCompression != BI_RGB &&
1187 bmi->bmiHeader.biCompression != BI_BITFIELDS)) )
1189 WARN( "invalid bitmap header %u\n", bmi->bmiHeader.biSize );
1190 return 0;
1193 size = bitmap_info_size( bmi, DIB_RGB_COLORS );
1194 DIB_GetBitmapInfo(&bmi->bmiHeader, &bmi_width, &bmi_height, &bpp, &compr);
1195 color_size = get_dib_image_size( bmi_width, bmi_height / 2,
1196 bpp );
1197 mask_size = get_dib_image_size( bmi_width, bmi_height / 2, 1 );
1198 if (size > maxsize || color_size > maxsize - size)
1200 WARN( "truncated file %u < %u+%u+%u\n", maxsize, size, color_size, mask_size );
1201 return 0;
1203 if (mask_size > maxsize - size - color_size) mask_size = 0; /* no mask */
1205 if (cFlag & LR_DEFAULTSIZE)
1207 if (!width) width = GetSystemMetrics( bIcon ? SM_CXICON : SM_CXCURSOR );
1208 if (!height) height = GetSystemMetrics( bIcon ? SM_CYICON : SM_CYCURSOR );
1210 else
1212 if (!width) width = bmi_width;
1213 if (!height) height = bmi_height/2;
1215 do_stretch = (bmi_height/2 != height) ||
1216 (bmi_width != width);
1218 /* Scale the hotspot */
1219 if (bIcon)
1221 hotspot.x = width / 2;
1222 hotspot.y = height / 2;
1224 else if (do_stretch)
1226 hotspot.x = (hotspot.x * width) / bmi_width;
1227 hotspot.y = (hotspot.y * height) / (bmi_height / 2);
1230 if (!(bmi_copy = HeapAlloc( GetProcessHeap(), 0, max( size, FIELD_OFFSET( BITMAPINFO, bmiColors[2] )))))
1231 return 0;
1232 if (!(hdc = CreateCompatibleDC( 0 ))) goto done;
1234 memcpy( bmi_copy, bmi, size );
1235 if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
1236 bmi_copy->bmiHeader.biHeight /= 2;
1237 else
1238 ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcHeight /= 2;
1239 bmi_height /= 2;
1241 color_bits = (const char*)bmi + size;
1242 mask_bits = (const char*)color_bits + color_size;
1244 alpha = 0;
1245 if (is_dib_monochrome( bmi ))
1247 if (!(mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
1248 color = 0;
1250 /* copy color data into second half of mask bitmap */
1251 SelectObject( hdc, mask );
1252 StretchDIBits( hdc, 0, height, width, height,
1253 0, 0, bmi_width, bmi_height,
1254 color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1256 else
1258 if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
1259 if (!(color = create_color_bitmap( width, height )))
1261 DeleteObject( mask );
1262 goto done;
1264 SelectObject( hdc, color );
1265 StretchDIBits( hdc, 0, 0, width, height,
1266 0, 0, bmi_width, bmi_height,
1267 color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1269 if (bmi_has_alpha( bmi_copy, color_bits ))
1271 alpha = create_alpha_bitmap( color, bmi_copy, color_bits );
1272 if (!mask_size) /* generate mask from alpha */
1274 LONG x, y, dst_stride = ((bmi_width + 31) / 8) & ~3;
1276 if ((alpha_mask_bits = heap_calloc( bmi_height, dst_stride )))
1278 static const unsigned char masks[] = { 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 };
1279 const DWORD *src = color_bits;
1280 unsigned char *dst = alpha_mask_bits;
1282 for (y = 0; y < bmi_height; y++, src += bmi_width, dst += dst_stride)
1283 for (x = 0; x < bmi_width; x++)
1284 if (src[x] >> 24 != 0xff) dst[x >> 3] |= masks[x & 7];
1286 mask_bits = alpha_mask_bits;
1287 mask_size = bmi_height * dst_stride;
1292 /* convert info to monochrome to copy the mask */
1293 if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
1295 RGBQUAD *rgb = bmi_copy->bmiColors;
1297 bmi_copy->bmiHeader.biBitCount = 1;
1298 bmi_copy->bmiHeader.biClrUsed = bmi_copy->bmiHeader.biClrImportant = 2;
1299 rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
1300 rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
1301 rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
1303 else
1305 RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)bmi_copy) + 1);
1307 ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcBitCount = 1;
1308 rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
1309 rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
1313 if (mask_size)
1315 SelectObject( hdc, mask );
1316 StretchDIBits( hdc, 0, 0, width, height,
1317 0, 0, bmi_width, bmi_height,
1318 mask_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1320 ret = TRUE;
1322 done:
1323 DeleteDC( hdc );
1324 HeapFree( GetProcessHeap(), 0, bmi_copy );
1325 HeapFree( GetProcessHeap(), 0, alpha_mask_bits );
1327 if (ret)
1328 hObj = alloc_icon_handle( FALSE, 0 );
1329 if (hObj)
1331 struct cursoricon_object *info = get_icon_ptr( hObj );
1332 struct cursoricon_frame *frame;
1334 info->is_icon = bIcon;
1335 info->module = module;
1336 info->hotspot = hotspot;
1337 frame = get_icon_frame( info, 0 );
1338 frame->delay = ~0;
1339 frame->width = width;
1340 frame->height = height;
1341 frame->color = color;
1342 frame->mask = mask;
1343 frame->alpha = alpha;
1344 release_icon_frame( info, frame );
1345 if (!IS_INTRESOURCE(resname))
1347 info->resname = HeapAlloc( GetProcessHeap(), 0, (strlenW(resname) + 1) * sizeof(WCHAR) );
1348 if (info->resname) strcpyW( info->resname, resname );
1350 else info->resname = MAKEINTRESOURCEW( LOWORD(resname) );
1352 if (module && (cFlag & LR_SHARED))
1354 info->rsrc = rsrc;
1355 list_add_head( &icon_cache, &info->entry );
1357 release_user_handle_ptr( info );
1359 else
1361 DeleteObject( color );
1362 DeleteObject( alpha );
1363 DeleteObject( mask );
1365 return hObj;
1369 /**********************************************************************
1370 * .ANI cursor support
1372 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
1373 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
1374 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
1375 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
1376 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
1377 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
1378 #define ANI_rate_ID RIFF_FOURCC('r', 'a', 't', 'e')
1380 #define ANI_FLAG_ICON 0x1
1381 #define ANI_FLAG_SEQUENCE 0x2
1383 typedef struct {
1384 DWORD header_size;
1385 DWORD num_frames;
1386 DWORD num_steps;
1387 DWORD width;
1388 DWORD height;
1389 DWORD bpp;
1390 DWORD num_planes;
1391 DWORD display_rate;
1392 DWORD flags;
1393 } ani_header;
1395 typedef struct {
1396 DWORD data_size;
1397 const unsigned char *data;
1398 } riff_chunk_t;
1400 static void dump_ani_header( const ani_header *header )
1402 TRACE(" header size: %d\n", header->header_size);
1403 TRACE(" frames: %d\n", header->num_frames);
1404 TRACE(" steps: %d\n", header->num_steps);
1405 TRACE(" width: %d\n", header->width);
1406 TRACE(" height: %d\n", header->height);
1407 TRACE(" bpp: %d\n", header->bpp);
1408 TRACE(" planes: %d\n", header->num_planes);
1409 TRACE(" display rate: %d\n", header->display_rate);
1410 TRACE(" flags: 0x%08x\n", header->flags);
1415 * RIFF:
1416 * DWORD "RIFF"
1417 * DWORD size
1418 * DWORD riff_id
1419 * BYTE[] data
1421 * LIST:
1422 * DWORD "LIST"
1423 * DWORD size
1424 * DWORD list_id
1425 * BYTE[] data
1427 * CHUNK:
1428 * DWORD chunk_id
1429 * DWORD size
1430 * BYTE[] data
1432 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
1434 const unsigned char *ptr = parent_chunk->data;
1435 const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
1437 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
1439 while (ptr < end)
1441 if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
1442 || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1444 ptr += sizeof(DWORD);
1445 chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1446 ptr += sizeof(DWORD);
1447 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
1448 chunk->data = ptr;
1450 return;
1453 ptr += sizeof(DWORD);
1454 ptr += (*(const DWORD *)ptr + 1) & ~1;
1455 ptr += sizeof(DWORD);
1461 * .ANI layout:
1463 * RIFF:'ACON' RIFF chunk
1464 * |- CHUNK:'anih' Header
1465 * |- CHUNK:'seq ' Sequence information (optional)
1466 * \- LIST:'fram' Frame list
1467 * |- CHUNK:icon Cursor frames
1468 * |- CHUNK:icon
1469 * |- ...
1470 * \- CHUNK:icon
1472 static HCURSOR CURSORICON_CreateIconFromANI( const BYTE *bits, DWORD bits_size, INT width, INT height,
1473 INT depth, BOOL is_icon, UINT loadflags )
1475 struct animated_cursoricon_object *ani_icon_data;
1476 struct cursoricon_object *info;
1477 DWORD *frame_rates = NULL;
1478 DWORD *frame_seq = NULL;
1479 ani_header header;
1480 BOOL use_seq = FALSE;
1481 HCURSOR cursor;
1482 UINT i;
1483 BOOL error = FALSE;
1484 HICON *frames;
1486 riff_chunk_t root_chunk = { bits_size, bits };
1487 riff_chunk_t ACON_chunk = {0};
1488 riff_chunk_t anih_chunk = {0};
1489 riff_chunk_t fram_chunk = {0};
1490 riff_chunk_t rate_chunk = {0};
1491 riff_chunk_t seq_chunk = {0};
1492 const unsigned char *icon_chunk;
1493 const unsigned char *icon_data;
1495 TRACE("bits %p, bits_size %d\n", bits, bits_size);
1497 riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1498 if (!ACON_chunk.data)
1500 ERR("Failed to get root chunk.\n");
1501 return 0;
1504 riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1505 if (!anih_chunk.data)
1507 ERR("Failed to get 'anih' chunk.\n");
1508 return 0;
1510 memcpy( &header, anih_chunk.data, sizeof(header) );
1511 dump_ani_header( &header );
1513 if (!(header.flags & ANI_FLAG_ICON))
1515 FIXME("Raw animated icon/cursor data is not currently supported.\n");
1516 return 0;
1519 if (header.flags & ANI_FLAG_SEQUENCE)
1521 riff_find_chunk( ANI_seq__ID, 0, &ACON_chunk, &seq_chunk );
1522 if (seq_chunk.data)
1524 frame_seq = (DWORD *) seq_chunk.data;
1525 use_seq = TRUE;
1527 else
1529 FIXME("Sequence data expected but not found, assuming steps == frames.\n");
1530 header.num_steps = header.num_frames;
1534 riff_find_chunk( ANI_rate_ID, 0, &ACON_chunk, &rate_chunk );
1535 if (rate_chunk.data)
1536 frame_rates = (DWORD *) rate_chunk.data;
1538 riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1539 if (!fram_chunk.data)
1541 ERR("Failed to get icon list.\n");
1542 return 0;
1545 cursor = alloc_icon_handle( TRUE, header.num_steps );
1546 if (!cursor) return 0;
1547 frames = HeapAlloc( GetProcessHeap(), 0, sizeof(*frames) * header.num_frames );
1548 if (!frames)
1550 free_icon_handle( cursor );
1551 return 0;
1554 info = get_icon_ptr( cursor );
1555 ani_icon_data = (struct animated_cursoricon_object *) info;
1556 info->is_icon = is_icon;
1557 ani_icon_data->num_frames = header.num_frames;
1559 /* The .ANI stores the display rate in jiffies (1/60s) */
1560 info->delay = header.display_rate;
1562 icon_chunk = fram_chunk.data;
1563 icon_data = fram_chunk.data + (2 * sizeof(DWORD));
1564 for (i=0; i<header.num_frames; i++)
1566 const DWORD chunk_size = *(const DWORD *)(icon_chunk + sizeof(DWORD));
1567 const CURSORICONFILEDIRENTRY *entry;
1568 INT frameWidth, frameHeight;
1569 const BITMAPINFO *bmi;
1571 entry = CURSORICON_FindBestIconFile((const CURSORICONFILEDIR *) icon_data,
1572 bits + bits_size - icon_data,
1573 width, height, depth, loadflags );
1575 info->hotspot.x = entry->xHotspot;
1576 info->hotspot.y = entry->yHotspot;
1577 if (!header.width || !header.height)
1579 frameWidth = entry->bWidth;
1580 frameHeight = entry->bHeight;
1582 else
1584 frameWidth = header.width;
1585 frameHeight = header.height;
1588 frames[i] = NULL;
1589 if (entry->dwDIBOffset < bits + bits_size - icon_data)
1591 bmi = (const BITMAPINFO *) (icon_data + entry->dwDIBOffset);
1592 /* Grab a frame from the animation */
1593 frames[i] = create_icon_from_bmi( bmi, bits + bits_size - (const BYTE *)bmi,
1594 NULL, NULL, NULL, info->hotspot,
1595 is_icon, frameWidth, frameHeight, loadflags );
1598 if (!frames[i])
1600 FIXME_(cursor)("failed to convert animated cursor frame.\n");
1601 error = TRUE;
1602 if (i == 0)
1604 FIXME_(cursor)("Completely failed to create animated cursor!\n");
1605 ani_icon_data->num_frames = 0;
1606 release_user_handle_ptr( info );
1607 free_icon_handle( cursor );
1608 HeapFree( GetProcessHeap(), 0, frames );
1609 return 0;
1611 break;
1614 /* Advance to the next chunk */
1615 icon_chunk += chunk_size + (2 * sizeof(DWORD));
1616 icon_data = icon_chunk + (2 * sizeof(DWORD));
1619 /* There was an error but we at least decoded the first frame, so just use that frame */
1620 if (error)
1622 FIXME_(cursor)("Error creating animated cursor, only using first frame!\n");
1623 for (i=1; i<ani_icon_data->num_frames; i++)
1624 free_icon_handle( ani_icon_data->frames[i] );
1625 use_seq = FALSE;
1626 info->delay = 0;
1627 ani_icon_data->num_steps = 1;
1628 ani_icon_data->num_frames = 1;
1631 /* Setup the animated frames in the correct sequence */
1632 for (i=0; i<ani_icon_data->num_steps; i++)
1634 DWORD frame_id = use_seq ? frame_seq[i] : i;
1635 struct cursoricon_frame *frame;
1637 if (frame_id >= ani_icon_data->num_frames)
1639 frame_id = ani_icon_data->num_frames-1;
1640 ERR_(cursor)("Sequence indicates frame past end of list, corrupt?\n");
1642 ani_icon_data->frames[i] = frames[frame_id];
1643 frame = get_icon_frame( info, i );
1644 if (frame_rates)
1645 frame->delay = frame_rates[i];
1646 else
1647 frame->delay = ~0;
1648 release_icon_frame( info, frame );
1651 HeapFree( GetProcessHeap(), 0, frames );
1652 release_user_handle_ptr( info );
1654 return cursor;
1658 /**********************************************************************
1659 * CreateIconFromResourceEx (USER32.@)
1661 * FIXME: Convert to mono when cFlag is LR_MONOCHROME.
1663 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1664 BOOL bIcon, DWORD dwVersion,
1665 INT width, INT height,
1666 UINT cFlag )
1668 POINT hotspot;
1669 const BITMAPINFO *bmi;
1671 TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s %s\n",
1672 bits, cbSize, dwVersion, width, height,
1673 bIcon ? "icon" : "cursor", (cFlag & LR_MONOCHROME) ? "mono" : "" );
1675 if (!bits) return 0;
1677 if (dwVersion == 0x00020000)
1679 FIXME_(cursor)("\t2.xx resources are not supported\n");
1680 return 0;
1683 /* Check if the resource is an animated icon/cursor */
1684 if (!memcmp(bits, "RIFF", 4))
1685 return CURSORICON_CreateIconFromANI( bits, cbSize, width, height,
1686 0 /* default depth */, bIcon, cFlag );
1688 if (bIcon)
1690 hotspot.x = width / 2;
1691 hotspot.y = height / 2;
1692 bmi = (BITMAPINFO *)bits;
1694 else /* get the hotspot */
1696 const SHORT *pt = (const SHORT *)bits;
1697 hotspot.x = pt[0];
1698 hotspot.y = pt[1];
1699 bmi = (const BITMAPINFO *)(pt + 2);
1700 cbSize -= 2 * sizeof(*pt);
1703 return create_icon_from_bmi( bmi, cbSize, NULL, NULL, NULL, hotspot, bIcon, width, height, cFlag );
1707 /**********************************************************************
1708 * CreateIconFromResource (USER32.@)
1710 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1711 BOOL bIcon, DWORD dwVersion)
1713 return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
1717 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1718 INT width, INT height, INT depth,
1719 BOOL fCursor, UINT loadflags)
1721 const CURSORICONFILEDIRENTRY *entry;
1722 const CURSORICONFILEDIR *dir;
1723 DWORD filesize = 0;
1724 HICON hIcon = 0;
1725 const BYTE *bits;
1726 POINT hotspot;
1728 TRACE("loading %s\n", debugstr_w( filename ));
1730 bits = map_fileW( filename, &filesize );
1731 if (!bits)
1732 return hIcon;
1734 /* Check for .ani. */
1735 if (memcmp( bits, "RIFF", 4 ) == 0)
1737 hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height, depth, !fCursor, loadflags );
1738 goto end;
1741 dir = (const CURSORICONFILEDIR*) bits;
1742 if ( filesize < FIELD_OFFSET( CURSORICONFILEDIR, idEntries[dir->idCount] ))
1743 goto end;
1745 if ( fCursor )
1746 entry = CURSORICON_FindBestCursorFile( dir, filesize, width, height, depth, loadflags );
1747 else
1748 entry = CURSORICON_FindBestIconFile( dir, filesize, width, height, depth, loadflags );
1750 if ( !entry )
1751 goto end;
1753 /* check that we don't run off the end of the file */
1754 if ( entry->dwDIBOffset > filesize )
1755 goto end;
1756 if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1757 goto end;
1759 hotspot.x = entry->xHotspot;
1760 hotspot.y = entry->yHotspot;
1761 hIcon = create_icon_from_bmi( (const BITMAPINFO *)&bits[entry->dwDIBOffset], filesize - entry->dwDIBOffset,
1762 NULL, NULL, NULL, hotspot, !fCursor, width, height, loadflags );
1763 end:
1764 TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1765 UnmapViewOfFile( bits );
1766 return hIcon;
1769 /**********************************************************************
1770 * CURSORICON_Load
1772 * Load a cursor or icon from resource or file.
1774 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1775 INT width, INT height, INT depth,
1776 BOOL fCursor, UINT loadflags)
1778 HANDLE handle = 0;
1779 HICON hIcon = 0;
1780 HRSRC hRsrc;
1781 DWORD size;
1782 const CURSORICONDIR *dir;
1783 const CURSORICONDIRENTRY *dirEntry;
1784 const BYTE *bits;
1785 WORD wResId;
1786 POINT hotspot;
1788 TRACE("%p, %s, %dx%d, depth %d, fCursor %d, flags 0x%04x\n",
1789 hInstance, debugstr_w(name), width, height, depth, fCursor, loadflags);
1791 if ( loadflags & LR_LOADFROMFILE ) /* Load from file */
1792 return CURSORICON_LoadFromFile( name, width, height, depth, fCursor, loadflags );
1794 if (!hInstance) hInstance = user32_module; /* Load OEM cursor/icon */
1796 /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1797 if ((ULONG_PTR)hInstance >> 16 == 0) loadflags &= ~LR_SHARED;
1799 /* Get directory resource ID */
1801 if (!(hRsrc = FindResourceW( hInstance, name,
1802 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1804 /* try animated resource */
1805 if (!(hRsrc = FindResourceW( hInstance, name,
1806 (LPWSTR)(fCursor ? RT_ANICURSOR : RT_ANIICON) ))) return 0;
1807 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1808 bits = LockResource( handle );
1809 return CURSORICON_CreateIconFromANI( bits, SizeofResource( hInstance, handle ),
1810 width, height, depth, !fCursor, loadflags );
1813 /* Find the best entry in the directory */
1815 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1816 if (!(dir = LockResource( handle ))) return 0;
1817 size = SizeofResource( hInstance, hRsrc );
1818 if (fCursor)
1819 dirEntry = CURSORICON_FindBestCursorRes( dir, size, width, height, depth, loadflags );
1820 else
1821 dirEntry = CURSORICON_FindBestIconRes( dir, size, width, height, depth, loadflags );
1822 if (!dirEntry) return 0;
1823 wResId = dirEntry->wResId;
1824 FreeResource( handle );
1826 /* Load the resource */
1828 if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1829 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1831 /* If shared icon, check whether it was already loaded */
1832 if (loadflags & LR_SHARED)
1834 struct cursoricon_object *ptr;
1836 USER_Lock();
1837 LIST_FOR_EACH_ENTRY( ptr, &icon_cache, struct cursoricon_object, entry )
1839 if (ptr->module != hInstance) continue;
1840 if (ptr->rsrc != hRsrc) continue;
1841 hIcon = ptr->obj.handle;
1842 break;
1844 USER_Unlock();
1845 if (hIcon) return hIcon;
1848 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1849 size = SizeofResource( hInstance, hRsrc );
1850 bits = LockResource( handle );
1852 if (!fCursor)
1854 hotspot.x = width / 2;
1855 hotspot.y = height / 2;
1857 else /* get the hotspot */
1859 const SHORT *pt = (const SHORT *)bits;
1860 hotspot.x = pt[0];
1861 hotspot.y = pt[1];
1862 bits += 2 * sizeof(SHORT);
1863 size -= 2 * sizeof(SHORT);
1865 hIcon = create_icon_from_bmi( (const BITMAPINFO *)bits, size, hInstance, name, hRsrc,
1866 hotspot, !fCursor, width, height, loadflags );
1867 FreeResource( handle );
1868 return hIcon;
1872 /***********************************************************************
1873 * CreateCursor (USER32.@)
1875 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
1876 INT xHotSpot, INT yHotSpot,
1877 INT nWidth, INT nHeight,
1878 LPCVOID lpANDbits, LPCVOID lpXORbits )
1880 ICONINFO info;
1881 HCURSOR hCursor;
1883 TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
1884 nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1886 info.fIcon = FALSE;
1887 info.xHotspot = xHotSpot;
1888 info.yHotspot = yHotSpot;
1889 info.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1890 info.hbmColor = CreateBitmap( nWidth, nHeight, 1, 1, lpXORbits );
1891 hCursor = CreateIconIndirect( &info );
1892 DeleteObject( info.hbmMask );
1893 DeleteObject( info.hbmColor );
1894 return hCursor;
1898 /***********************************************************************
1899 * CreateIcon (USER32.@)
1901 * Creates an icon based on the specified bitmaps. The bitmaps must be
1902 * provided in a device dependent format and will be resized to
1903 * (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1904 * depth. The provided bitmaps must be top-down bitmaps.
1905 * Although Windows does not support 15bpp(*) this API must support it
1906 * for Winelib applications.
1908 * (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1909 * format!
1911 * RETURNS
1912 * Success: handle to an icon
1913 * Failure: NULL
1915 * FIXME: Do we need to resize the bitmaps?
1917 HICON WINAPI CreateIcon(
1918 HINSTANCE hInstance, /* [in] the application's hInstance */
1919 INT nWidth, /* [in] the width of the provided bitmaps */
1920 INT nHeight, /* [in] the height of the provided bitmaps */
1921 BYTE bPlanes, /* [in] the number of planes in the provided bitmaps */
1922 BYTE bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1923 LPCVOID lpANDbits, /* [in] a monochrome bitmap representing the icon's mask */
1924 LPCVOID lpXORbits) /* [in] the icon's 'color' bitmap */
1926 ICONINFO iinfo;
1927 HICON hIcon;
1929 TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
1930 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1932 iinfo.fIcon = TRUE;
1933 iinfo.xHotspot = nWidth / 2;
1934 iinfo.yHotspot = nHeight / 2;
1935 iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1936 iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );
1938 hIcon = CreateIconIndirect( &iinfo );
1940 DeleteObject( iinfo.hbmMask );
1941 DeleteObject( iinfo.hbmColor );
1943 return hIcon;
1947 /***********************************************************************
1948 * CopyIcon (USER32.@)
1950 HICON WINAPI CopyIcon( HICON hIcon )
1952 struct cursoricon_object *ptrOld, *ptrNew;
1953 HICON hNew;
1955 if (!(ptrOld = get_icon_ptr( hIcon )))
1957 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
1958 return 0;
1960 if ((hNew = alloc_icon_handle( FALSE, 0 )))
1962 struct cursoricon_frame *frameOld, *frameNew;
1964 ptrNew = get_icon_ptr( hNew );
1965 ptrNew->is_icon = ptrOld->is_icon;
1966 ptrNew->hotspot = ptrOld->hotspot;
1967 if (!(frameOld = get_icon_frame( ptrOld, 0 )))
1969 release_user_handle_ptr( ptrOld );
1970 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
1971 return 0;
1973 if (!(frameNew = get_icon_frame( ptrNew, 0 )))
1975 release_icon_frame( ptrOld, frameOld );
1976 release_user_handle_ptr( ptrOld );
1977 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
1978 return 0;
1980 frameNew->delay = 0;
1981 frameNew->width = frameOld->width;
1982 frameNew->height = frameOld->height;
1983 frameNew->mask = copy_bitmap( frameOld->mask );
1984 frameNew->color = copy_bitmap( frameOld->color );
1985 frameNew->alpha = copy_bitmap( frameOld->alpha );
1986 release_icon_frame( ptrOld, frameOld );
1987 release_icon_frame( ptrNew, frameNew );
1988 release_user_handle_ptr( ptrNew );
1990 release_user_handle_ptr( ptrOld );
1991 return hNew;
1995 /***********************************************************************
1996 * DestroyIcon (USER32.@)
1998 BOOL WINAPI DestroyIcon( HICON hIcon )
2000 BOOL ret = FALSE;
2001 struct cursoricon_object *obj = get_icon_ptr( hIcon );
2003 TRACE_(icon)("%p\n", hIcon );
2005 if (obj)
2007 BOOL shared = (obj->rsrc != NULL);
2008 release_user_handle_ptr( obj );
2009 ret = (GetCursor() != hIcon);
2010 if (!shared) free_icon_handle( hIcon );
2012 return ret;
2016 /***********************************************************************
2017 * DestroyCursor (USER32.@)
2019 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
2021 return DestroyIcon( hCursor );
2024 /***********************************************************************
2025 * DrawIcon (USER32.@)
2027 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
2029 return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
2032 /***********************************************************************
2033 * SetCursor (USER32.@)
2035 * Set the cursor shape.
2037 * RETURNS
2038 * A handle to the previous cursor shape.
2040 HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
2042 struct cursoricon_object *obj;
2043 HCURSOR hOldCursor;
2044 int show_count;
2045 BOOL ret;
2047 TRACE("%p\n", hCursor);
2049 SERVER_START_REQ( set_cursor )
2051 req->flags = SET_CURSOR_HANDLE;
2052 req->handle = wine_server_user_handle( hCursor );
2053 if ((ret = !wine_server_call_err( req )))
2055 hOldCursor = wine_server_ptr_handle( reply->prev_handle );
2056 show_count = reply->prev_count;
2059 SERVER_END_REQ;
2061 if (!ret) return 0;
2062 USER_Driver->pSetCursor( show_count >= 0 ? hCursor : 0 );
2064 if (!(obj = get_icon_ptr( hOldCursor ))) return 0;
2065 release_user_handle_ptr( obj );
2066 return hOldCursor;
2069 /***********************************************************************
2070 * ShowCursor (USER32.@)
2072 INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
2074 HCURSOR cursor;
2075 int increment = bShow ? 1 : -1;
2076 int count;
2078 SERVER_START_REQ( set_cursor )
2080 req->flags = SET_CURSOR_COUNT;
2081 req->show_count = increment;
2082 wine_server_call( req );
2083 cursor = wine_server_ptr_handle( reply->prev_handle );
2084 count = reply->prev_count + increment;
2086 SERVER_END_REQ;
2088 TRACE("%d, count=%d\n", bShow, count );
2090 if (bShow && !count) USER_Driver->pSetCursor( cursor );
2091 else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
2093 return count;
2096 /***********************************************************************
2097 * GetCursor (USER32.@)
2099 HCURSOR WINAPI GetCursor(void)
2101 HCURSOR ret;
2103 SERVER_START_REQ( set_cursor )
2105 req->flags = 0;
2106 wine_server_call( req );
2107 ret = wine_server_ptr_handle( reply->prev_handle );
2109 SERVER_END_REQ;
2110 return ret;
2114 /***********************************************************************
2115 * ClipCursor (USER32.@)
2117 BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
2119 UINT dpi;
2120 BOOL ret;
2121 RECT new_rect;
2123 TRACE( "Clipping to %s\n", wine_dbgstr_rect(rect) );
2125 if (rect)
2127 if (rect->left > rect->right || rect->top > rect->bottom) return FALSE;
2128 if ((dpi = get_thread_dpi()))
2130 new_rect = map_dpi_rect( *rect, dpi,
2131 get_monitor_dpi( MonitorFromRect( rect, MONITOR_DEFAULTTOPRIMARY )));
2132 rect = &new_rect;
2136 SERVER_START_REQ( set_cursor )
2138 req->clip_msg = WM_WINE_CLIPCURSOR;
2139 if (rect)
2141 req->flags = SET_CURSOR_CLIP;
2142 req->clip.left = rect->left;
2143 req->clip.top = rect->top;
2144 req->clip.right = rect->right;
2145 req->clip.bottom = rect->bottom;
2147 else req->flags = SET_CURSOR_NOCLIP;
2149 if ((ret = !wine_server_call( req )))
2151 new_rect.left = reply->new_clip.left;
2152 new_rect.top = reply->new_clip.top;
2153 new_rect.right = reply->new_clip.right;
2154 new_rect.bottom = reply->new_clip.bottom;
2157 SERVER_END_REQ;
2158 if (ret) USER_Driver->pClipCursor( &new_rect );
2159 return ret;
2163 /***********************************************************************
2164 * GetClipCursor (USER32.@)
2166 BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
2168 DPI_AWARENESS_CONTEXT context;
2169 UINT dpi;
2170 BOOL ret;
2172 if (!rect) return FALSE;
2174 SERVER_START_REQ( set_cursor )
2176 req->flags = 0;
2177 if ((ret = !wine_server_call( req )))
2179 rect->left = reply->new_clip.left;
2180 rect->top = reply->new_clip.top;
2181 rect->right = reply->new_clip.right;
2182 rect->bottom = reply->new_clip.bottom;
2185 SERVER_END_REQ;
2187 if (ret && (dpi = get_thread_dpi()))
2189 context = SetThreadDpiAwarenessContext( DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE );
2190 *rect = map_dpi_rect( *rect, get_monitor_dpi( MonitorFromRect( rect, MONITOR_DEFAULTTOPRIMARY )), dpi );
2191 SetThreadDpiAwarenessContext( context );
2193 return ret;
2197 /***********************************************************************
2198 * SetSystemCursor (USER32.@)
2200 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
2202 FIXME("(%p,%08x),stub!\n", hcur, id);
2203 return TRUE;
2207 /**********************************************************************
2208 * LookupIconIdFromDirectoryEx (USER32.@)
2210 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
2211 INT width, INT height, UINT cFlag )
2213 const CURSORICONDIR *dir = (const CURSORICONDIR*)xdir;
2214 UINT retVal = 0;
2215 if( dir && !dir->idReserved && (dir->idType & 3) )
2217 const CURSORICONDIRENTRY* entry;
2218 int depth = (cFlag & LR_MONOCHROME) ? 1 : get_display_bpp();
2220 if( bIcon )
2221 entry = CURSORICON_FindBestIconRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
2222 else
2223 entry = CURSORICON_FindBestCursorRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
2225 if( entry ) retVal = entry->wResId;
2227 else WARN_(cursor)("invalid resource directory\n");
2228 return retVal;
2231 /**********************************************************************
2232 * LookupIconIdFromDirectory (USER32.@)
2234 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
2236 return LookupIconIdFromDirectoryEx( dir, bIcon, 0, 0, bIcon ? 0 : LR_MONOCHROME );
2239 /***********************************************************************
2240 * LoadCursorW (USER32.@)
2242 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
2244 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2246 return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
2247 LR_SHARED | LR_DEFAULTSIZE );
2250 /***********************************************************************
2251 * LoadCursorA (USER32.@)
2253 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
2255 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2257 return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
2258 LR_SHARED | LR_DEFAULTSIZE );
2261 /***********************************************************************
2262 * LoadCursorFromFileW (USER32.@)
2264 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
2266 TRACE("%s\n", debugstr_w(name));
2268 return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
2269 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2272 /***********************************************************************
2273 * LoadCursorFromFileA (USER32.@)
2275 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
2277 TRACE("%s\n", debugstr_a(name));
2279 return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
2280 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2283 /***********************************************************************
2284 * LoadIconW (USER32.@)
2286 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
2288 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2290 return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
2291 LR_SHARED | LR_DEFAULTSIZE );
2294 /***********************************************************************
2295 * LoadIconA (USER32.@)
2297 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
2299 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2301 return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
2302 LR_SHARED | LR_DEFAULTSIZE );
2305 /**********************************************************************
2306 * GetCursorFrameInfo (USER32.@)
2308 * NOTES
2309 * So far no use has been found for the second parameter, it is currently presumed
2310 * that this parameter is reserved for future use.
2312 * PARAMS
2313 * hCursor [I] Handle to cursor for which to retrieve information
2314 * reserved [I] No purpose has been found for this parameter (may be NULL)
2315 * istep [I] The step of the cursor for which to retrieve information
2316 * rate_jiffies [O] Pointer to DWORD that receives the frame-specific delay (cannot be NULL)
2317 * num_steps [O] Pointer to DWORD that receives the number of steps in the cursor (cannot be NULL)
2319 * RETURNS
2320 * Success: Handle to a frame of the cursor (specified by istep)
2321 * Failure: NULL cursor (0)
2323 HCURSOR WINAPI GetCursorFrameInfo(HCURSOR hCursor, DWORD reserved, DWORD istep, DWORD *rate_jiffies, DWORD *num_steps)
2325 struct cursoricon_object *ptr;
2326 HCURSOR ret = 0;
2327 UINT icon_steps;
2329 if (rate_jiffies == NULL || num_steps == NULL) return 0;
2331 if (!(ptr = get_icon_ptr( hCursor ))) return 0;
2333 TRACE("%p => %d %d %p %p\n", hCursor, reserved, istep, rate_jiffies, num_steps);
2334 if (reserved != 0)
2335 FIXME("Second parameter non-zero (%d), please report this!\n", reserved);
2337 icon_steps = get_icon_steps(ptr);
2338 if (istep < icon_steps || !ptr->is_ani)
2340 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) ptr;
2341 UINT icon_frames = 1;
2343 if (ptr->is_ani)
2344 icon_frames = ani_icon_data->num_frames;
2345 if (ptr->is_ani && icon_frames > 1)
2346 ret = ani_icon_data->frames[istep];
2347 else
2348 ret = hCursor;
2349 if (icon_frames == 1)
2351 *rate_jiffies = 0;
2352 *num_steps = 1;
2354 else if (icon_steps == 1)
2356 *num_steps = ~0;
2357 *rate_jiffies = ptr->delay;
2359 else if (istep < icon_steps)
2361 struct cursoricon_frame *frame;
2363 *num_steps = icon_steps;
2364 frame = get_icon_frame( ptr, istep );
2365 if (get_icon_steps(ptr) == 1)
2366 *num_steps = ~0;
2367 else
2368 *num_steps = get_icon_steps(ptr);
2369 /* If this specific frame does not have a delay then use the global delay */
2370 if (frame->delay == ~0)
2371 *rate_jiffies = ptr->delay;
2372 else
2373 *rate_jiffies = frame->delay;
2374 release_icon_frame( ptr, frame );
2378 release_user_handle_ptr( ptr );
2380 return ret;
2383 /**********************************************************************
2384 * GetIconInfo (USER32.@)
2386 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
2388 ICONINFOEXW infoW;
2390 infoW.cbSize = sizeof(infoW);
2391 if (!GetIconInfoExW( hIcon, &infoW )) return FALSE;
2392 iconinfo->fIcon = infoW.fIcon;
2393 iconinfo->xHotspot = infoW.xHotspot;
2394 iconinfo->yHotspot = infoW.yHotspot;
2395 iconinfo->hbmColor = infoW.hbmColor;
2396 iconinfo->hbmMask = infoW.hbmMask;
2397 return TRUE;
2400 /**********************************************************************
2401 * GetIconInfoExA (USER32.@)
2403 BOOL WINAPI GetIconInfoExA( HICON icon, ICONINFOEXA *info )
2405 ICONINFOEXW infoW;
2407 if (info->cbSize != sizeof(*info))
2409 SetLastError( ERROR_INVALID_PARAMETER );
2410 return FALSE;
2412 infoW.cbSize = sizeof(infoW);
2413 if (!GetIconInfoExW( icon, &infoW )) return FALSE;
2414 info->fIcon = infoW.fIcon;
2415 info->xHotspot = infoW.xHotspot;
2416 info->yHotspot = infoW.yHotspot;
2417 info->hbmColor = infoW.hbmColor;
2418 info->hbmMask = infoW.hbmMask;
2419 info->wResID = infoW.wResID;
2420 WideCharToMultiByte( CP_ACP, 0, infoW.szModName, -1, info->szModName, MAX_PATH, NULL, NULL );
2421 WideCharToMultiByte( CP_ACP, 0, infoW.szResName, -1, info->szResName, MAX_PATH, NULL, NULL );
2422 return TRUE;
2425 /**********************************************************************
2426 * GetIconInfoExW (USER32.@)
2428 BOOL WINAPI GetIconInfoExW( HICON icon, ICONINFOEXW *info )
2430 struct cursoricon_frame *frame;
2431 struct cursoricon_object *ptr;
2432 HMODULE module;
2433 BOOL ret = TRUE;
2435 if (info->cbSize != sizeof(*info))
2437 SetLastError( ERROR_INVALID_PARAMETER );
2438 return FALSE;
2440 if (!(ptr = get_icon_ptr( icon )))
2442 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
2443 return FALSE;
2446 frame = get_icon_frame( ptr, 0 );
2447 if (!frame)
2449 release_user_handle_ptr( ptr );
2450 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
2451 return FALSE;
2454 TRACE("%p => %dx%d\n", icon, frame->width, frame->height);
2456 info->fIcon = ptr->is_icon;
2457 info->xHotspot = ptr->hotspot.x;
2458 info->yHotspot = ptr->hotspot.y;
2459 info->hbmColor = copy_bitmap( frame->color );
2460 info->hbmMask = copy_bitmap( frame->mask );
2461 info->wResID = 0;
2462 info->szModName[0] = 0;
2463 info->szResName[0] = 0;
2464 if (ptr->module)
2466 if (IS_INTRESOURCE( ptr->resname )) info->wResID = LOWORD( ptr->resname );
2467 else lstrcpynW( info->szResName, ptr->resname, MAX_PATH );
2469 if (!info->hbmMask || (!info->hbmColor && frame->color))
2471 DeleteObject( info->hbmMask );
2472 DeleteObject( info->hbmColor );
2473 ret = FALSE;
2475 module = ptr->module;
2476 release_icon_frame( ptr, frame );
2477 release_user_handle_ptr( ptr );
2478 if (ret && module) GetModuleFileNameW( module, info->szModName, MAX_PATH );
2479 return ret;
2482 /* copy an icon bitmap, even when it can't be selected into a DC */
2483 /* helper for CreateIconIndirect */
2484 static void stretch_blt_icon( HDC hdc_dst, int dst_x, int dst_y, int dst_width, int dst_height,
2485 HBITMAP src, int width, int height )
2487 HDC hdc = CreateCompatibleDC( 0 );
2489 if (!SelectObject( hdc, src )) /* do it the hard way */
2491 BITMAPINFO *info;
2492 void *bits;
2494 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) return;
2495 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2496 info->bmiHeader.biWidth = width;
2497 info->bmiHeader.biHeight = height;
2498 info->bmiHeader.biPlanes = GetDeviceCaps( hdc_dst, PLANES );
2499 info->bmiHeader.biBitCount = GetDeviceCaps( hdc_dst, BITSPIXEL );
2500 info->bmiHeader.biCompression = BI_RGB;
2501 info->bmiHeader.biSizeImage = get_dib_image_size( width, height, info->bmiHeader.biBitCount );
2502 info->bmiHeader.biXPelsPerMeter = 0;
2503 info->bmiHeader.biYPelsPerMeter = 0;
2504 info->bmiHeader.biClrUsed = 0;
2505 info->bmiHeader.biClrImportant = 0;
2506 bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
2507 if (bits && GetDIBits( hdc, src, 0, height, bits, info, DIB_RGB_COLORS ))
2508 StretchDIBits( hdc_dst, dst_x, dst_y, dst_width, dst_height,
2509 0, 0, width, height, bits, info, DIB_RGB_COLORS, SRCCOPY );
2511 HeapFree( GetProcessHeap(), 0, bits );
2512 HeapFree( GetProcessHeap(), 0, info );
2514 else StretchBlt( hdc_dst, dst_x, dst_y, dst_width, dst_height, hdc, 0, 0, width, height, SRCCOPY );
2516 DeleteDC( hdc );
2519 /**********************************************************************
2520 * CreateIconIndirect (USER32.@)
2522 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
2524 BITMAP bmpXor, bmpAnd;
2525 HICON hObj;
2526 HBITMAP color = 0, mask;
2527 int width, height;
2528 HDC hdc;
2530 TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
2531 iconinfo->hbmColor, iconinfo->hbmMask,
2532 iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
2534 if (!iconinfo->hbmMask) return 0;
2536 GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
2537 TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2538 bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
2539 bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
2541 if (iconinfo->hbmColor)
2543 GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2544 TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2545 bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
2546 bmpXor.bmPlanes, bmpXor.bmBitsPixel);
2548 width = bmpXor.bmWidth;
2549 height = bmpXor.bmHeight;
2550 if (bmpXor.bmPlanes * bmpXor.bmBitsPixel != 1 || bmpAnd.bmPlanes * bmpAnd.bmBitsPixel != 1)
2552 color = create_color_bitmap( width, height );
2553 mask = CreateBitmap( width, height, 1, 1, NULL );
2555 else mask = CreateBitmap( width, height * 2, 1, 1, NULL );
2557 else
2559 width = bmpAnd.bmWidth;
2560 height = bmpAnd.bmHeight;
2561 mask = CreateBitmap( width, height, 1, 1, NULL );
2564 hdc = CreateCompatibleDC( 0 );
2565 SelectObject( hdc, mask );
2566 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
2568 if (color)
2570 SelectObject( hdc, color );
2571 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
2573 else if (iconinfo->hbmColor)
2575 stretch_blt_icon( hdc, 0, height, width, height, iconinfo->hbmColor, width, height );
2577 else height /= 2;
2579 DeleteDC( hdc );
2581 hObj = alloc_icon_handle( FALSE, 0 );
2582 if (hObj)
2584 struct cursoricon_object *info = get_icon_ptr( hObj );
2585 struct cursoricon_frame *frame;
2587 info->is_icon = iconinfo->fIcon;
2588 frame = get_icon_frame( info, 0 );
2589 frame->delay = ~0;
2590 frame->width = width;
2591 frame->height = height;
2592 frame->color = color;
2593 frame->mask = mask;
2594 frame->alpha = create_alpha_bitmap( iconinfo->hbmColor, NULL, NULL );
2595 release_icon_frame( info, frame );
2596 if (info->is_icon)
2598 info->hotspot.x = width / 2;
2599 info->hotspot.y = height / 2;
2601 else
2603 info->hotspot.x = iconinfo->xHotspot;
2604 info->hotspot.y = iconinfo->yHotspot;
2607 release_user_handle_ptr( info );
2609 return hObj;
2612 /******************************************************************************
2613 * DrawIconEx (USER32.@) Draws an icon or cursor on device context
2615 * NOTES
2616 * Why is this using SM_CXICON instead of SM_CXCURSOR?
2618 * PARAMS
2619 * hdc [I] Handle to device context
2620 * x0 [I] X coordinate of upper left corner
2621 * y0 [I] Y coordinate of upper left corner
2622 * hIcon [I] Handle to icon to draw
2623 * cxWidth [I] Width of icon
2624 * cyWidth [I] Height of icon
2625 * istep [I] Index of frame in animated cursor
2626 * hbr [I] Handle to background brush
2627 * flags [I] Icon-drawing flags
2629 * RETURNS
2630 * Success: TRUE
2631 * Failure: FALSE
2633 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2634 INT cxWidth, INT cyWidth, UINT istep,
2635 HBRUSH hbr, UINT flags )
2637 struct cursoricon_frame *frame;
2638 struct cursoricon_object *ptr;
2639 HDC hdc_dest, hMemDC;
2640 BOOL result = FALSE, DoOffscreen;
2641 HBITMAP hB_off = 0;
2642 COLORREF oldFg, oldBg;
2643 INT x, y, nStretchMode;
2645 TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2646 hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2648 if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2649 if (istep >= get_icon_steps( ptr ))
2651 TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
2652 release_user_handle_ptr( ptr );
2653 return FALSE;
2655 if (!(frame = get_icon_frame( ptr, istep )))
2657 FIXME_(icon)("Error retrieving icon frame %d\n", istep);
2658 release_user_handle_ptr( ptr );
2659 return FALSE;
2661 if (!(hMemDC = CreateCompatibleDC( hdc )))
2663 release_icon_frame( ptr, frame );
2664 release_user_handle_ptr( ptr );
2665 return FALSE;
2668 if (flags & DI_NOMIRROR)
2669 FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
2671 /* Calculate the size of the destination image. */
2672 if (cxWidth == 0)
2674 if (flags & DI_DEFAULTSIZE)
2675 cxWidth = GetSystemMetrics (SM_CXICON);
2676 else
2677 cxWidth = frame->width;
2679 if (cyWidth == 0)
2681 if (flags & DI_DEFAULTSIZE)
2682 cyWidth = GetSystemMetrics (SM_CYICON);
2683 else
2684 cyWidth = frame->height;
2687 DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2689 if (DoOffscreen) {
2690 RECT r;
2692 SetRect(&r, 0, 0, cxWidth, cxWidth);
2694 if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
2695 if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
2697 DeleteDC( hdc_dest );
2698 goto failed;
2700 SelectObject(hdc_dest, hB_off);
2701 FillRect(hdc_dest, &r, hbr);
2702 x = y = 0;
2704 else
2706 hdc_dest = hdc;
2707 x = x0;
2708 y = y0;
2711 nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2713 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2714 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2716 if (frame->alpha && (flags & DI_IMAGE))
2718 BOOL alpha_blend = TRUE;
2720 if (GetObjectType( hdc_dest ) == OBJ_MEMDC)
2722 BITMAP bm;
2723 HBITMAP bmp = GetCurrentObject( hdc_dest, OBJ_BITMAP );
2724 alpha_blend = GetObjectW( bmp, sizeof(bm), &bm ) && bm.bmBitsPixel > 8;
2726 if (alpha_blend)
2728 BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2729 SelectObject( hMemDC, frame->alpha );
2730 if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
2731 0, 0, frame->width, frame->height,
2732 pixelblend )) goto done;
2736 if (flags & DI_MASK)
2738 DWORD rop = (flags & DI_IMAGE) ? SRCAND : SRCCOPY;
2739 SelectObject( hMemDC, frame->mask );
2740 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2741 hMemDC, 0, 0, frame->width, frame->height, rop );
2744 if (flags & DI_IMAGE)
2746 if (frame->color)
2748 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2749 SelectObject( hMemDC, frame->color );
2750 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2751 hMemDC, 0, 0, frame->width, frame->height, rop );
2753 else
2755 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2756 SelectObject( hMemDC, frame->mask );
2757 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2758 hMemDC, 0, frame->height, frame->width,
2759 frame->height, rop );
2763 done:
2764 if (DoOffscreen) BitBlt( hdc, x0, y0, cxWidth, cyWidth, hdc_dest, 0, 0, SRCCOPY );
2766 SetTextColor( hdc, oldFg );
2767 SetBkColor( hdc, oldBg );
2768 SetStretchBltMode (hdc, nStretchMode);
2769 result = TRUE;
2770 if (hdc_dest != hdc) DeleteDC( hdc_dest );
2771 if (hB_off) DeleteObject(hB_off);
2772 failed:
2773 DeleteDC( hMemDC );
2774 release_icon_frame( ptr, frame );
2775 release_user_handle_ptr( ptr );
2776 return result;
2779 /***********************************************************************
2780 * DIB_FixColorsToLoadflags
2782 * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2783 * are in loadflags
2785 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2787 int colors;
2788 COLORREF c_W, c_S, c_F, c_L, c_C;
2789 int incr,i;
2790 RGBQUAD *ptr;
2791 int bitmap_type;
2792 LONG width;
2793 LONG height;
2794 WORD bpp;
2795 DWORD compr;
2797 if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2799 WARN_(resource)("Invalid bitmap\n");
2800 return;
2803 if (bpp > 8) return;
2805 if (bitmap_type == 0) /* BITMAPCOREHEADER */
2807 incr = 3;
2808 colors = 1 << bpp;
2810 else
2812 incr = 4;
2813 colors = bmi->bmiHeader.biClrUsed;
2814 if (colors > 256) colors = 256;
2815 if (!colors && (bpp <= 8)) colors = 1 << bpp;
2818 c_W = GetSysColor(COLOR_WINDOW);
2819 c_S = GetSysColor(COLOR_3DSHADOW);
2820 c_F = GetSysColor(COLOR_3DFACE);
2821 c_L = GetSysColor(COLOR_3DLIGHT);
2823 if (loadflags & LR_LOADTRANSPARENT) {
2824 switch (bpp) {
2825 case 1: pix = pix >> 7; break;
2826 case 4: pix = pix >> 4; break;
2827 case 8: break;
2828 default:
2829 WARN_(resource)("(%d): Unsupported depth\n", bpp);
2830 return;
2832 if (pix >= colors) {
2833 WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2834 return;
2836 if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2837 ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2838 ptr->rgbBlue = GetBValue(c_W);
2839 ptr->rgbGreen = GetGValue(c_W);
2840 ptr->rgbRed = GetRValue(c_W);
2842 if (loadflags & LR_LOADMAP3DCOLORS)
2843 for (i=0; i<colors; i++) {
2844 ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2845 c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2846 if (c_C == RGB(128, 128, 128)) {
2847 ptr->rgbRed = GetRValue(c_S);
2848 ptr->rgbGreen = GetGValue(c_S);
2849 ptr->rgbBlue = GetBValue(c_S);
2850 } else if (c_C == RGB(192, 192, 192)) {
2851 ptr->rgbRed = GetRValue(c_F);
2852 ptr->rgbGreen = GetGValue(c_F);
2853 ptr->rgbBlue = GetBValue(c_F);
2854 } else if (c_C == RGB(223, 223, 223)) {
2855 ptr->rgbRed = GetRValue(c_L);
2856 ptr->rgbGreen = GetGValue(c_L);
2857 ptr->rgbBlue = GetBValue(c_L);
2863 /**********************************************************************
2864 * BITMAP_Load
2866 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2867 INT desiredx, INT desiredy, UINT loadflags )
2869 HBITMAP hbitmap = 0, orig_bm;
2870 HRSRC hRsrc;
2871 HGLOBAL handle;
2872 const char *ptr = NULL;
2873 BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2874 int size;
2875 BYTE pix;
2876 char *bits;
2877 LONG width, height, new_width, new_height;
2878 WORD bpp_dummy;
2879 DWORD compr_dummy, offbits = 0;
2880 INT bm_type;
2881 HDC screen_mem_dc = NULL;
2883 if (!(loadflags & LR_LOADFROMFILE))
2885 if (!instance)
2887 /* OEM bitmap: try to load the resource from user32.dll */
2888 instance = user32_module;
2891 if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2892 if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2894 if ((info = LockResource( handle )) == NULL) return 0;
2896 else
2898 BITMAPFILEHEADER * bmfh;
2900 if (!(ptr = map_fileW( name, NULL ))) return 0;
2901 info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2902 bmfh = (BITMAPFILEHEADER *)ptr;
2903 if (bmfh->bfType != 0x4d42 /* 'BM' */)
2905 WARN("Invalid/unsupported bitmap format!\n");
2906 goto end;
2908 if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2911 bm_type = DIB_GetBitmapInfo( &info->bmiHeader, &width, &height,
2912 &bpp_dummy, &compr_dummy);
2913 if (bm_type == -1)
2915 WARN("Invalid bitmap format!\n");
2916 goto end;
2919 size = bitmap_info_size(info, DIB_RGB_COLORS);
2920 fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2921 scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2923 if (!fix_info || !scaled_info) goto end;
2924 memcpy(fix_info, info, size);
2926 pix = *((LPBYTE)info + size);
2927 DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2929 memcpy(scaled_info, fix_info, size);
2931 if(desiredx != 0)
2932 new_width = desiredx;
2933 else
2934 new_width = width;
2936 if(desiredy != 0)
2937 new_height = height > 0 ? desiredy : -desiredy;
2938 else
2939 new_height = height;
2941 if(bm_type == 0)
2943 BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2944 core->bcWidth = new_width;
2945 core->bcHeight = new_height;
2947 else
2949 /* Some sanity checks for BITMAPINFO (not applicable to BITMAPCOREINFO) */
2950 if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
2951 WARN("Broken BitmapInfoHeader!\n");
2952 goto end;
2955 scaled_info->bmiHeader.biWidth = new_width;
2956 scaled_info->bmiHeader.biHeight = new_height;
2959 if (new_height < 0) new_height = -new_height;
2961 if (!(screen_mem_dc = CreateCompatibleDC( 0 ))) goto end;
2963 bits = (char *)info + (offbits ? offbits : size);
2965 if (loadflags & LR_CREATEDIBSECTION)
2967 scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2968 hbitmap = CreateDIBSection(0, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2970 else
2972 if (is_dib_monochrome(fix_info))
2973 hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2974 else
2975 hbitmap = create_color_bitmap(new_width, new_height);
2978 orig_bm = SelectObject(screen_mem_dc, hbitmap);
2979 if (info->bmiHeader.biBitCount > 1)
2980 SetStretchBltMode(screen_mem_dc, HALFTONE);
2981 StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2982 SelectObject(screen_mem_dc, orig_bm);
2984 end:
2985 if (screen_mem_dc) DeleteDC(screen_mem_dc);
2986 HeapFree(GetProcessHeap(), 0, scaled_info);
2987 HeapFree(GetProcessHeap(), 0, fix_info);
2988 if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2990 return hbitmap;
2993 /**********************************************************************
2994 * LoadImageA (USER32.@)
2996 * See LoadImageW.
2998 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2999 INT desiredx, INT desiredy, UINT loadflags)
3001 HANDLE res;
3002 LPWSTR u_name;
3004 if (IS_INTRESOURCE(name))
3005 return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
3007 __TRY {
3008 DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
3009 u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
3010 MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
3012 __EXCEPT_PAGE_FAULT {
3013 SetLastError( ERROR_INVALID_PARAMETER );
3014 return 0;
3016 __ENDTRY
3017 res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
3018 HeapFree(GetProcessHeap(), 0, u_name);
3019 return res;
3023 /******************************************************************************
3024 * LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
3026 * PARAMS
3027 * hinst [I] Handle of instance that contains image
3028 * name [I] Name of image
3029 * type [I] Type of image
3030 * desiredx [I] Desired width
3031 * desiredy [I] Desired height
3032 * loadflags [I] Load flags
3034 * RETURNS
3035 * Success: Handle to newly loaded image
3036 * Failure: NULL
3038 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
3040 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
3041 INT desiredx, INT desiredy, UINT loadflags )
3043 int depth;
3044 WCHAR path[MAX_PATH];
3046 TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
3047 hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
3049 if (loadflags & LR_LOADFROMFILE)
3051 loadflags &= ~LR_SHARED;
3052 /* relative paths are not only relative to the current working directory */
3053 if (SearchPathW(NULL, name, NULL, ARRAY_SIZE(path), path, NULL)) name = path;
3055 switch (type) {
3056 case IMAGE_BITMAP:
3057 return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
3059 case IMAGE_ICON:
3060 case IMAGE_CURSOR:
3061 depth = 1;
3062 if (!(loadflags & LR_MONOCHROME)) depth = get_display_bpp();
3063 return CURSORICON_Load(hinst, name, desiredx, desiredy, depth, (type == IMAGE_CURSOR), loadflags);
3065 return 0;
3068 /******************************************************************************
3069 * CopyImage (USER32.@) Creates new image and copies attributes to it
3071 * PARAMS
3072 * hnd [I] Handle to image to copy
3073 * type [I] Type of image to copy
3074 * desiredx [I] Desired width of new image
3075 * desiredy [I] Desired height of new image
3076 * flags [I] Copy flags
3078 * RETURNS
3079 * Success: Handle to newly created image
3080 * Failure: NULL
3082 * BUGS
3083 * Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
3084 * all other versions (95/2000/XP have been tested) ignore it.
3086 * NOTES
3087 * If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
3088 * a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
3089 * the copy will have the same depth as the screen.
3090 * The content of the image will only be copied if the bit depth of the
3091 * original image is compatible with the bit depth of the screen, or
3092 * if the source is a DIB section.
3093 * The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
3095 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
3096 INT desiredy, UINT flags )
3098 TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
3099 hnd, type, desiredx, desiredy, flags);
3101 switch (type)
3103 case IMAGE_BITMAP:
3105 HBITMAP res = NULL;
3106 DIBSECTION ds;
3107 int objSize;
3108 BITMAPINFO * bi;
3110 objSize = GetObjectW( hnd, sizeof(ds), &ds );
3111 if (!objSize) return 0;
3112 if ((desiredx < 0) || (desiredy < 0)) return 0;
3114 if (flags & LR_COPYFROMRESOURCE)
3116 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
3119 if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
3120 if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
3122 /* Allocate memory for a BITMAPINFOHEADER structure and a
3123 color table. The maximum number of colors in a color table
3124 is 256 which corresponds to a bitmap with depth 8.
3125 Bitmaps with higher depths don't have color tables. */
3126 bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
3127 if (!bi) return 0;
3129 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
3130 bi->bmiHeader.biPlanes = ds.dsBm.bmPlanes;
3131 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
3132 bi->bmiHeader.biCompression = BI_RGB;
3134 if (flags & LR_CREATEDIBSECTION)
3136 /* Create a DIB section. LR_MONOCHROME is ignored */
3137 void * bits;
3138 HDC dc = CreateCompatibleDC(NULL);
3140 if (objSize == sizeof(DIBSECTION))
3142 /* The source bitmap is a DIB.
3143 Get its attributes to create an exact copy */
3144 memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
3147 bi->bmiHeader.biWidth = desiredx;
3148 bi->bmiHeader.biHeight = desiredy;
3150 /* Get the color table or the color masks */
3151 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3153 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
3154 DeleteDC(dc);
3156 else
3158 /* Create a device-dependent bitmap */
3160 BOOL monochrome = (flags & LR_MONOCHROME);
3162 if (objSize == sizeof(DIBSECTION))
3164 /* The source bitmap is a DIB section.
3165 Get its attributes */
3166 HDC dc = CreateCompatibleDC(NULL);
3167 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
3168 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
3169 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3170 DeleteDC(dc);
3172 if (!monochrome && ds.dsBm.bmBitsPixel == 1)
3174 /* Look if the colors of the DIB are black and white */
3176 monochrome =
3177 (bi->bmiColors[0].rgbRed == 0xff
3178 && bi->bmiColors[0].rgbGreen == 0xff
3179 && bi->bmiColors[0].rgbBlue == 0xff
3180 && bi->bmiColors[0].rgbReserved == 0
3181 && bi->bmiColors[1].rgbRed == 0
3182 && bi->bmiColors[1].rgbGreen == 0
3183 && bi->bmiColors[1].rgbBlue == 0
3184 && bi->bmiColors[1].rgbReserved == 0)
3186 (bi->bmiColors[0].rgbRed == 0
3187 && bi->bmiColors[0].rgbGreen == 0
3188 && bi->bmiColors[0].rgbBlue == 0
3189 && bi->bmiColors[0].rgbReserved == 0
3190 && bi->bmiColors[1].rgbRed == 0xff
3191 && bi->bmiColors[1].rgbGreen == 0xff
3192 && bi->bmiColors[1].rgbBlue == 0xff
3193 && bi->bmiColors[1].rgbReserved == 0);
3196 else if (!monochrome)
3198 monochrome = ds.dsBm.bmBitsPixel == 1;
3201 if (monochrome)
3202 res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
3203 else
3204 res = create_color_bitmap(desiredx, desiredy);
3207 if (res)
3209 /* Only copy the bitmap if it's a DIB section or if it's
3210 compatible to the screen */
3211 if (objSize == sizeof(DIBSECTION) ||
3212 ds.dsBm.bmBitsPixel == 1 ||
3213 ds.dsBm.bmBitsPixel == get_display_bpp())
3215 /* The source bitmap may already be selected in a device context,
3216 use GetDIBits/StretchDIBits and not StretchBlt */
3218 HDC dc;
3219 void * bits;
3221 dc = CreateCompatibleDC(NULL);
3222 if (ds.dsBm.bmBitsPixel > 1)
3223 SetStretchBltMode(dc, HALFTONE);
3225 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
3226 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
3227 bi->bmiHeader.biSizeImage = 0;
3228 bi->bmiHeader.biClrUsed = 0;
3229 bi->bmiHeader.biClrImportant = 0;
3231 /* Fill in biSizeImage */
3232 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3233 bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
3235 if (bits)
3237 HBITMAP oldBmp;
3239 /* Get the image bits of the source bitmap */
3240 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
3242 /* Copy it to the destination bitmap */
3243 oldBmp = SelectObject(dc, res);
3244 StretchDIBits(dc, 0, 0, desiredx, desiredy,
3245 0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
3246 bits, bi, DIB_RGB_COLORS, SRCCOPY);
3247 SelectObject(dc, oldBmp);
3249 HeapFree(GetProcessHeap(), 0, bits);
3252 DeleteDC(dc);
3255 if (flags & LR_COPYDELETEORG)
3257 DeleteObject(hnd);
3260 HeapFree(GetProcessHeap(), 0, bi);
3261 return res;
3263 case IMAGE_ICON:
3264 case IMAGE_CURSOR:
3266 struct cursoricon_object *icon;
3267 HICON res = 0;
3268 int depth = (flags & LR_MONOCHROME) ? 1 : get_display_bpp();
3270 if (flags & LR_DEFAULTSIZE)
3272 if (!desiredx) desiredx = GetSystemMetrics( type == IMAGE_ICON ? SM_CXICON : SM_CXCURSOR );
3273 if (!desiredy) desiredy = GetSystemMetrics( type == IMAGE_ICON ? SM_CYICON : SM_CYCURSOR );
3276 if (!(icon = get_icon_ptr( hnd ))) return 0;
3278 if (icon->rsrc && (flags & LR_COPYFROMRESOURCE))
3279 res = CURSORICON_Load( icon->module, icon->resname, desiredx, desiredy, depth,
3280 !icon->is_icon, flags );
3281 else
3282 res = CopyIcon( hnd ); /* FIXME: change size if necessary */
3283 release_user_handle_ptr( icon );
3285 if (res && (flags & LR_COPYDELETEORG)) DeleteObject( hnd );
3286 return res;
3289 return 0;
3293 /******************************************************************************
3294 * LoadBitmapW (USER32.@) Loads bitmap from the executable file
3296 * RETURNS
3297 * Success: Handle to specified bitmap
3298 * Failure: NULL
3300 HBITMAP WINAPI LoadBitmapW(
3301 HINSTANCE instance, /* [in] Handle to application instance */
3302 LPCWSTR name) /* [in] Address of bitmap resource name */
3304 return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
3307 /**********************************************************************
3308 * LoadBitmapA (USER32.@)
3310 * See LoadBitmapW.
3312 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
3314 return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );