user32: Don't wait for other threads to process WM_NCDESTROY.
[wine.git] / dlls / user32 / cursoricon.c
blob0adb73bf564a34d6d05c20fa0b519484f84afa5f
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 BITMAPINFO *bmi_copy;
1148 BOOL ret = FALSE;
1149 BOOL do_stretch;
1150 HICON hObj = 0;
1151 HDC hdc = 0;
1152 LONG bmi_width, bmi_height;
1153 WORD bpp;
1154 DWORD compr;
1156 /* Check bitmap header */
1158 if (bmi->bmiHeader.biSize == PNG_SIGN)
1160 BITMAPINFO *bmi_png;
1162 bmi_png = load_png( (const char *)bmi, &maxsize );
1163 if (bmi_png)
1165 hObj = create_icon_from_bmi( bmi_png, maxsize, module, resname,
1166 rsrc, hotspot, bIcon, width, height, cFlag );
1167 HeapFree( GetProcessHeap(), 0, bmi_png );
1168 return hObj;
1170 return 0;
1173 if (maxsize < sizeof(BITMAPCOREHEADER))
1175 WARN( "invalid size %u\n", maxsize );
1176 return 0;
1178 if (maxsize < bmi->bmiHeader.biSize)
1180 WARN( "invalid header size %u\n", bmi->bmiHeader.biSize );
1181 return 0;
1183 if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
1184 (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER) ||
1185 (bmi->bmiHeader.biCompression != BI_RGB &&
1186 bmi->bmiHeader.biCompression != BI_BITFIELDS)) )
1188 WARN( "invalid bitmap header %u\n", bmi->bmiHeader.biSize );
1189 return 0;
1192 size = bitmap_info_size( bmi, DIB_RGB_COLORS );
1193 DIB_GetBitmapInfo(&bmi->bmiHeader, &bmi_width, &bmi_height, &bpp, &compr);
1194 color_size = get_dib_image_size( bmi_width, bmi_height / 2,
1195 bpp );
1196 mask_size = get_dib_image_size( bmi_width, bmi_height / 2, 1 );
1197 if (size > maxsize || color_size > maxsize - size)
1199 WARN( "truncated file %u < %u+%u+%u\n", maxsize, size, color_size, mask_size );
1200 return 0;
1202 if (mask_size > maxsize - size - color_size) mask_size = 0; /* no mask */
1204 if (cFlag & LR_DEFAULTSIZE)
1206 if (!width) width = GetSystemMetrics( bIcon ? SM_CXICON : SM_CXCURSOR );
1207 if (!height) height = GetSystemMetrics( bIcon ? SM_CYICON : SM_CYCURSOR );
1209 else
1211 if (!width) width = bmi_width;
1212 if (!height) height = bmi_height/2;
1214 do_stretch = (bmi_height/2 != height) ||
1215 (bmi_width != width);
1217 /* Scale the hotspot */
1218 if (bIcon)
1220 hotspot.x = width / 2;
1221 hotspot.y = height / 2;
1223 else if (do_stretch)
1225 hotspot.x = (hotspot.x * width) / bmi_width;
1226 hotspot.y = (hotspot.y * height) / (bmi_height / 2);
1229 if (!(bmi_copy = HeapAlloc( GetProcessHeap(), 0, max( size, FIELD_OFFSET( BITMAPINFO, bmiColors[2] )))))
1230 return 0;
1231 if (!(hdc = CreateCompatibleDC( 0 ))) goto done;
1233 memcpy( bmi_copy, bmi, size );
1234 if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
1235 bmi_copy->bmiHeader.biHeight /= 2;
1236 else
1237 ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcHeight /= 2;
1238 bmi_height /= 2;
1240 color_bits = (const char*)bmi + size;
1241 mask_bits = (const char*)color_bits + color_size;
1243 alpha = 0;
1244 if (is_dib_monochrome( bmi ))
1246 if (!(mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
1247 color = 0;
1249 /* copy color data into second half of mask bitmap */
1250 SelectObject( hdc, mask );
1251 StretchDIBits( hdc, 0, height, width, height,
1252 0, 0, bmi_width, bmi_height,
1253 color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1255 else
1257 if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
1258 if (!(color = create_color_bitmap( width, height )))
1260 DeleteObject( mask );
1261 goto done;
1263 SelectObject( hdc, color );
1264 StretchDIBits( hdc, 0, 0, width, height,
1265 0, 0, bmi_width, bmi_height,
1266 color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1268 if (bmi_has_alpha( bmi_copy, color_bits ))
1269 alpha = create_alpha_bitmap( color, bmi_copy, color_bits );
1271 /* convert info to monochrome to copy the mask */
1272 if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
1274 RGBQUAD *rgb = bmi_copy->bmiColors;
1276 bmi_copy->bmiHeader.biBitCount = 1;
1277 bmi_copy->bmiHeader.biClrUsed = bmi_copy->bmiHeader.biClrImportant = 2;
1278 rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
1279 rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
1280 rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
1282 else
1284 RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)bmi_copy) + 1);
1286 ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcBitCount = 1;
1287 rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
1288 rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
1292 if (mask_size)
1294 SelectObject( hdc, mask );
1295 StretchDIBits( hdc, 0, 0, width, height,
1296 0, 0, bmi_width, bmi_height,
1297 mask_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1299 ret = TRUE;
1301 done:
1302 DeleteDC( hdc );
1303 HeapFree( GetProcessHeap(), 0, bmi_copy );
1305 if (ret)
1306 hObj = alloc_icon_handle( FALSE, 0 );
1307 if (hObj)
1309 struct cursoricon_object *info = get_icon_ptr( hObj );
1310 struct cursoricon_frame *frame;
1312 info->is_icon = bIcon;
1313 info->module = module;
1314 info->hotspot = hotspot;
1315 frame = get_icon_frame( info, 0 );
1316 frame->delay = ~0;
1317 frame->width = width;
1318 frame->height = height;
1319 frame->color = color;
1320 frame->mask = mask;
1321 frame->alpha = alpha;
1322 release_icon_frame( info, frame );
1323 if (!IS_INTRESOURCE(resname))
1325 info->resname = HeapAlloc( GetProcessHeap(), 0, (strlenW(resname) + 1) * sizeof(WCHAR) );
1326 if (info->resname) strcpyW( info->resname, resname );
1328 else info->resname = MAKEINTRESOURCEW( LOWORD(resname) );
1330 if (module && (cFlag & LR_SHARED))
1332 info->rsrc = rsrc;
1333 list_add_head( &icon_cache, &info->entry );
1335 release_user_handle_ptr( info );
1337 else
1339 DeleteObject( color );
1340 DeleteObject( alpha );
1341 DeleteObject( mask );
1343 return hObj;
1347 /**********************************************************************
1348 * .ANI cursor support
1350 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
1351 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
1352 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
1353 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
1354 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
1355 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
1356 #define ANI_rate_ID RIFF_FOURCC('r', 'a', 't', 'e')
1358 #define ANI_FLAG_ICON 0x1
1359 #define ANI_FLAG_SEQUENCE 0x2
1361 typedef struct {
1362 DWORD header_size;
1363 DWORD num_frames;
1364 DWORD num_steps;
1365 DWORD width;
1366 DWORD height;
1367 DWORD bpp;
1368 DWORD num_planes;
1369 DWORD display_rate;
1370 DWORD flags;
1371 } ani_header;
1373 typedef struct {
1374 DWORD data_size;
1375 const unsigned char *data;
1376 } riff_chunk_t;
1378 static void dump_ani_header( const ani_header *header )
1380 TRACE(" header size: %d\n", header->header_size);
1381 TRACE(" frames: %d\n", header->num_frames);
1382 TRACE(" steps: %d\n", header->num_steps);
1383 TRACE(" width: %d\n", header->width);
1384 TRACE(" height: %d\n", header->height);
1385 TRACE(" bpp: %d\n", header->bpp);
1386 TRACE(" planes: %d\n", header->num_planes);
1387 TRACE(" display rate: %d\n", header->display_rate);
1388 TRACE(" flags: 0x%08x\n", header->flags);
1393 * RIFF:
1394 * DWORD "RIFF"
1395 * DWORD size
1396 * DWORD riff_id
1397 * BYTE[] data
1399 * LIST:
1400 * DWORD "LIST"
1401 * DWORD size
1402 * DWORD list_id
1403 * BYTE[] data
1405 * CHUNK:
1406 * DWORD chunk_id
1407 * DWORD size
1408 * BYTE[] data
1410 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
1412 const unsigned char *ptr = parent_chunk->data;
1413 const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
1415 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
1417 while (ptr < end)
1419 if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
1420 || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1422 ptr += sizeof(DWORD);
1423 chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1424 ptr += sizeof(DWORD);
1425 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
1426 chunk->data = ptr;
1428 return;
1431 ptr += sizeof(DWORD);
1432 ptr += (*(const DWORD *)ptr + 1) & ~1;
1433 ptr += sizeof(DWORD);
1439 * .ANI layout:
1441 * RIFF:'ACON' RIFF chunk
1442 * |- CHUNK:'anih' Header
1443 * |- CHUNK:'seq ' Sequence information (optional)
1444 * \- LIST:'fram' Frame list
1445 * |- CHUNK:icon Cursor frames
1446 * |- CHUNK:icon
1447 * |- ...
1448 * \- CHUNK:icon
1450 static HCURSOR CURSORICON_CreateIconFromANI( const BYTE *bits, DWORD bits_size, INT width, INT height,
1451 INT depth, BOOL is_icon, UINT loadflags )
1453 struct animated_cursoricon_object *ani_icon_data;
1454 struct cursoricon_object *info;
1455 DWORD *frame_rates = NULL;
1456 DWORD *frame_seq = NULL;
1457 ani_header header;
1458 BOOL use_seq = FALSE;
1459 HCURSOR cursor;
1460 UINT i;
1461 BOOL error = FALSE;
1462 HICON *frames;
1464 riff_chunk_t root_chunk = { bits_size, bits };
1465 riff_chunk_t ACON_chunk = {0};
1466 riff_chunk_t anih_chunk = {0};
1467 riff_chunk_t fram_chunk = {0};
1468 riff_chunk_t rate_chunk = {0};
1469 riff_chunk_t seq_chunk = {0};
1470 const unsigned char *icon_chunk;
1471 const unsigned char *icon_data;
1473 TRACE("bits %p, bits_size %d\n", bits, bits_size);
1475 riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1476 if (!ACON_chunk.data)
1478 ERR("Failed to get root chunk.\n");
1479 return 0;
1482 riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1483 if (!anih_chunk.data)
1485 ERR("Failed to get 'anih' chunk.\n");
1486 return 0;
1488 memcpy( &header, anih_chunk.data, sizeof(header) );
1489 dump_ani_header( &header );
1491 if (!(header.flags & ANI_FLAG_ICON))
1493 FIXME("Raw animated icon/cursor data is not currently supported.\n");
1494 return 0;
1497 if (header.flags & ANI_FLAG_SEQUENCE)
1499 riff_find_chunk( ANI_seq__ID, 0, &ACON_chunk, &seq_chunk );
1500 if (seq_chunk.data)
1502 frame_seq = (DWORD *) seq_chunk.data;
1503 use_seq = TRUE;
1505 else
1507 FIXME("Sequence data expected but not found, assuming steps == frames.\n");
1508 header.num_steps = header.num_frames;
1512 riff_find_chunk( ANI_rate_ID, 0, &ACON_chunk, &rate_chunk );
1513 if (rate_chunk.data)
1514 frame_rates = (DWORD *) rate_chunk.data;
1516 riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1517 if (!fram_chunk.data)
1519 ERR("Failed to get icon list.\n");
1520 return 0;
1523 cursor = alloc_icon_handle( TRUE, header.num_steps );
1524 if (!cursor) return 0;
1525 frames = HeapAlloc( GetProcessHeap(), 0, sizeof(*frames) * header.num_frames );
1526 if (!frames)
1528 free_icon_handle( cursor );
1529 return 0;
1532 info = get_icon_ptr( cursor );
1533 ani_icon_data = (struct animated_cursoricon_object *) info;
1534 info->is_icon = is_icon;
1535 ani_icon_data->num_frames = header.num_frames;
1537 /* The .ANI stores the display rate in jiffies (1/60s) */
1538 info->delay = header.display_rate;
1540 icon_chunk = fram_chunk.data;
1541 icon_data = fram_chunk.data + (2 * sizeof(DWORD));
1542 for (i=0; i<header.num_frames; i++)
1544 const DWORD chunk_size = *(const DWORD *)(icon_chunk + sizeof(DWORD));
1545 const CURSORICONFILEDIRENTRY *entry;
1546 INT frameWidth, frameHeight;
1547 const BITMAPINFO *bmi;
1549 entry = CURSORICON_FindBestIconFile((const CURSORICONFILEDIR *) icon_data,
1550 bits + bits_size - icon_data,
1551 width, height, depth, loadflags );
1553 info->hotspot.x = entry->xHotspot;
1554 info->hotspot.y = entry->yHotspot;
1555 if (!header.width || !header.height)
1557 frameWidth = entry->bWidth;
1558 frameHeight = entry->bHeight;
1560 else
1562 frameWidth = header.width;
1563 frameHeight = header.height;
1566 frames[i] = NULL;
1567 if (entry->dwDIBOffset < bits + bits_size - icon_data)
1569 bmi = (const BITMAPINFO *) (icon_data + entry->dwDIBOffset);
1570 /* Grab a frame from the animation */
1571 frames[i] = create_icon_from_bmi( bmi, bits + bits_size - (const BYTE *)bmi,
1572 NULL, NULL, NULL, info->hotspot,
1573 is_icon, frameWidth, frameHeight, loadflags );
1576 if (!frames[i])
1578 FIXME_(cursor)("failed to convert animated cursor frame.\n");
1579 error = TRUE;
1580 if (i == 0)
1582 FIXME_(cursor)("Completely failed to create animated cursor!\n");
1583 ani_icon_data->num_frames = 0;
1584 release_user_handle_ptr( info );
1585 free_icon_handle( cursor );
1586 HeapFree( GetProcessHeap(), 0, frames );
1587 return 0;
1589 break;
1592 /* Advance to the next chunk */
1593 icon_chunk += chunk_size + (2 * sizeof(DWORD));
1594 icon_data = icon_chunk + (2 * sizeof(DWORD));
1597 /* There was an error but we at least decoded the first frame, so just use that frame */
1598 if (error)
1600 FIXME_(cursor)("Error creating animated cursor, only using first frame!\n");
1601 for (i=1; i<ani_icon_data->num_frames; i++)
1602 free_icon_handle( ani_icon_data->frames[i] );
1603 use_seq = FALSE;
1604 info->delay = 0;
1605 ani_icon_data->num_steps = 1;
1606 ani_icon_data->num_frames = 1;
1609 /* Setup the animated frames in the correct sequence */
1610 for (i=0; i<ani_icon_data->num_steps; i++)
1612 DWORD frame_id = use_seq ? frame_seq[i] : i;
1613 struct cursoricon_frame *frame;
1615 if (frame_id >= ani_icon_data->num_frames)
1617 frame_id = ani_icon_data->num_frames-1;
1618 ERR_(cursor)("Sequence indicates frame past end of list, corrupt?\n");
1620 ani_icon_data->frames[i] = frames[frame_id];
1621 frame = get_icon_frame( info, i );
1622 if (frame_rates)
1623 frame->delay = frame_rates[i];
1624 else
1625 frame->delay = ~0;
1626 release_icon_frame( info, frame );
1629 HeapFree( GetProcessHeap(), 0, frames );
1630 release_user_handle_ptr( info );
1632 return cursor;
1636 /**********************************************************************
1637 * CreateIconFromResourceEx (USER32.@)
1639 * FIXME: Convert to mono when cFlag is LR_MONOCHROME.
1641 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1642 BOOL bIcon, DWORD dwVersion,
1643 INT width, INT height,
1644 UINT cFlag )
1646 POINT hotspot;
1647 const BITMAPINFO *bmi;
1649 TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s %s\n",
1650 bits, cbSize, dwVersion, width, height,
1651 bIcon ? "icon" : "cursor", (cFlag & LR_MONOCHROME) ? "mono" : "" );
1653 if (!bits) return 0;
1655 if (dwVersion == 0x00020000)
1657 FIXME_(cursor)("\t2.xx resources are not supported\n");
1658 return 0;
1661 /* Check if the resource is an animated icon/cursor */
1662 if (!memcmp(bits, "RIFF", 4))
1663 return CURSORICON_CreateIconFromANI( bits, cbSize, width, height,
1664 0 /* default depth */, bIcon, cFlag );
1666 if (bIcon)
1668 hotspot.x = width / 2;
1669 hotspot.y = height / 2;
1670 bmi = (BITMAPINFO *)bits;
1672 else /* get the hotspot */
1674 const SHORT *pt = (const SHORT *)bits;
1675 hotspot.x = pt[0];
1676 hotspot.y = pt[1];
1677 bmi = (const BITMAPINFO *)(pt + 2);
1678 cbSize -= 2 * sizeof(*pt);
1681 return create_icon_from_bmi( bmi, cbSize, NULL, NULL, NULL, hotspot, bIcon, width, height, cFlag );
1685 /**********************************************************************
1686 * CreateIconFromResource (USER32.@)
1688 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1689 BOOL bIcon, DWORD dwVersion)
1691 return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
1695 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1696 INT width, INT height, INT depth,
1697 BOOL fCursor, UINT loadflags)
1699 const CURSORICONFILEDIRENTRY *entry;
1700 const CURSORICONFILEDIR *dir;
1701 DWORD filesize = 0;
1702 HICON hIcon = 0;
1703 const BYTE *bits;
1704 POINT hotspot;
1706 TRACE("loading %s\n", debugstr_w( filename ));
1708 bits = map_fileW( filename, &filesize );
1709 if (!bits)
1710 return hIcon;
1712 /* Check for .ani. */
1713 if (memcmp( bits, "RIFF", 4 ) == 0)
1715 hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height, depth, !fCursor, loadflags );
1716 goto end;
1719 dir = (const CURSORICONFILEDIR*) bits;
1720 if ( filesize < FIELD_OFFSET( CURSORICONFILEDIR, idEntries[dir->idCount] ))
1721 goto end;
1723 if ( fCursor )
1724 entry = CURSORICON_FindBestCursorFile( dir, filesize, width, height, depth, loadflags );
1725 else
1726 entry = CURSORICON_FindBestIconFile( dir, filesize, width, height, depth, loadflags );
1728 if ( !entry )
1729 goto end;
1731 /* check that we don't run off the end of the file */
1732 if ( entry->dwDIBOffset > filesize )
1733 goto end;
1734 if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1735 goto end;
1737 hotspot.x = entry->xHotspot;
1738 hotspot.y = entry->yHotspot;
1739 hIcon = create_icon_from_bmi( (const BITMAPINFO *)&bits[entry->dwDIBOffset], filesize - entry->dwDIBOffset,
1740 NULL, NULL, NULL, hotspot, !fCursor, width, height, loadflags );
1741 end:
1742 TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1743 UnmapViewOfFile( bits );
1744 return hIcon;
1747 /**********************************************************************
1748 * CURSORICON_Load
1750 * Load a cursor or icon from resource or file.
1752 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1753 INT width, INT height, INT depth,
1754 BOOL fCursor, UINT loadflags)
1756 HANDLE handle = 0;
1757 HICON hIcon = 0;
1758 HRSRC hRsrc;
1759 DWORD size;
1760 const CURSORICONDIR *dir;
1761 const CURSORICONDIRENTRY *dirEntry;
1762 const BYTE *bits;
1763 WORD wResId;
1764 POINT hotspot;
1766 TRACE("%p, %s, %dx%d, depth %d, fCursor %d, flags 0x%04x\n",
1767 hInstance, debugstr_w(name), width, height, depth, fCursor, loadflags);
1769 if ( loadflags & LR_LOADFROMFILE ) /* Load from file */
1770 return CURSORICON_LoadFromFile( name, width, height, depth, fCursor, loadflags );
1772 if (!hInstance) hInstance = user32_module; /* Load OEM cursor/icon */
1774 /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1775 if ((ULONG_PTR)hInstance >> 16 == 0) loadflags &= ~LR_SHARED;
1777 /* Get directory resource ID */
1779 if (!(hRsrc = FindResourceW( hInstance, name,
1780 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1782 /* try animated resource */
1783 if (!(hRsrc = FindResourceW( hInstance, name,
1784 (LPWSTR)(fCursor ? RT_ANICURSOR : RT_ANIICON) ))) return 0;
1785 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1786 bits = LockResource( handle );
1787 return CURSORICON_CreateIconFromANI( bits, SizeofResource( hInstance, handle ),
1788 width, height, depth, !fCursor, loadflags );
1791 /* Find the best entry in the directory */
1793 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1794 if (!(dir = LockResource( handle ))) return 0;
1795 size = SizeofResource( hInstance, hRsrc );
1796 if (fCursor)
1797 dirEntry = CURSORICON_FindBestCursorRes( dir, size, width, height, depth, loadflags );
1798 else
1799 dirEntry = CURSORICON_FindBestIconRes( dir, size, width, height, depth, loadflags );
1800 if (!dirEntry) return 0;
1801 wResId = dirEntry->wResId;
1802 FreeResource( handle );
1804 /* Load the resource */
1806 if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1807 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1809 /* If shared icon, check whether it was already loaded */
1810 if (loadflags & LR_SHARED)
1812 struct cursoricon_object *ptr;
1814 USER_Lock();
1815 LIST_FOR_EACH_ENTRY( ptr, &icon_cache, struct cursoricon_object, entry )
1817 if (ptr->module != hInstance) continue;
1818 if (ptr->rsrc != hRsrc) continue;
1819 hIcon = ptr->obj.handle;
1820 break;
1822 USER_Unlock();
1823 if (hIcon) return hIcon;
1826 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1827 size = SizeofResource( hInstance, hRsrc );
1828 bits = LockResource( handle );
1830 if (!fCursor)
1832 hotspot.x = width / 2;
1833 hotspot.y = height / 2;
1835 else /* get the hotspot */
1837 const SHORT *pt = (const SHORT *)bits;
1838 hotspot.x = pt[0];
1839 hotspot.y = pt[1];
1840 bits += 2 * sizeof(SHORT);
1841 size -= 2 * sizeof(SHORT);
1843 hIcon = create_icon_from_bmi( (const BITMAPINFO *)bits, size, hInstance, name, hRsrc,
1844 hotspot, !fCursor, width, height, loadflags );
1845 FreeResource( handle );
1846 return hIcon;
1850 /***********************************************************************
1851 * CreateCursor (USER32.@)
1853 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
1854 INT xHotSpot, INT yHotSpot,
1855 INT nWidth, INT nHeight,
1856 LPCVOID lpANDbits, LPCVOID lpXORbits )
1858 ICONINFO info;
1859 HCURSOR hCursor;
1861 TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
1862 nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1864 info.fIcon = FALSE;
1865 info.xHotspot = xHotSpot;
1866 info.yHotspot = yHotSpot;
1867 info.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1868 info.hbmColor = CreateBitmap( nWidth, nHeight, 1, 1, lpXORbits );
1869 hCursor = CreateIconIndirect( &info );
1870 DeleteObject( info.hbmMask );
1871 DeleteObject( info.hbmColor );
1872 return hCursor;
1876 /***********************************************************************
1877 * CreateIcon (USER32.@)
1879 * Creates an icon based on the specified bitmaps. The bitmaps must be
1880 * provided in a device dependent format and will be resized to
1881 * (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1882 * depth. The provided bitmaps must be top-down bitmaps.
1883 * Although Windows does not support 15bpp(*) this API must support it
1884 * for Winelib applications.
1886 * (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1887 * format!
1889 * RETURNS
1890 * Success: handle to an icon
1891 * Failure: NULL
1893 * FIXME: Do we need to resize the bitmaps?
1895 HICON WINAPI CreateIcon(
1896 HINSTANCE hInstance, /* [in] the application's hInstance */
1897 INT nWidth, /* [in] the width of the provided bitmaps */
1898 INT nHeight, /* [in] the height of the provided bitmaps */
1899 BYTE bPlanes, /* [in] the number of planes in the provided bitmaps */
1900 BYTE bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1901 LPCVOID lpANDbits, /* [in] a monochrome bitmap representing the icon's mask */
1902 LPCVOID lpXORbits) /* [in] the icon's 'color' bitmap */
1904 ICONINFO iinfo;
1905 HICON hIcon;
1907 TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
1908 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1910 iinfo.fIcon = TRUE;
1911 iinfo.xHotspot = nWidth / 2;
1912 iinfo.yHotspot = nHeight / 2;
1913 iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1914 iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );
1916 hIcon = CreateIconIndirect( &iinfo );
1918 DeleteObject( iinfo.hbmMask );
1919 DeleteObject( iinfo.hbmColor );
1921 return hIcon;
1925 /***********************************************************************
1926 * CopyIcon (USER32.@)
1928 HICON WINAPI CopyIcon( HICON hIcon )
1930 struct cursoricon_object *ptrOld, *ptrNew;
1931 HICON hNew;
1933 if (!(ptrOld = get_icon_ptr( hIcon )))
1935 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
1936 return 0;
1938 if ((hNew = alloc_icon_handle( FALSE, 0 )))
1940 struct cursoricon_frame *frameOld, *frameNew;
1942 ptrNew = get_icon_ptr( hNew );
1943 ptrNew->is_icon = ptrOld->is_icon;
1944 ptrNew->hotspot = ptrOld->hotspot;
1945 if (!(frameOld = get_icon_frame( ptrOld, 0 )))
1947 release_user_handle_ptr( ptrOld );
1948 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
1949 return 0;
1951 if (!(frameNew = get_icon_frame( ptrNew, 0 )))
1953 release_icon_frame( ptrOld, frameOld );
1954 release_user_handle_ptr( ptrOld );
1955 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
1956 return 0;
1958 frameNew->delay = 0;
1959 frameNew->width = frameOld->width;
1960 frameNew->height = frameOld->height;
1961 frameNew->mask = copy_bitmap( frameOld->mask );
1962 frameNew->color = copy_bitmap( frameOld->color );
1963 frameNew->alpha = copy_bitmap( frameOld->alpha );
1964 release_icon_frame( ptrOld, frameOld );
1965 release_icon_frame( ptrNew, frameNew );
1966 release_user_handle_ptr( ptrNew );
1968 release_user_handle_ptr( ptrOld );
1969 return hNew;
1973 /***********************************************************************
1974 * DestroyIcon (USER32.@)
1976 BOOL WINAPI DestroyIcon( HICON hIcon )
1978 BOOL ret = FALSE;
1979 struct cursoricon_object *obj = get_icon_ptr( hIcon );
1981 TRACE_(icon)("%p\n", hIcon );
1983 if (obj)
1985 BOOL shared = (obj->rsrc != NULL);
1986 release_user_handle_ptr( obj );
1987 ret = (GetCursor() != hIcon);
1988 if (!shared) free_icon_handle( hIcon );
1990 return ret;
1994 /***********************************************************************
1995 * DestroyCursor (USER32.@)
1997 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
1999 return DestroyIcon( hCursor );
2002 /***********************************************************************
2003 * DrawIcon (USER32.@)
2005 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
2007 return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
2010 /***********************************************************************
2011 * SetCursor (USER32.@)
2013 * Set the cursor shape.
2015 * RETURNS
2016 * A handle to the previous cursor shape.
2018 HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
2020 struct cursoricon_object *obj;
2021 HCURSOR hOldCursor;
2022 int show_count;
2023 BOOL ret;
2025 TRACE("%p\n", hCursor);
2027 SERVER_START_REQ( set_cursor )
2029 req->flags = SET_CURSOR_HANDLE;
2030 req->handle = wine_server_user_handle( hCursor );
2031 if ((ret = !wine_server_call_err( req )))
2033 hOldCursor = wine_server_ptr_handle( reply->prev_handle );
2034 show_count = reply->prev_count;
2037 SERVER_END_REQ;
2039 if (!ret) return 0;
2040 USER_Driver->pSetCursor( show_count >= 0 ? hCursor : 0 );
2042 if (!(obj = get_icon_ptr( hOldCursor ))) return 0;
2043 release_user_handle_ptr( obj );
2044 return hOldCursor;
2047 /***********************************************************************
2048 * ShowCursor (USER32.@)
2050 INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
2052 HCURSOR cursor;
2053 int increment = bShow ? 1 : -1;
2054 int count;
2056 SERVER_START_REQ( set_cursor )
2058 req->flags = SET_CURSOR_COUNT;
2059 req->show_count = increment;
2060 wine_server_call( req );
2061 cursor = wine_server_ptr_handle( reply->prev_handle );
2062 count = reply->prev_count + increment;
2064 SERVER_END_REQ;
2066 TRACE("%d, count=%d\n", bShow, count );
2068 if (bShow && !count) USER_Driver->pSetCursor( cursor );
2069 else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
2071 return count;
2074 /***********************************************************************
2075 * GetCursor (USER32.@)
2077 HCURSOR WINAPI GetCursor(void)
2079 HCURSOR ret;
2081 SERVER_START_REQ( set_cursor )
2083 req->flags = 0;
2084 wine_server_call( req );
2085 ret = wine_server_ptr_handle( reply->prev_handle );
2087 SERVER_END_REQ;
2088 return ret;
2092 /***********************************************************************
2093 * ClipCursor (USER32.@)
2095 BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
2097 BOOL ret;
2098 RECT new_rect;
2100 TRACE( "Clipping to %s\n", wine_dbgstr_rect(rect) );
2102 if (rect && (rect->left > rect->right || rect->top > rect->bottom)) return FALSE;
2104 SERVER_START_REQ( set_cursor )
2106 req->clip_msg = WM_WINE_CLIPCURSOR;
2107 if (rect)
2109 req->flags = SET_CURSOR_CLIP;
2110 req->clip.left = rect->left;
2111 req->clip.top = rect->top;
2112 req->clip.right = rect->right;
2113 req->clip.bottom = rect->bottom;
2115 else req->flags = SET_CURSOR_NOCLIP;
2117 if ((ret = !wine_server_call( req )))
2119 new_rect.left = reply->new_clip.left;
2120 new_rect.top = reply->new_clip.top;
2121 new_rect.right = reply->new_clip.right;
2122 new_rect.bottom = reply->new_clip.bottom;
2125 SERVER_END_REQ;
2126 if (ret) USER_Driver->pClipCursor( &new_rect );
2127 return ret;
2131 /***********************************************************************
2132 * GetClipCursor (USER32.@)
2134 BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
2136 BOOL ret;
2138 if (!rect) return FALSE;
2140 SERVER_START_REQ( set_cursor )
2142 req->flags = 0;
2143 if ((ret = !wine_server_call( req )))
2145 rect->left = reply->new_clip.left;
2146 rect->top = reply->new_clip.top;
2147 rect->right = reply->new_clip.right;
2148 rect->bottom = reply->new_clip.bottom;
2151 SERVER_END_REQ;
2152 return ret;
2156 /***********************************************************************
2157 * SetSystemCursor (USER32.@)
2159 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
2161 FIXME("(%p,%08x),stub!\n", hcur, id);
2162 return TRUE;
2166 /**********************************************************************
2167 * LookupIconIdFromDirectoryEx (USER32.@)
2169 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
2170 INT width, INT height, UINT cFlag )
2172 const CURSORICONDIR *dir = (const CURSORICONDIR*)xdir;
2173 UINT retVal = 0;
2174 if( dir && !dir->idReserved && (dir->idType & 3) )
2176 const CURSORICONDIRENTRY* entry;
2177 int depth = (cFlag & LR_MONOCHROME) ? 1 : get_display_bpp();
2179 if( bIcon )
2180 entry = CURSORICON_FindBestIconRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
2181 else
2182 entry = CURSORICON_FindBestCursorRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
2184 if( entry ) retVal = entry->wResId;
2186 else WARN_(cursor)("invalid resource directory\n");
2187 return retVal;
2190 /**********************************************************************
2191 * LookupIconIdFromDirectory (USER32.@)
2193 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
2195 return LookupIconIdFromDirectoryEx( dir, bIcon, 0, 0, bIcon ? 0 : LR_MONOCHROME );
2198 /***********************************************************************
2199 * LoadCursorW (USER32.@)
2201 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
2203 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2205 return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
2206 LR_SHARED | LR_DEFAULTSIZE );
2209 /***********************************************************************
2210 * LoadCursorA (USER32.@)
2212 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
2214 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2216 return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
2217 LR_SHARED | LR_DEFAULTSIZE );
2220 /***********************************************************************
2221 * LoadCursorFromFileW (USER32.@)
2223 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
2225 TRACE("%s\n", debugstr_w(name));
2227 return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
2228 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2231 /***********************************************************************
2232 * LoadCursorFromFileA (USER32.@)
2234 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
2236 TRACE("%s\n", debugstr_a(name));
2238 return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
2239 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2242 /***********************************************************************
2243 * LoadIconW (USER32.@)
2245 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
2247 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2249 return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
2250 LR_SHARED | LR_DEFAULTSIZE );
2253 /***********************************************************************
2254 * LoadIconA (USER32.@)
2256 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
2258 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2260 return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
2261 LR_SHARED | LR_DEFAULTSIZE );
2264 /**********************************************************************
2265 * GetCursorFrameInfo (USER32.@)
2267 * NOTES
2268 * So far no use has been found for the second parameter, it is currently presumed
2269 * that this parameter is reserved for future use.
2271 * PARAMS
2272 * hCursor [I] Handle to cursor for which to retrieve information
2273 * reserved [I] No purpose has been found for this parameter (may be NULL)
2274 * istep [I] The step of the cursor for which to retrieve information
2275 * rate_jiffies [O] Pointer to DWORD that receives the frame-specific delay (cannot be NULL)
2276 * num_steps [O] Pointer to DWORD that receives the number of steps in the cursor (cannot be NULL)
2278 * RETURNS
2279 * Success: Handle to a frame of the cursor (specified by istep)
2280 * Failure: NULL cursor (0)
2282 HCURSOR WINAPI GetCursorFrameInfo(HCURSOR hCursor, DWORD reserved, DWORD istep, DWORD *rate_jiffies, DWORD *num_steps)
2284 struct cursoricon_object *ptr;
2285 HCURSOR ret = 0;
2286 UINT icon_steps;
2288 if (rate_jiffies == NULL || num_steps == NULL) return 0;
2290 if (!(ptr = get_icon_ptr( hCursor ))) return 0;
2292 TRACE("%p => %d %d %p %p\n", hCursor, reserved, istep, rate_jiffies, num_steps);
2293 if (reserved != 0)
2294 FIXME("Second parameter non-zero (%d), please report this!\n", reserved);
2296 icon_steps = get_icon_steps(ptr);
2297 if (istep < icon_steps || !ptr->is_ani)
2299 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) ptr;
2300 UINT icon_frames = 1;
2302 if (ptr->is_ani)
2303 icon_frames = ani_icon_data->num_frames;
2304 if (ptr->is_ani && icon_frames > 1)
2305 ret = ani_icon_data->frames[istep];
2306 else
2307 ret = hCursor;
2308 if (icon_frames == 1)
2310 *rate_jiffies = 0;
2311 *num_steps = 1;
2313 else if (icon_steps == 1)
2315 *num_steps = ~0;
2316 *rate_jiffies = ptr->delay;
2318 else if (istep < icon_steps)
2320 struct cursoricon_frame *frame;
2322 *num_steps = icon_steps;
2323 frame = get_icon_frame( ptr, istep );
2324 if (get_icon_steps(ptr) == 1)
2325 *num_steps = ~0;
2326 else
2327 *num_steps = get_icon_steps(ptr);
2328 /* If this specific frame does not have a delay then use the global delay */
2329 if (frame->delay == ~0)
2330 *rate_jiffies = ptr->delay;
2331 else
2332 *rate_jiffies = frame->delay;
2333 release_icon_frame( ptr, frame );
2337 release_user_handle_ptr( ptr );
2339 return ret;
2342 /**********************************************************************
2343 * GetIconInfo (USER32.@)
2345 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
2347 ICONINFOEXW infoW;
2349 infoW.cbSize = sizeof(infoW);
2350 if (!GetIconInfoExW( hIcon, &infoW )) return FALSE;
2351 iconinfo->fIcon = infoW.fIcon;
2352 iconinfo->xHotspot = infoW.xHotspot;
2353 iconinfo->yHotspot = infoW.yHotspot;
2354 iconinfo->hbmColor = infoW.hbmColor;
2355 iconinfo->hbmMask = infoW.hbmMask;
2356 return TRUE;
2359 /**********************************************************************
2360 * GetIconInfoExA (USER32.@)
2362 BOOL WINAPI GetIconInfoExA( HICON icon, ICONINFOEXA *info )
2364 ICONINFOEXW infoW;
2366 if (info->cbSize != sizeof(*info))
2368 SetLastError( ERROR_INVALID_PARAMETER );
2369 return FALSE;
2371 infoW.cbSize = sizeof(infoW);
2372 if (!GetIconInfoExW( icon, &infoW )) return FALSE;
2373 info->fIcon = infoW.fIcon;
2374 info->xHotspot = infoW.xHotspot;
2375 info->yHotspot = infoW.yHotspot;
2376 info->hbmColor = infoW.hbmColor;
2377 info->hbmMask = infoW.hbmMask;
2378 info->wResID = infoW.wResID;
2379 WideCharToMultiByte( CP_ACP, 0, infoW.szModName, -1, info->szModName, MAX_PATH, NULL, NULL );
2380 WideCharToMultiByte( CP_ACP, 0, infoW.szResName, -1, info->szResName, MAX_PATH, NULL, NULL );
2381 return TRUE;
2384 /**********************************************************************
2385 * GetIconInfoExW (USER32.@)
2387 BOOL WINAPI GetIconInfoExW( HICON icon, ICONINFOEXW *info )
2389 struct cursoricon_frame *frame;
2390 struct cursoricon_object *ptr;
2391 HMODULE module;
2392 BOOL ret = TRUE;
2394 if (info->cbSize != sizeof(*info))
2396 SetLastError( ERROR_INVALID_PARAMETER );
2397 return FALSE;
2399 if (!(ptr = get_icon_ptr( icon )))
2401 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
2402 return FALSE;
2405 frame = get_icon_frame( ptr, 0 );
2406 if (!frame)
2408 release_user_handle_ptr( ptr );
2409 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
2410 return FALSE;
2413 TRACE("%p => %dx%d\n", icon, frame->width, frame->height);
2415 info->fIcon = ptr->is_icon;
2416 info->xHotspot = ptr->hotspot.x;
2417 info->yHotspot = ptr->hotspot.y;
2418 info->hbmColor = copy_bitmap( frame->color );
2419 info->hbmMask = copy_bitmap( frame->mask );
2420 info->wResID = 0;
2421 info->szModName[0] = 0;
2422 info->szResName[0] = 0;
2423 if (ptr->module)
2425 if (IS_INTRESOURCE( ptr->resname )) info->wResID = LOWORD( ptr->resname );
2426 else lstrcpynW( info->szResName, ptr->resname, MAX_PATH );
2428 if (!info->hbmMask || (!info->hbmColor && frame->color))
2430 DeleteObject( info->hbmMask );
2431 DeleteObject( info->hbmColor );
2432 ret = FALSE;
2434 module = ptr->module;
2435 release_icon_frame( ptr, frame );
2436 release_user_handle_ptr( ptr );
2437 if (ret && module) GetModuleFileNameW( module, info->szModName, MAX_PATH );
2438 return ret;
2441 /* copy an icon bitmap, even when it can't be selected into a DC */
2442 /* helper for CreateIconIndirect */
2443 static void stretch_blt_icon( HDC hdc_dst, int dst_x, int dst_y, int dst_width, int dst_height,
2444 HBITMAP src, int width, int height )
2446 HDC hdc = CreateCompatibleDC( 0 );
2448 if (!SelectObject( hdc, src )) /* do it the hard way */
2450 BITMAPINFO *info;
2451 void *bits;
2453 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) return;
2454 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2455 info->bmiHeader.biWidth = width;
2456 info->bmiHeader.biHeight = height;
2457 info->bmiHeader.biPlanes = GetDeviceCaps( hdc_dst, PLANES );
2458 info->bmiHeader.biBitCount = GetDeviceCaps( hdc_dst, BITSPIXEL );
2459 info->bmiHeader.biCompression = BI_RGB;
2460 info->bmiHeader.biSizeImage = get_dib_image_size( width, height, info->bmiHeader.biBitCount );
2461 info->bmiHeader.biXPelsPerMeter = 0;
2462 info->bmiHeader.biYPelsPerMeter = 0;
2463 info->bmiHeader.biClrUsed = 0;
2464 info->bmiHeader.biClrImportant = 0;
2465 bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
2466 if (bits && GetDIBits( hdc, src, 0, height, bits, info, DIB_RGB_COLORS ))
2467 StretchDIBits( hdc_dst, dst_x, dst_y, dst_width, dst_height,
2468 0, 0, width, height, bits, info, DIB_RGB_COLORS, SRCCOPY );
2470 HeapFree( GetProcessHeap(), 0, bits );
2471 HeapFree( GetProcessHeap(), 0, info );
2473 else StretchBlt( hdc_dst, dst_x, dst_y, dst_width, dst_height, hdc, 0, 0, width, height, SRCCOPY );
2475 DeleteDC( hdc );
2478 /**********************************************************************
2479 * CreateIconIndirect (USER32.@)
2481 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
2483 BITMAP bmpXor, bmpAnd;
2484 HICON hObj;
2485 HBITMAP color = 0, mask;
2486 int width, height;
2487 HDC hdc;
2489 TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
2490 iconinfo->hbmColor, iconinfo->hbmMask,
2491 iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
2493 if (!iconinfo->hbmMask) return 0;
2495 GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
2496 TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2497 bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
2498 bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
2500 if (iconinfo->hbmColor)
2502 GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2503 TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2504 bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
2505 bmpXor.bmPlanes, bmpXor.bmBitsPixel);
2507 width = bmpXor.bmWidth;
2508 height = bmpXor.bmHeight;
2509 if (bmpXor.bmPlanes * bmpXor.bmBitsPixel != 1 || bmpAnd.bmPlanes * bmpAnd.bmBitsPixel != 1)
2511 color = create_color_bitmap( width, height );
2512 mask = CreateBitmap( width, height, 1, 1, NULL );
2514 else mask = CreateBitmap( width, height * 2, 1, 1, NULL );
2516 else
2518 width = bmpAnd.bmWidth;
2519 height = bmpAnd.bmHeight;
2520 mask = CreateBitmap( width, height, 1, 1, NULL );
2523 hdc = CreateCompatibleDC( 0 );
2524 SelectObject( hdc, mask );
2525 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
2527 if (color)
2529 SelectObject( hdc, color );
2530 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
2532 else if (iconinfo->hbmColor)
2534 stretch_blt_icon( hdc, 0, height, width, height, iconinfo->hbmColor, width, height );
2536 else height /= 2;
2538 DeleteDC( hdc );
2540 hObj = alloc_icon_handle( FALSE, 0 );
2541 if (hObj)
2543 struct cursoricon_object *info = get_icon_ptr( hObj );
2544 struct cursoricon_frame *frame;
2546 info->is_icon = iconinfo->fIcon;
2547 frame = get_icon_frame( info, 0 );
2548 frame->delay = ~0;
2549 frame->width = width;
2550 frame->height = height;
2551 frame->color = color;
2552 frame->mask = mask;
2553 frame->alpha = create_alpha_bitmap( iconinfo->hbmColor, NULL, NULL );
2554 release_icon_frame( info, frame );
2555 if (info->is_icon)
2557 info->hotspot.x = width / 2;
2558 info->hotspot.y = height / 2;
2560 else
2562 info->hotspot.x = iconinfo->xHotspot;
2563 info->hotspot.y = iconinfo->yHotspot;
2566 release_user_handle_ptr( info );
2568 return hObj;
2571 /******************************************************************************
2572 * DrawIconEx (USER32.@) Draws an icon or cursor on device context
2574 * NOTES
2575 * Why is this using SM_CXICON instead of SM_CXCURSOR?
2577 * PARAMS
2578 * hdc [I] Handle to device context
2579 * x0 [I] X coordinate of upper left corner
2580 * y0 [I] Y coordinate of upper left corner
2581 * hIcon [I] Handle to icon to draw
2582 * cxWidth [I] Width of icon
2583 * cyWidth [I] Height of icon
2584 * istep [I] Index of frame in animated cursor
2585 * hbr [I] Handle to background brush
2586 * flags [I] Icon-drawing flags
2588 * RETURNS
2589 * Success: TRUE
2590 * Failure: FALSE
2592 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2593 INT cxWidth, INT cyWidth, UINT istep,
2594 HBRUSH hbr, UINT flags )
2596 struct cursoricon_frame *frame;
2597 struct cursoricon_object *ptr;
2598 HDC hdc_dest, hMemDC;
2599 BOOL result = FALSE, DoOffscreen;
2600 HBITMAP hB_off = 0;
2601 COLORREF oldFg, oldBg;
2602 INT x, y, nStretchMode;
2604 TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2605 hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2607 if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2608 if (istep >= get_icon_steps( ptr ))
2610 TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
2611 release_user_handle_ptr( ptr );
2612 return FALSE;
2614 if (!(frame = get_icon_frame( ptr, istep )))
2616 FIXME_(icon)("Error retrieving icon frame %d\n", istep);
2617 release_user_handle_ptr( ptr );
2618 return FALSE;
2620 if (!(hMemDC = CreateCompatibleDC( hdc )))
2622 release_icon_frame( ptr, frame );
2623 release_user_handle_ptr( ptr );
2624 return FALSE;
2627 if (flags & DI_NOMIRROR)
2628 FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
2630 /* Calculate the size of the destination image. */
2631 if (cxWidth == 0)
2633 if (flags & DI_DEFAULTSIZE)
2634 cxWidth = GetSystemMetrics (SM_CXICON);
2635 else
2636 cxWidth = frame->width;
2638 if (cyWidth == 0)
2640 if (flags & DI_DEFAULTSIZE)
2641 cyWidth = GetSystemMetrics (SM_CYICON);
2642 else
2643 cyWidth = frame->height;
2646 DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2648 if (DoOffscreen) {
2649 RECT r;
2651 SetRect(&r, 0, 0, cxWidth, cxWidth);
2653 if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
2654 if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
2656 DeleteDC( hdc_dest );
2657 goto failed;
2659 SelectObject(hdc_dest, hB_off);
2660 FillRect(hdc_dest, &r, hbr);
2661 x = y = 0;
2663 else
2665 hdc_dest = hdc;
2666 x = x0;
2667 y = y0;
2670 nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2672 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2673 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2675 if (frame->alpha && (flags & DI_IMAGE))
2677 BOOL alpha_blend = TRUE;
2679 if (GetObjectType( hdc_dest ) == OBJ_MEMDC)
2681 BITMAP bm;
2682 HBITMAP bmp = GetCurrentObject( hdc_dest, OBJ_BITMAP );
2683 alpha_blend = GetObjectW( bmp, sizeof(bm), &bm ) && bm.bmBitsPixel > 8;
2685 if (alpha_blend)
2687 BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2688 SelectObject( hMemDC, frame->alpha );
2689 if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
2690 0, 0, frame->width, frame->height,
2691 pixelblend )) goto done;
2695 if (flags & DI_MASK)
2697 DWORD rop = (flags & DI_IMAGE) ? SRCAND : SRCCOPY;
2698 SelectObject( hMemDC, frame->mask );
2699 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2700 hMemDC, 0, 0, frame->width, frame->height, rop );
2703 if (flags & DI_IMAGE)
2705 if (frame->color)
2707 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2708 SelectObject( hMemDC, frame->color );
2709 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2710 hMemDC, 0, 0, frame->width, frame->height, rop );
2712 else
2714 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2715 SelectObject( hMemDC, frame->mask );
2716 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2717 hMemDC, 0, frame->height, frame->width,
2718 frame->height, rop );
2722 done:
2723 if (DoOffscreen) BitBlt( hdc, x0, y0, cxWidth, cyWidth, hdc_dest, 0, 0, SRCCOPY );
2725 SetTextColor( hdc, oldFg );
2726 SetBkColor( hdc, oldBg );
2727 SetStretchBltMode (hdc, nStretchMode);
2728 result = TRUE;
2729 if (hdc_dest != hdc) DeleteDC( hdc_dest );
2730 if (hB_off) DeleteObject(hB_off);
2731 failed:
2732 DeleteDC( hMemDC );
2733 release_icon_frame( ptr, frame );
2734 release_user_handle_ptr( ptr );
2735 return result;
2738 /***********************************************************************
2739 * DIB_FixColorsToLoadflags
2741 * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2742 * are in loadflags
2744 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2746 int colors;
2747 COLORREF c_W, c_S, c_F, c_L, c_C;
2748 int incr,i;
2749 RGBQUAD *ptr;
2750 int bitmap_type;
2751 LONG width;
2752 LONG height;
2753 WORD bpp;
2754 DWORD compr;
2756 if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2758 WARN_(resource)("Invalid bitmap\n");
2759 return;
2762 if (bpp > 8) return;
2764 if (bitmap_type == 0) /* BITMAPCOREHEADER */
2766 incr = 3;
2767 colors = 1 << bpp;
2769 else
2771 incr = 4;
2772 colors = bmi->bmiHeader.biClrUsed;
2773 if (colors > 256) colors = 256;
2774 if (!colors && (bpp <= 8)) colors = 1 << bpp;
2777 c_W = GetSysColor(COLOR_WINDOW);
2778 c_S = GetSysColor(COLOR_3DSHADOW);
2779 c_F = GetSysColor(COLOR_3DFACE);
2780 c_L = GetSysColor(COLOR_3DLIGHT);
2782 if (loadflags & LR_LOADTRANSPARENT) {
2783 switch (bpp) {
2784 case 1: pix = pix >> 7; break;
2785 case 4: pix = pix >> 4; break;
2786 case 8: break;
2787 default:
2788 WARN_(resource)("(%d): Unsupported depth\n", bpp);
2789 return;
2791 if (pix >= colors) {
2792 WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2793 return;
2795 if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2796 ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2797 ptr->rgbBlue = GetBValue(c_W);
2798 ptr->rgbGreen = GetGValue(c_W);
2799 ptr->rgbRed = GetRValue(c_W);
2801 if (loadflags & LR_LOADMAP3DCOLORS)
2802 for (i=0; i<colors; i++) {
2803 ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2804 c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2805 if (c_C == RGB(128, 128, 128)) {
2806 ptr->rgbRed = GetRValue(c_S);
2807 ptr->rgbGreen = GetGValue(c_S);
2808 ptr->rgbBlue = GetBValue(c_S);
2809 } else if (c_C == RGB(192, 192, 192)) {
2810 ptr->rgbRed = GetRValue(c_F);
2811 ptr->rgbGreen = GetGValue(c_F);
2812 ptr->rgbBlue = GetBValue(c_F);
2813 } else if (c_C == RGB(223, 223, 223)) {
2814 ptr->rgbRed = GetRValue(c_L);
2815 ptr->rgbGreen = GetGValue(c_L);
2816 ptr->rgbBlue = GetBValue(c_L);
2822 /**********************************************************************
2823 * BITMAP_Load
2825 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2826 INT desiredx, INT desiredy, UINT loadflags )
2828 HBITMAP hbitmap = 0, orig_bm;
2829 HRSRC hRsrc;
2830 HGLOBAL handle;
2831 const char *ptr = NULL;
2832 BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2833 int size;
2834 BYTE pix;
2835 char *bits;
2836 LONG width, height, new_width, new_height;
2837 WORD bpp_dummy;
2838 DWORD compr_dummy, offbits = 0;
2839 INT bm_type;
2840 HDC screen_mem_dc = NULL;
2842 if (!(loadflags & LR_LOADFROMFILE))
2844 if (!instance)
2846 /* OEM bitmap: try to load the resource from user32.dll */
2847 instance = user32_module;
2850 if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2851 if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2853 if ((info = LockResource( handle )) == NULL) return 0;
2855 else
2857 BITMAPFILEHEADER * bmfh;
2859 if (!(ptr = map_fileW( name, NULL ))) return 0;
2860 info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2861 bmfh = (BITMAPFILEHEADER *)ptr;
2862 if (bmfh->bfType != 0x4d42 /* 'BM' */)
2864 WARN("Invalid/unsupported bitmap format!\n");
2865 goto end;
2867 if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2870 bm_type = DIB_GetBitmapInfo( &info->bmiHeader, &width, &height,
2871 &bpp_dummy, &compr_dummy);
2872 if (bm_type == -1)
2874 WARN("Invalid bitmap format!\n");
2875 goto end;
2878 size = bitmap_info_size(info, DIB_RGB_COLORS);
2879 fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2880 scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2882 if (!fix_info || !scaled_info) goto end;
2883 memcpy(fix_info, info, size);
2885 pix = *((LPBYTE)info + size);
2886 DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2888 memcpy(scaled_info, fix_info, size);
2890 if(desiredx != 0)
2891 new_width = desiredx;
2892 else
2893 new_width = width;
2895 if(desiredy != 0)
2896 new_height = height > 0 ? desiredy : -desiredy;
2897 else
2898 new_height = height;
2900 if(bm_type == 0)
2902 BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2903 core->bcWidth = new_width;
2904 core->bcHeight = new_height;
2906 else
2908 /* Some sanity checks for BITMAPINFO (not applicable to BITMAPCOREINFO) */
2909 if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
2910 WARN("Broken BitmapInfoHeader!\n");
2911 goto end;
2914 scaled_info->bmiHeader.biWidth = new_width;
2915 scaled_info->bmiHeader.biHeight = new_height;
2918 if (new_height < 0) new_height = -new_height;
2920 if (!(screen_mem_dc = CreateCompatibleDC( 0 ))) goto end;
2922 bits = (char *)info + (offbits ? offbits : size);
2924 if (loadflags & LR_CREATEDIBSECTION)
2926 scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2927 hbitmap = CreateDIBSection(0, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2929 else
2931 if (is_dib_monochrome(fix_info))
2932 hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2933 else
2934 hbitmap = create_color_bitmap(new_width, new_height);
2937 orig_bm = SelectObject(screen_mem_dc, hbitmap);
2938 StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2939 SelectObject(screen_mem_dc, orig_bm);
2941 end:
2942 if (screen_mem_dc) DeleteDC(screen_mem_dc);
2943 HeapFree(GetProcessHeap(), 0, scaled_info);
2944 HeapFree(GetProcessHeap(), 0, fix_info);
2945 if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2947 return hbitmap;
2950 /**********************************************************************
2951 * LoadImageA (USER32.@)
2953 * See LoadImageW.
2955 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2956 INT desiredx, INT desiredy, UINT loadflags)
2958 HANDLE res;
2959 LPWSTR u_name;
2961 if (IS_INTRESOURCE(name))
2962 return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2964 __TRY {
2965 DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2966 u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2967 MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2969 __EXCEPT_PAGE_FAULT {
2970 SetLastError( ERROR_INVALID_PARAMETER );
2971 return 0;
2973 __ENDTRY
2974 res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2975 HeapFree(GetProcessHeap(), 0, u_name);
2976 return res;
2980 /******************************************************************************
2981 * LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2983 * PARAMS
2984 * hinst [I] Handle of instance that contains image
2985 * name [I] Name of image
2986 * type [I] Type of image
2987 * desiredx [I] Desired width
2988 * desiredy [I] Desired height
2989 * loadflags [I] Load flags
2991 * RETURNS
2992 * Success: Handle to newly loaded image
2993 * Failure: NULL
2995 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2997 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2998 INT desiredx, INT desiredy, UINT loadflags )
3000 int depth;
3002 TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
3003 hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
3005 if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
3006 switch (type) {
3007 case IMAGE_BITMAP:
3008 return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
3010 case IMAGE_ICON:
3011 case IMAGE_CURSOR:
3012 depth = 1;
3013 if (!(loadflags & LR_MONOCHROME)) depth = get_display_bpp();
3014 return CURSORICON_Load(hinst, name, desiredx, desiredy, depth, (type == IMAGE_CURSOR), loadflags);
3016 return 0;
3019 /******************************************************************************
3020 * CopyImage (USER32.@) Creates new image and copies attributes to it
3022 * PARAMS
3023 * hnd [I] Handle to image to copy
3024 * type [I] Type of image to copy
3025 * desiredx [I] Desired width of new image
3026 * desiredy [I] Desired height of new image
3027 * flags [I] Copy flags
3029 * RETURNS
3030 * Success: Handle to newly created image
3031 * Failure: NULL
3033 * BUGS
3034 * Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
3035 * all other versions (95/2000/XP have been tested) ignore it.
3037 * NOTES
3038 * If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
3039 * a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
3040 * the copy will have the same depth as the screen.
3041 * The content of the image will only be copied if the bit depth of the
3042 * original image is compatible with the bit depth of the screen, or
3043 * if the source is a DIB section.
3044 * The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
3046 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
3047 INT desiredy, UINT flags )
3049 TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
3050 hnd, type, desiredx, desiredy, flags);
3052 switch (type)
3054 case IMAGE_BITMAP:
3056 HBITMAP res = NULL;
3057 DIBSECTION ds;
3058 int objSize;
3059 BITMAPINFO * bi;
3061 objSize = GetObjectW( hnd, sizeof(ds), &ds );
3062 if (!objSize) return 0;
3063 if ((desiredx < 0) || (desiredy < 0)) return 0;
3065 if (flags & LR_COPYFROMRESOURCE)
3067 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
3070 if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
3071 if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
3073 /* Allocate memory for a BITMAPINFOHEADER structure and a
3074 color table. The maximum number of colors in a color table
3075 is 256 which corresponds to a bitmap with depth 8.
3076 Bitmaps with higher depths don't have color tables. */
3077 bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
3078 if (!bi) return 0;
3080 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
3081 bi->bmiHeader.biPlanes = ds.dsBm.bmPlanes;
3082 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
3083 bi->bmiHeader.biCompression = BI_RGB;
3085 if (flags & LR_CREATEDIBSECTION)
3087 /* Create a DIB section. LR_MONOCHROME is ignored */
3088 void * bits;
3089 HDC dc = CreateCompatibleDC(NULL);
3091 if (objSize == sizeof(DIBSECTION))
3093 /* The source bitmap is a DIB.
3094 Get its attributes to create an exact copy */
3095 memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
3098 bi->bmiHeader.biWidth = desiredx;
3099 bi->bmiHeader.biHeight = desiredy;
3101 /* Get the color table or the color masks */
3102 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3104 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
3105 DeleteDC(dc);
3107 else
3109 /* Create a device-dependent bitmap */
3111 BOOL monochrome = (flags & LR_MONOCHROME);
3113 if (objSize == sizeof(DIBSECTION))
3115 /* The source bitmap is a DIB section.
3116 Get its attributes */
3117 HDC dc = CreateCompatibleDC(NULL);
3118 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
3119 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
3120 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3121 DeleteDC(dc);
3123 if (!monochrome && ds.dsBm.bmBitsPixel == 1)
3125 /* Look if the colors of the DIB are black and white */
3127 monochrome =
3128 (bi->bmiColors[0].rgbRed == 0xff
3129 && bi->bmiColors[0].rgbGreen == 0xff
3130 && bi->bmiColors[0].rgbBlue == 0xff
3131 && bi->bmiColors[0].rgbReserved == 0
3132 && bi->bmiColors[1].rgbRed == 0
3133 && bi->bmiColors[1].rgbGreen == 0
3134 && bi->bmiColors[1].rgbBlue == 0
3135 && bi->bmiColors[1].rgbReserved == 0)
3137 (bi->bmiColors[0].rgbRed == 0
3138 && bi->bmiColors[0].rgbGreen == 0
3139 && bi->bmiColors[0].rgbBlue == 0
3140 && bi->bmiColors[0].rgbReserved == 0
3141 && bi->bmiColors[1].rgbRed == 0xff
3142 && bi->bmiColors[1].rgbGreen == 0xff
3143 && bi->bmiColors[1].rgbBlue == 0xff
3144 && bi->bmiColors[1].rgbReserved == 0);
3147 else if (!monochrome)
3149 monochrome = ds.dsBm.bmBitsPixel == 1;
3152 if (monochrome)
3153 res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
3154 else
3155 res = create_color_bitmap(desiredx, desiredy);
3158 if (res)
3160 /* Only copy the bitmap if it's a DIB section or if it's
3161 compatible to the screen */
3162 if (objSize == sizeof(DIBSECTION) ||
3163 ds.dsBm.bmBitsPixel == 1 ||
3164 ds.dsBm.bmBitsPixel == get_display_bpp())
3166 /* The source bitmap may already be selected in a device context,
3167 use GetDIBits/StretchDIBits and not StretchBlt */
3169 HDC dc;
3170 void * bits;
3172 dc = CreateCompatibleDC(NULL);
3174 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
3175 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
3176 bi->bmiHeader.biSizeImage = 0;
3177 bi->bmiHeader.biClrUsed = 0;
3178 bi->bmiHeader.biClrImportant = 0;
3180 /* Fill in biSizeImage */
3181 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3182 bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
3184 if (bits)
3186 HBITMAP oldBmp;
3188 /* Get the image bits of the source bitmap */
3189 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
3191 /* Copy it to the destination bitmap */
3192 oldBmp = SelectObject(dc, res);
3193 StretchDIBits(dc, 0, 0, desiredx, desiredy,
3194 0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
3195 bits, bi, DIB_RGB_COLORS, SRCCOPY);
3196 SelectObject(dc, oldBmp);
3198 HeapFree(GetProcessHeap(), 0, bits);
3201 DeleteDC(dc);
3204 if (flags & LR_COPYDELETEORG)
3206 DeleteObject(hnd);
3209 HeapFree(GetProcessHeap(), 0, bi);
3210 return res;
3212 case IMAGE_ICON:
3213 case IMAGE_CURSOR:
3215 struct cursoricon_object *icon;
3216 HICON res = 0;
3217 int depth = (flags & LR_MONOCHROME) ? 1 : get_display_bpp();
3219 if (flags & LR_DEFAULTSIZE)
3221 if (!desiredx) desiredx = GetSystemMetrics( type == IMAGE_ICON ? SM_CXICON : SM_CXCURSOR );
3222 if (!desiredy) desiredy = GetSystemMetrics( type == IMAGE_ICON ? SM_CYICON : SM_CYCURSOR );
3225 if (!(icon = get_icon_ptr( hnd ))) return 0;
3227 if (icon->rsrc && (flags & LR_COPYFROMRESOURCE))
3228 res = CURSORICON_Load( icon->module, icon->resname, desiredx, desiredy, depth,
3229 !icon->is_icon, flags );
3230 else
3231 res = CopyIcon( hnd ); /* FIXME: change size if necessary */
3232 release_user_handle_ptr( icon );
3234 if (res && (flags & LR_COPYDELETEORG)) DeleteObject( hnd );
3235 return res;
3238 return 0;
3242 /******************************************************************************
3243 * LoadBitmapW (USER32.@) Loads bitmap from the executable file
3245 * RETURNS
3246 * Success: Handle to specified bitmap
3247 * Failure: NULL
3249 HBITMAP WINAPI LoadBitmapW(
3250 HINSTANCE instance, /* [in] Handle to application instance */
3251 LPCWSTR name) /* [in] Address of bitmap resource name */
3253 return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
3256 /**********************************************************************
3257 * LoadBitmapA (USER32.@)
3259 * See LoadBitmapW.
3261 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
3263 return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );