include: Remove the wine_ prefix on rbtree functions.
[wine.git] / dlls / user32 / cursoricon.c
blobd163d1a7360435e9aba861ce482c9b48ff88e61f
1 /*
2 * Cursor and icon support
4 * Copyright 1995 Alexandre Julliard
5 * Copyright 1996 Martin Von Loewis
6 * Copyright 1997 Alex Korobka
7 * Copyright 1998 Turchanov Sergey
8 * Copyright 2007 Henri Verbeet
9 * Copyright 2009 Vincent Povirk for CodeWeavers
10 * Copyright 2016 Dmitry Timoshkov
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #include <assert.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <png.h>
33 #include "windef.h"
34 #include "winbase.h"
35 #include "wingdi.h"
36 #include "winerror.h"
37 #include "winnls.h"
38 #include "wine/exception.h"
39 #include "wine/server.h"
40 #include "controls.h"
41 #include "win.h"
42 #include "user_private.h"
43 #include "wine/list.h"
44 #include "wine/debug.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
47 WINE_DECLARE_DEBUG_CHANNEL(icon);
48 WINE_DECLARE_DEBUG_CHANNEL(resource);
50 #define RIFF_FOURCC( c0, c1, c2, c3 ) \
51 ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
52 ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
53 #define PNG_SIGN RIFF_FOURCC(0x89,'P','N','G')
55 static struct list icon_cache = LIST_INIT( icon_cache );
57 /**********************************************************************
58 * User objects management
61 struct cursoricon_frame
63 UINT width; /* frame-specific width */
64 UINT height; /* frame-specific height */
65 UINT delay; /* frame-specific delay between this frame and the next (in jiffies) */
66 HBITMAP color; /* color bitmap */
67 HBITMAP alpha; /* pre-multiplied alpha bitmap for 32-bpp icons */
68 HBITMAP mask; /* mask bitmap (followed by color for 1-bpp icons) */
71 struct cursoricon_object
73 struct user_object obj; /* object header */
74 struct list entry; /* entry in shared icons list */
75 ULONG_PTR param; /* opaque param used by 16-bit code */
76 HMODULE module; /* module for icons loaded from resources */
77 LPWSTR resname; /* resource name for icons loaded from resources */
78 HRSRC rsrc; /* resource for shared icons */
79 BOOL is_shared; /* whether this object is shared */
80 BOOL is_icon; /* whether icon or cursor */
81 BOOL is_ani; /* whether this object is a static cursor or an animated cursor */
82 UINT delay; /* delay between this frame and the next (in jiffies) */
83 POINT hotspot;
86 struct static_cursoricon_object
88 struct cursoricon_object shared;
89 struct cursoricon_frame frame; /* frame-specific icon data */
92 struct animated_cursoricon_object
94 struct cursoricon_object shared;
95 UINT num_frames; /* number of frames in the icon/cursor */
96 UINT num_steps; /* number of sequence steps in the icon/cursor */
97 HICON frames[1]; /* list of animated cursor frames */
100 static HBITMAP create_color_bitmap( int width, int height )
102 HDC hdc = get_display_dc();
103 HBITMAP ret = CreateCompatibleBitmap( hdc, width, height );
104 release_display_dc( hdc );
105 return ret;
108 static int get_display_bpp(void)
110 HDC hdc = get_display_dc();
111 int ret = GetDeviceCaps( hdc, BITSPIXEL );
112 release_display_dc( hdc );
113 return ret;
116 static HICON alloc_icon_handle( BOOL is_ani, UINT num_steps )
118 struct cursoricon_object *obj;
119 int icon_size;
120 HICON handle;
122 if (is_ani)
123 icon_size = FIELD_OFFSET( struct animated_cursoricon_object, frames[num_steps] );
124 else
125 icon_size = sizeof( struct static_cursoricon_object );
126 obj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, icon_size );
127 if (!obj) return NULL;
129 obj->delay = 0;
130 obj->is_ani = is_ani;
131 if (is_ani)
133 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;
135 ani_icon_data->num_steps = num_steps;
136 ani_icon_data->num_frames = num_steps; /* changed later for some animated cursors */
139 if (!(handle = alloc_user_handle( &obj->obj, USER_ICON )))
140 HeapFree( GetProcessHeap(), 0, obj );
141 return handle;
144 static struct cursoricon_object *get_icon_ptr( HICON handle )
146 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
147 if (obj == OBJ_OTHER_PROCESS)
149 WARN( "icon handle %p from other process\n", handle );
150 obj = NULL;
152 return obj;
155 static struct cursoricon_frame *get_icon_frame( struct cursoricon_object *obj, int istep )
157 struct static_cursoricon_object *req_frame;
159 if (obj->is_ani)
161 struct animated_cursoricon_object *ani_icon_data;
162 struct cursoricon_object *frameobj;
164 ani_icon_data = (struct animated_cursoricon_object *) obj;
165 if (!(frameobj = get_icon_ptr( ani_icon_data->frames[istep] )))
166 return 0;
167 req_frame = (struct static_cursoricon_object *) frameobj;
169 else
170 req_frame = (struct static_cursoricon_object *) obj;
172 return &req_frame->frame;
175 static void release_icon_frame( struct cursoricon_object *obj, struct cursoricon_frame *frame )
177 if (obj->is_ani)
179 struct cursoricon_object *frameobj;
181 frameobj = (struct cursoricon_object *) (((char *)frame) - FIELD_OFFSET(struct static_cursoricon_object, frame));
182 release_user_handle_ptr( frameobj );
186 static UINT get_icon_steps( struct cursoricon_object *obj )
188 if (obj->is_ani)
190 struct animated_cursoricon_object *ani_icon_data;
192 ani_icon_data = (struct animated_cursoricon_object *) obj;
193 return ani_icon_data->num_steps;
195 return 1;
198 static BOOL free_icon_handle( HICON handle )
200 struct cursoricon_object *obj = free_user_handle( handle, USER_ICON );
202 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
203 else if (obj)
205 ULONG_PTR param = obj->param;
206 UINT i;
208 assert( !obj->rsrc ); /* shared icons can't be freed */
210 if (!obj->is_ani)
212 struct cursoricon_frame *frame = get_icon_frame( obj, 0 );
214 if (frame->alpha) DeleteObject( frame->alpha );
215 if (frame->color) DeleteObject( frame->color );
216 DeleteObject( frame->mask );
217 release_icon_frame( obj, frame );
219 else
221 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) obj;
223 for (i=0; i<ani_icon_data->num_steps; i++)
225 HICON hFrame = ani_icon_data->frames[i];
227 if (hFrame)
229 UINT j;
231 free_icon_handle( ani_icon_data->frames[i] );
232 for (j=0; j<ani_icon_data->num_steps; j++)
234 if (ani_icon_data->frames[j] == hFrame)
235 ani_icon_data->frames[j] = 0;
240 if (!IS_INTRESOURCE( obj->resname )) HeapFree( GetProcessHeap(), 0, obj->resname );
241 HeapFree( GetProcessHeap(), 0, obj );
242 if (wow_handlers.free_icon_param && param) wow_handlers.free_icon_param( param );
243 USER_Driver->pDestroyCursorIcon( handle );
244 return TRUE;
246 return FALSE;
249 ULONG_PTR get_icon_param( HICON handle )
251 ULONG_PTR ret = 0;
252 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
254 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
255 else if (obj)
257 ret = obj->param;
258 release_user_handle_ptr( obj );
260 return ret;
263 ULONG_PTR set_icon_param( HICON handle, ULONG_PTR param )
265 ULONG_PTR ret = 0;
266 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
268 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
269 else if (obj)
271 ret = obj->param;
272 obj->param = param;
273 release_user_handle_ptr( obj );
275 return ret;
279 /***********************************************************************
280 * map_fileW
282 * Helper function to map a file to memory:
283 * name - file name
284 * [RETURN] ptr - pointer to mapped file
285 * [RETURN] filesize - pointer size of file to be stored if not NULL
287 static const void *map_fileW( LPCWSTR name, LPDWORD filesize )
289 HANDLE hFile, hMapping;
290 LPVOID ptr = NULL;
292 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
293 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
294 if (hFile != INVALID_HANDLE_VALUE)
296 hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
297 if (hMapping)
299 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
300 CloseHandle( hMapping );
301 if (filesize)
302 *filesize = GetFileSize( hFile, NULL );
304 CloseHandle( hFile );
306 return ptr;
310 /***********************************************************************
311 * get_dib_image_size
313 * Return the size of a DIB bitmap in bytes.
315 static int get_dib_image_size( int width, int height, int depth )
317 return (((width * depth + 31) / 8) & ~3) * abs( height );
321 /***********************************************************************
322 * bitmap_info_size
324 * Return the size of the bitmap info structure including color table.
326 int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
328 unsigned int colors, size, masks = 0;
330 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
332 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
333 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
334 return sizeof(BITMAPCOREHEADER) + colors *
335 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
337 else /* assume BITMAPINFOHEADER */
339 colors = info->bmiHeader.biClrUsed;
340 if (colors > 256) /* buffer overflow otherwise */
341 colors = 256;
342 if (!colors && (info->bmiHeader.biBitCount <= 8))
343 colors = 1 << info->bmiHeader.biBitCount;
344 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
345 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
346 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
351 /***********************************************************************
352 * copy_bitmap
354 * Helper function to duplicate a bitmap.
356 static HBITMAP copy_bitmap( HBITMAP bitmap )
358 HDC src, dst = 0;
359 HBITMAP new_bitmap = 0;
360 BITMAP bmp;
362 if (!bitmap) return 0;
363 if (!GetObjectW( bitmap, sizeof(bmp), &bmp )) return 0;
365 if ((src = CreateCompatibleDC( 0 )) && (dst = CreateCompatibleDC( 0 )))
367 SelectObject( src, bitmap );
368 if ((new_bitmap = CreateCompatibleBitmap( src, bmp.bmWidth, bmp.bmHeight )))
370 SelectObject( dst, new_bitmap );
371 BitBlt( dst, 0, 0, bmp.bmWidth, bmp.bmHeight, src, 0, 0, SRCCOPY );
374 DeleteDC( dst );
375 DeleteDC( src );
376 return new_bitmap;
380 /***********************************************************************
381 * is_dib_monochrome
383 * Returns whether a DIB can be converted to a monochrome DDB.
385 * A DIB can be converted if its color table contains only black and
386 * white. Black must be the first color in the color table.
388 * Note : If the first color in the color table is white followed by
389 * black, we can't convert it to a monochrome DDB with
390 * SetDIBits, because black and white would be inverted.
392 static BOOL is_dib_monochrome( const BITMAPINFO* info )
394 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
396 const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
398 if (((const BITMAPCOREINFO*)info)->bmciHeader.bcBitCount != 1) return FALSE;
400 /* Check if the first color is black */
401 if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
403 rgb++;
405 /* Check if the second color is white */
406 return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
407 && (rgb->rgbtBlue == 0xff));
409 else return FALSE;
411 else /* assume BITMAPINFOHEADER */
413 const RGBQUAD *rgb = info->bmiColors;
415 if (info->bmiHeader.biBitCount != 1) return FALSE;
417 /* Check if the first color is black */
418 if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
419 (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
421 rgb++;
423 /* Check if the second color is white */
424 return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
425 && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
427 else return FALSE;
431 /***********************************************************************
432 * DIB_GetBitmapInfo
434 * Get the info from a bitmap header.
435 * Return 1 for INFOHEADER, 0 for COREHEADER, -1 in case of failure.
437 static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
438 LONG *height, WORD *bpp, DWORD *compr )
440 if (header->biSize == sizeof(BITMAPCOREHEADER))
442 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
443 *width = core->bcWidth;
444 *height = core->bcHeight;
445 *bpp = core->bcBitCount;
446 *compr = 0;
447 return 0;
449 else if (header->biSize == sizeof(BITMAPINFOHEADER) ||
450 header->biSize == sizeof(BITMAPV4HEADER) ||
451 header->biSize == sizeof(BITMAPV5HEADER))
453 *width = header->biWidth;
454 *height = header->biHeight;
455 *bpp = header->biBitCount;
456 *compr = header->biCompression;
457 return 1;
459 WARN("unknown/wrong size (%u) for header\n", header->biSize);
460 return -1;
463 /**********************************************************************
464 * get_icon_size
466 BOOL get_icon_size( HICON handle, SIZE *size )
468 struct cursoricon_object *info;
469 struct cursoricon_frame *frame;
471 if (!(info = get_icon_ptr( handle ))) return FALSE;
472 frame = get_icon_frame( info, 0 );
473 size->cx = frame->width;
474 size->cy = frame->height;
475 release_icon_frame( info, frame);
476 release_user_handle_ptr( info );
477 return TRUE;
480 struct png_wrapper
482 const char *buffer;
483 size_t size, pos;
486 static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
488 struct png_wrapper *png = png_get_io_ptr(png_ptr);
490 if (png->size - png->pos >= length)
492 memcpy(data, png->buffer + png->pos, length);
493 png->pos += length;
495 else
497 png_error(png_ptr, "failed to read PNG data");
501 static unsigned be_uint(unsigned val)
503 union
505 unsigned val;
506 unsigned char c[4];
507 } u;
509 u.val = val;
510 return (u.c[0] << 24) | (u.c[1] << 16) | (u.c[2] << 8) | u.c[3];
513 static BOOL get_png_info(const void *png_data, DWORD size, int *width, int *height, int *bpp)
515 static const char png_sig[8] = { 0x89,'P','N','G',0x0d,0x0a,0x1a,0x0a };
516 static const char png_IHDR[8] = { 0,0,0,0x0d,'I','H','D','R' };
517 const struct
519 char png_sig[8];
520 char ihdr_sig[8];
521 unsigned width, height;
522 char bit_depth, color_type, compression, filter, interlace;
523 } *png = png_data;
525 if (size < sizeof(*png)) return FALSE;
526 if (memcmp(png->png_sig, png_sig, sizeof(png_sig)) != 0) return FALSE;
527 if (memcmp(png->ihdr_sig, png_IHDR, sizeof(png_IHDR)) != 0) return FALSE;
529 *bpp = (png->color_type == PNG_COLOR_TYPE_RGB_ALPHA) ? 32 : 24;
530 *width = be_uint(png->width);
531 *height = be_uint(png->height);
533 return TRUE;
536 static BITMAPINFO *load_png(const char *png_data, DWORD *size)
538 struct png_wrapper png;
539 png_structp png_ptr;
540 png_infop info_ptr;
541 png_bytep *row_pointers = NULL;
542 int color_type, bit_depth, bpp, width, height;
543 int rowbytes, image_size, mask_size = 0, i;
544 BITMAPINFO *info = NULL;
545 unsigned char *image_data;
547 if (!get_png_info(png_data, *size, &width, &height, &bpp)) return NULL;
549 png.buffer = png_data;
550 png.size = *size;
551 png.pos = 0;
553 /* initialize libpng */
554 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
555 if (!png_ptr) return NULL;
557 info_ptr = png_create_info_struct(png_ptr);
558 if (!info_ptr)
560 png_destroy_read_struct(&png_ptr, NULL, NULL);
561 return NULL;
564 /* set up setjmp/longjmp error handling */
565 if (setjmp(png_jmpbuf(png_ptr)))
567 free(row_pointers);
568 RtlFreeHeap(GetProcessHeap(), 0, info);
569 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
570 return NULL;
573 png_set_crc_action(png_ptr, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);
575 /* set up custom i/o handling */
576 png_set_read_fn(png_ptr, &png, user_read_data);
578 /* read the header */
579 png_read_info(png_ptr, info_ptr);
581 color_type = png_get_color_type(png_ptr, info_ptr);
582 bit_depth = png_get_bit_depth(png_ptr, info_ptr);
584 /* expand grayscale image data to rgb */
585 if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
586 png_set_gray_to_rgb(png_ptr);
588 /* expand palette image data to rgb */
589 if (color_type == PNG_COLOR_TYPE_PALETTE || bit_depth < 8)
590 png_set_expand(png_ptr);
592 /* update color type information */
593 png_read_update_info(png_ptr, info_ptr);
595 color_type = png_get_color_type(png_ptr, info_ptr);
596 bit_depth = png_get_bit_depth(png_ptr, info_ptr);
598 bpp = 0;
600 switch (color_type)
602 case PNG_COLOR_TYPE_RGB:
603 if (bit_depth == 8)
604 bpp = 24;
605 break;
607 case PNG_COLOR_TYPE_RGB_ALPHA:
608 if (bit_depth == 8)
610 png_set_bgr(png_ptr);
611 bpp = 32;
613 break;
615 default:
616 break;
619 if (!bpp)
621 FIXME("unsupported PNG color format %d, %d bpp\n", color_type, bit_depth);
622 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
623 return NULL;
626 width = png_get_image_width(png_ptr, info_ptr);
627 height = png_get_image_height(png_ptr, info_ptr);
629 rowbytes = (width * bpp + 7) / 8;
630 image_size = height * rowbytes;
631 if (bpp != 32) /* add a mask if there is no alpha */
632 mask_size = (width + 7) / 8 * height;
634 info = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(BITMAPINFOHEADER) + image_size + mask_size);
635 if (!info)
637 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
638 return NULL;
641 image_data = (unsigned char *)info + sizeof(BITMAPINFOHEADER);
642 memset(image_data + image_size, 0, mask_size);
644 row_pointers = malloc(height * sizeof(png_bytep));
645 if (!row_pointers)
647 RtlFreeHeap(GetProcessHeap(), 0, info);
648 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
649 return NULL;
652 /* upside down */
653 for (i = 0; i < height; i++)
654 row_pointers[i] = image_data + (height - i - 1) * rowbytes;
656 png_read_image(png_ptr, row_pointers);
657 free(row_pointers);
658 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
660 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
661 info->bmiHeader.biWidth = width;
662 info->bmiHeader.biHeight = height * 2;
663 info->bmiHeader.biPlanes = 1;
664 info->bmiHeader.biBitCount = bpp;
665 info->bmiHeader.biCompression = BI_RGB;
666 info->bmiHeader.biSizeImage = image_size;
667 info->bmiHeader.biXPelsPerMeter = 0;
668 info->bmiHeader.biYPelsPerMeter = 0;
669 info->bmiHeader.biClrUsed = 0;
670 info->bmiHeader.biClrImportant = 0;
672 *size = sizeof(BITMAPINFOHEADER) + image_size + mask_size;
673 return info;
678 * The following macro functions account for the irregularities of
679 * accessing cursor and icon resources in files and resource entries.
681 typedef BOOL (*fnGetCIEntry)( LPCVOID dir, DWORD size, int n,
682 int *width, int *height, int *bits );
684 /**********************************************************************
685 * CURSORICON_FindBestIcon
687 * Find the icon closest to the requested size and bit depth.
689 static int CURSORICON_FindBestIcon( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
690 int width, int height, int depth, UINT loadflags )
692 int i, cx, cy, bits, bestEntry = -1;
693 UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
694 UINT iTempXDiff, iTempYDiff, iTempColorDiff;
696 /* Find Best Fit */
697 iTotalDiff = 0xFFFFFFFF;
698 iColorDiff = 0xFFFFFFFF;
700 if (loadflags & LR_DEFAULTSIZE)
702 if (!width) width = GetSystemMetrics( SM_CXICON );
703 if (!height) height = GetSystemMetrics( SM_CYICON );
705 else if (!width && !height)
707 /* use the size of the first entry */
708 if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
709 iTotalDiff = 0;
712 for ( i = 0; iTotalDiff && get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
714 iTempXDiff = abs(width - cx);
715 iTempYDiff = abs(height - cy);
717 if(iTotalDiff > (iTempXDiff + iTempYDiff))
719 iXDiff = iTempXDiff;
720 iYDiff = iTempYDiff;
721 iTotalDiff = iXDiff + iYDiff;
725 /* Find Best Colors for Best Fit */
726 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
728 TRACE("entry %d: %d x %d, %d bpp\n", i, cx, cy, bits);
730 if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
732 iTempColorDiff = abs(depth - bits);
733 if(iColorDiff > iTempColorDiff)
735 bestEntry = i;
736 iColorDiff = iTempColorDiff;
741 return bestEntry;
744 static BOOL CURSORICON_GetResIconEntry( LPCVOID dir, DWORD size, int n,
745 int *width, int *height, int *bits )
747 const CURSORICONDIR *resdir = dir;
748 const ICONRESDIR *icon;
750 if ( resdir->idCount <= n )
751 return FALSE;
752 if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
753 return FALSE;
754 icon = &resdir->idEntries[n].ResInfo.icon;
755 *width = icon->bWidth;
756 *height = icon->bHeight;
757 *bits = resdir->idEntries[n].wBitCount;
758 if (!*width && !*height) *width = *height = 256;
759 return TRUE;
762 /**********************************************************************
763 * CURSORICON_FindBestCursor
765 * Find the cursor closest to the requested size.
767 * FIXME: parameter 'color' ignored.
769 static int CURSORICON_FindBestCursor( LPCVOID dir, DWORD size, fnGetCIEntry get_entry,
770 int width, int height, int depth, UINT loadflags )
772 int i, maxwidth, maxheight, maxbits, cx, cy, bits, bestEntry = -1;
774 if (loadflags & LR_DEFAULTSIZE)
776 if (!width) width = GetSystemMetrics( SM_CXCURSOR );
777 if (!height) height = GetSystemMetrics( SM_CYCURSOR );
779 else if (!width && !height)
781 /* use the first entry */
782 if (!get_entry( dir, size, 0, &width, &height, &bits )) return -1;
783 return 0;
786 /* First find the largest one smaller than or equal to the requested size*/
788 maxwidth = maxheight = maxbits = 0;
789 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
791 if (cx > width || cy > height) continue;
792 if (cx < maxwidth || cy < maxheight) continue;
793 if (cx == maxwidth && cy == maxheight)
795 if (loadflags & LR_MONOCHROME)
797 if (maxbits && bits >= maxbits) continue;
799 else if (bits <= maxbits) continue;
801 bestEntry = i;
802 maxwidth = cx;
803 maxheight = cy;
804 maxbits = bits;
806 if (bestEntry != -1) return bestEntry;
808 /* Now find the smallest one larger than the requested size */
810 maxwidth = maxheight = 255;
811 for ( i = 0; get_entry( dir, size, i, &cx, &cy, &bits ); i++ )
813 if (cx > maxwidth || cy > maxheight) continue;
814 if (cx == maxwidth && cy == maxheight)
816 if (loadflags & LR_MONOCHROME)
818 if (maxbits && bits >= maxbits) continue;
820 else if (bits <= maxbits) continue;
822 bestEntry = i;
823 maxwidth = cx;
824 maxheight = cy;
825 maxbits = bits;
827 if (bestEntry == -1) bestEntry = 0;
829 return bestEntry;
832 static BOOL CURSORICON_GetResCursorEntry( LPCVOID dir, DWORD size, int n,
833 int *width, int *height, int *bits )
835 const CURSORICONDIR *resdir = dir;
836 const CURSORDIR *cursor;
838 if ( resdir->idCount <= n )
839 return FALSE;
840 if ((const char *)&resdir->idEntries[n + 1] - (const char *)dir > size)
841 return FALSE;
842 cursor = &resdir->idEntries[n].ResInfo.cursor;
843 *width = cursor->wWidth;
844 *height = cursor->wHeight;
845 *bits = resdir->idEntries[n].wBitCount;
846 if (*height == *width * 2) *height /= 2;
847 return TRUE;
850 static const CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( const CURSORICONDIR * dir, DWORD size,
851 int width, int height, int depth,
852 UINT loadflags )
854 int n;
856 n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetResIconEntry,
857 width, height, depth, loadflags );
858 if ( n < 0 )
859 return NULL;
860 return &dir->idEntries[n];
863 static const CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( const CURSORICONDIR *dir, DWORD size,
864 int width, int height, int depth,
865 UINT loadflags )
867 int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetResCursorEntry,
868 width, height, depth, loadflags );
869 if ( n < 0 )
870 return NULL;
871 return &dir->idEntries[n];
874 static BOOL CURSORICON_GetFileEntry( LPCVOID dir, DWORD size, int n,
875 int *width, int *height, int *bits )
877 const CURSORICONFILEDIR *filedir = dir;
878 const CURSORICONFILEDIRENTRY *entry;
879 const BITMAPINFOHEADER *info;
881 if ( filedir->idCount <= n )
882 return FALSE;
883 if ((const char *)&filedir->idEntries[n + 1] - (const char *)dir > size)
884 return FALSE;
885 entry = &filedir->idEntries[n];
886 if (entry->dwDIBOffset > size - sizeof(info->biSize)) return FALSE;
887 info = (const BITMAPINFOHEADER *)((const char *)dir + entry->dwDIBOffset);
889 if (info->biSize == PNG_SIGN) return get_png_info(info, size, width, height, bits);
891 if (info->biSize != sizeof(BITMAPCOREHEADER))
893 if ((const char *)(info + 1) - (const char *)dir > size) return FALSE;
894 *bits = info->biBitCount;
896 else
898 const BITMAPCOREHEADER *coreinfo = (const BITMAPCOREHEADER *)((const char *)dir + entry->dwDIBOffset);
899 if ((const char *)(coreinfo + 1) - (const char *)dir > size) return FALSE;
900 *bits = coreinfo->bcBitCount;
902 *width = entry->bWidth;
903 *height = entry->bHeight;
904 return TRUE;
907 static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( const CURSORICONFILEDIR *dir, DWORD size,
908 int width, int height, int depth,
909 UINT loadflags )
911 int n = CURSORICON_FindBestCursor( dir, size, CURSORICON_GetFileEntry,
912 width, height, depth, loadflags );
913 if ( n < 0 )
914 return NULL;
915 return &dir->idEntries[n];
918 static const CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( const CURSORICONFILEDIR *dir, DWORD size,
919 int width, int height, int depth,
920 UINT loadflags )
922 int n = CURSORICON_FindBestIcon( dir, size, CURSORICON_GetFileEntry,
923 width, height, depth, loadflags );
924 if ( n < 0 )
925 return NULL;
926 return &dir->idEntries[n];
929 /***********************************************************************
930 * bmi_has_alpha
932 static BOOL bmi_has_alpha( const BITMAPINFO *info, const void *bits )
934 int i;
935 BOOL has_alpha = FALSE;
936 const unsigned char *ptr = bits;
938 if (info->bmiHeader.biBitCount != 32) return FALSE;
939 for (i = 0; i < info->bmiHeader.biWidth * abs(info->bmiHeader.biHeight); i++, ptr += 4)
940 if ((has_alpha = (ptr[3] != 0))) break;
941 return has_alpha;
944 /***********************************************************************
945 * create_alpha_bitmap
947 * Create the alpha bitmap for a 32-bpp icon that has an alpha channel.
949 static HBITMAP create_alpha_bitmap( HBITMAP color, const BITMAPINFO *src_info, const void *color_bits )
951 HBITMAP alpha = 0;
952 BITMAPINFO *info = NULL;
953 BITMAP bm;
954 HDC hdc;
955 void *bits;
956 unsigned char *ptr;
957 int i;
959 if (!GetObjectW( color, sizeof(bm), &bm )) return 0;
960 if (bm.bmBitsPixel != 32) return 0;
962 if (!(hdc = CreateCompatibleDC( 0 ))) return 0;
963 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto done;
964 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
965 info->bmiHeader.biWidth = bm.bmWidth;
966 info->bmiHeader.biHeight = -bm.bmHeight;
967 info->bmiHeader.biPlanes = 1;
968 info->bmiHeader.biBitCount = 32;
969 info->bmiHeader.biCompression = BI_RGB;
970 info->bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
971 info->bmiHeader.biXPelsPerMeter = 0;
972 info->bmiHeader.biYPelsPerMeter = 0;
973 info->bmiHeader.biClrUsed = 0;
974 info->bmiHeader.biClrImportant = 0;
975 if (!(alpha = CreateDIBSection( hdc, info, DIB_RGB_COLORS, &bits, NULL, 0 ))) goto done;
977 if (src_info)
979 SelectObject( hdc, alpha );
980 StretchDIBits( hdc, 0, 0, bm.bmWidth, bm.bmHeight,
981 0, 0, src_info->bmiHeader.biWidth, src_info->bmiHeader.biHeight,
982 color_bits, src_info, DIB_RGB_COLORS, SRCCOPY );
985 else
987 GetDIBits( hdc, color, 0, bm.bmHeight, bits, info, DIB_RGB_COLORS );
988 if (!bmi_has_alpha( info, bits ))
990 DeleteObject( alpha );
991 alpha = 0;
992 goto done;
996 /* pre-multiply by alpha */
997 for (i = 0, ptr = bits; i < bm.bmWidth * bm.bmHeight; i++, ptr += 4)
999 unsigned int alpha = ptr[3];
1000 ptr[0] = ptr[0] * alpha / 255;
1001 ptr[1] = ptr[1] * alpha / 255;
1002 ptr[2] = ptr[2] * alpha / 255;
1005 done:
1006 DeleteDC( hdc );
1007 HeapFree( GetProcessHeap(), 0, info );
1008 return alpha;
1012 /***********************************************************************
1013 * create_icon_from_bmi
1015 * Create an icon from its BITMAPINFO.
1017 static HICON create_icon_from_bmi( const BITMAPINFO *bmi, DWORD maxsize, HMODULE module, LPCWSTR resname,
1018 HRSRC rsrc, POINT hotspot, BOOL bIcon, INT width, INT height,
1019 UINT cFlag )
1021 DWORD size, color_size, mask_size;
1022 HBITMAP color = 0, mask = 0, alpha = 0;
1023 const void *color_bits, *mask_bits;
1024 void *alpha_mask_bits = NULL;
1025 BITMAPINFO *bmi_copy;
1026 BOOL ret = FALSE;
1027 BOOL do_stretch;
1028 HICON hObj = 0;
1029 HDC hdc = 0;
1030 LONG bmi_width, bmi_height;
1031 WORD bpp;
1032 DWORD compr;
1034 /* Check bitmap header */
1036 if (bmi->bmiHeader.biSize == PNG_SIGN)
1038 BITMAPINFO *bmi_png = load_png( (const char *)bmi, &maxsize );
1040 if (bmi_png)
1042 hObj = create_icon_from_bmi( bmi_png, maxsize, module, resname,
1043 rsrc, hotspot, bIcon, width, height, cFlag );
1044 HeapFree( GetProcessHeap(), 0, bmi_png );
1045 return hObj;
1047 return 0;
1050 if (maxsize < sizeof(BITMAPCOREHEADER))
1052 WARN( "invalid size %u\n", maxsize );
1053 return 0;
1055 if (maxsize < bmi->bmiHeader.biSize)
1057 WARN( "invalid header size %u\n", bmi->bmiHeader.biSize );
1058 return 0;
1060 if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
1061 (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER) ||
1062 (bmi->bmiHeader.biCompression != BI_RGB &&
1063 bmi->bmiHeader.biCompression != BI_BITFIELDS)) )
1065 WARN( "invalid bitmap header %u\n", bmi->bmiHeader.biSize );
1066 return 0;
1069 size = bitmap_info_size( bmi, DIB_RGB_COLORS );
1070 DIB_GetBitmapInfo(&bmi->bmiHeader, &bmi_width, &bmi_height, &bpp, &compr);
1071 color_size = get_dib_image_size( bmi_width, bmi_height / 2,
1072 bpp );
1073 mask_size = get_dib_image_size( bmi_width, bmi_height / 2, 1 );
1074 if (size > maxsize || color_size > maxsize - size)
1076 WARN( "truncated file %u < %u+%u+%u\n", maxsize, size, color_size, mask_size );
1077 return 0;
1079 if (mask_size > maxsize - size - color_size) mask_size = 0; /* no mask */
1081 if (cFlag & LR_DEFAULTSIZE)
1083 if (!width) width = GetSystemMetrics( bIcon ? SM_CXICON : SM_CXCURSOR );
1084 if (!height) height = GetSystemMetrics( bIcon ? SM_CYICON : SM_CYCURSOR );
1086 else
1088 if (!width) width = bmi_width;
1089 if (!height) height = bmi_height/2;
1091 do_stretch = (bmi_height/2 != height) ||
1092 (bmi_width != width);
1094 /* Scale the hotspot */
1095 if (bIcon)
1097 hotspot.x = width / 2;
1098 hotspot.y = height / 2;
1100 else if (do_stretch)
1102 hotspot.x = (hotspot.x * width) / bmi_width;
1103 hotspot.y = (hotspot.y * height) / (bmi_height / 2);
1106 if (!(bmi_copy = HeapAlloc( GetProcessHeap(), 0, max( size, FIELD_OFFSET( BITMAPINFO, bmiColors[2] )))))
1107 return 0;
1108 if (!(hdc = CreateCompatibleDC( 0 ))) goto done;
1110 memcpy( bmi_copy, bmi, size );
1111 if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
1112 bmi_copy->bmiHeader.biHeight /= 2;
1113 else
1114 ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcHeight /= 2;
1115 bmi_height /= 2;
1117 color_bits = (const char*)bmi + size;
1118 mask_bits = (const char*)color_bits + color_size;
1120 alpha = 0;
1121 if (is_dib_monochrome( bmi ))
1123 if (!(mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
1124 color = 0;
1126 /* copy color data into second half of mask bitmap */
1127 SelectObject( hdc, mask );
1128 StretchDIBits( hdc, 0, height, width, height,
1129 0, 0, bmi_width, bmi_height,
1130 color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1132 else
1134 if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
1135 if (!(color = create_color_bitmap( width, height )))
1137 DeleteObject( mask );
1138 goto done;
1140 SelectObject( hdc, color );
1141 StretchDIBits( hdc, 0, 0, width, height,
1142 0, 0, bmi_width, bmi_height,
1143 color_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1145 if (bmi_has_alpha( bmi_copy, color_bits ))
1147 alpha = create_alpha_bitmap( color, bmi_copy, color_bits );
1148 if (!mask_size) /* generate mask from alpha */
1150 LONG x, y, dst_stride = ((bmi_width + 31) / 8) & ~3;
1152 if ((alpha_mask_bits = heap_calloc( bmi_height, dst_stride )))
1154 static const unsigned char masks[] = { 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 };
1155 const DWORD *src = color_bits;
1156 unsigned char *dst = alpha_mask_bits;
1158 for (y = 0; y < bmi_height; y++, src += bmi_width, dst += dst_stride)
1159 for (x = 0; x < bmi_width; x++)
1160 if (src[x] >> 24 != 0xff) dst[x >> 3] |= masks[x & 7];
1162 mask_bits = alpha_mask_bits;
1163 mask_size = bmi_height * dst_stride;
1168 /* convert info to monochrome to copy the mask */
1169 if (bmi_copy->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
1171 RGBQUAD *rgb = bmi_copy->bmiColors;
1173 bmi_copy->bmiHeader.biBitCount = 1;
1174 bmi_copy->bmiHeader.biClrUsed = bmi_copy->bmiHeader.biClrImportant = 2;
1175 rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
1176 rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
1177 rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
1179 else
1181 RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)bmi_copy) + 1);
1183 ((BITMAPCOREINFO *)bmi_copy)->bmciHeader.bcBitCount = 1;
1184 rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
1185 rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
1189 if (mask_size)
1191 SelectObject( hdc, mask );
1192 StretchDIBits( hdc, 0, 0, width, height,
1193 0, 0, bmi_width, bmi_height,
1194 mask_bits, bmi_copy, DIB_RGB_COLORS, SRCCOPY );
1196 ret = TRUE;
1198 done:
1199 DeleteDC( hdc );
1200 HeapFree( GetProcessHeap(), 0, bmi_copy );
1201 HeapFree( GetProcessHeap(), 0, alpha_mask_bits );
1203 if (ret)
1204 hObj = alloc_icon_handle( FALSE, 0 );
1205 if (hObj)
1207 struct cursoricon_object *info = get_icon_ptr( hObj );
1208 struct cursoricon_frame *frame;
1210 info->is_icon = bIcon;
1211 info->module = module;
1212 info->hotspot = hotspot;
1213 frame = get_icon_frame( info, 0 );
1214 frame->delay = ~0;
1215 frame->width = width;
1216 frame->height = height;
1217 frame->color = color;
1218 frame->mask = mask;
1219 frame->alpha = alpha;
1220 release_icon_frame( info, frame );
1221 if (!IS_INTRESOURCE(resname))
1223 info->resname = HeapAlloc( GetProcessHeap(), 0, (lstrlenW(resname) + 1) * sizeof(WCHAR) );
1224 if (info->resname) lstrcpyW( info->resname, resname );
1226 else info->resname = MAKEINTRESOURCEW( LOWORD(resname) );
1228 if (cFlag & LR_SHARED)
1230 info->is_shared = TRUE;
1231 if (module)
1233 info->rsrc = rsrc;
1234 list_add_head( &icon_cache, &info->entry );
1237 release_user_handle_ptr( info );
1239 else
1241 DeleteObject( color );
1242 DeleteObject( alpha );
1243 DeleteObject( mask );
1245 return hObj;
1249 /**********************************************************************
1250 * .ANI cursor support
1252 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
1253 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
1254 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
1255 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
1256 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
1257 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
1258 #define ANI_rate_ID RIFF_FOURCC('r', 'a', 't', 'e')
1260 #define ANI_FLAG_ICON 0x1
1261 #define ANI_FLAG_SEQUENCE 0x2
1263 typedef struct {
1264 DWORD header_size;
1265 DWORD num_frames;
1266 DWORD num_steps;
1267 DWORD width;
1268 DWORD height;
1269 DWORD bpp;
1270 DWORD num_planes;
1271 DWORD display_rate;
1272 DWORD flags;
1273 } ani_header;
1275 typedef struct {
1276 DWORD data_size;
1277 const unsigned char *data;
1278 } riff_chunk_t;
1280 static void dump_ani_header( const ani_header *header )
1282 TRACE(" header size: %d\n", header->header_size);
1283 TRACE(" frames: %d\n", header->num_frames);
1284 TRACE(" steps: %d\n", header->num_steps);
1285 TRACE(" width: %d\n", header->width);
1286 TRACE(" height: %d\n", header->height);
1287 TRACE(" bpp: %d\n", header->bpp);
1288 TRACE(" planes: %d\n", header->num_planes);
1289 TRACE(" display rate: %d\n", header->display_rate);
1290 TRACE(" flags: 0x%08x\n", header->flags);
1295 * RIFF:
1296 * DWORD "RIFF"
1297 * DWORD size
1298 * DWORD riff_id
1299 * BYTE[] data
1301 * LIST:
1302 * DWORD "LIST"
1303 * DWORD size
1304 * DWORD list_id
1305 * BYTE[] data
1307 * CHUNK:
1308 * DWORD chunk_id
1309 * DWORD size
1310 * BYTE[] data
1312 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
1314 const unsigned char *ptr = parent_chunk->data;
1315 const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
1317 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
1319 while (ptr < end)
1321 if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
1322 || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1324 ptr += sizeof(DWORD);
1325 chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1326 ptr += sizeof(DWORD);
1327 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
1328 chunk->data = ptr;
1330 return;
1333 ptr += sizeof(DWORD);
1334 if (ptr >= end)
1335 break;
1336 ptr += (*(const DWORD *)ptr + 1) & ~1;
1337 ptr += sizeof(DWORD);
1343 * .ANI layout:
1345 * RIFF:'ACON' RIFF chunk
1346 * |- CHUNK:'anih' Header
1347 * |- CHUNK:'seq ' Sequence information (optional)
1348 * \- LIST:'fram' Frame list
1349 * |- CHUNK:icon Cursor frames
1350 * |- CHUNK:icon
1351 * |- ...
1352 * \- CHUNK:icon
1354 static HCURSOR CURSORICON_CreateIconFromANI( const BYTE *bits, DWORD bits_size, INT width, INT height,
1355 INT depth, BOOL is_icon, UINT loadflags )
1357 struct animated_cursoricon_object *ani_icon_data;
1358 struct cursoricon_object *info;
1359 DWORD *frame_rates = NULL;
1360 DWORD *frame_seq = NULL;
1361 ani_header header;
1362 BOOL use_seq = FALSE;
1363 HCURSOR cursor;
1364 UINT i;
1365 BOOL error = FALSE;
1366 HICON *frames;
1368 riff_chunk_t root_chunk = { bits_size, bits };
1369 riff_chunk_t ACON_chunk = {0};
1370 riff_chunk_t anih_chunk = {0};
1371 riff_chunk_t fram_chunk = {0};
1372 riff_chunk_t rate_chunk = {0};
1373 riff_chunk_t seq_chunk = {0};
1374 const unsigned char *icon_chunk;
1375 const unsigned char *icon_data;
1377 TRACE("bits %p, bits_size %d\n", bits, bits_size);
1379 riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1380 if (!ACON_chunk.data)
1382 ERR("Failed to get root chunk.\n");
1383 return 0;
1386 riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1387 if (!anih_chunk.data)
1389 ERR("Failed to get 'anih' chunk.\n");
1390 return 0;
1392 memcpy( &header, anih_chunk.data, sizeof(header) );
1393 dump_ani_header( &header );
1395 if (!(header.flags & ANI_FLAG_ICON))
1397 FIXME("Raw animated icon/cursor data is not currently supported.\n");
1398 return 0;
1401 if (header.flags & ANI_FLAG_SEQUENCE)
1403 riff_find_chunk( ANI_seq__ID, 0, &ACON_chunk, &seq_chunk );
1404 if (seq_chunk.data)
1406 frame_seq = (DWORD *) seq_chunk.data;
1407 use_seq = TRUE;
1409 else
1411 FIXME("Sequence data expected but not found, assuming steps == frames.\n");
1412 header.num_steps = header.num_frames;
1416 riff_find_chunk( ANI_rate_ID, 0, &ACON_chunk, &rate_chunk );
1417 if (rate_chunk.data)
1418 frame_rates = (DWORD *) rate_chunk.data;
1420 riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1421 if (!fram_chunk.data)
1423 ERR("Failed to get icon list.\n");
1424 return 0;
1427 cursor = alloc_icon_handle( TRUE, header.num_steps );
1428 if (!cursor) return 0;
1429 frames = HeapAlloc( GetProcessHeap(), 0, sizeof(*frames) * header.num_frames );
1430 if (!frames)
1432 free_icon_handle( cursor );
1433 return 0;
1436 info = get_icon_ptr( cursor );
1437 ani_icon_data = (struct animated_cursoricon_object *) info;
1438 info->is_icon = is_icon;
1439 ani_icon_data->num_frames = header.num_frames;
1441 /* The .ANI stores the display rate in jiffies (1/60s) */
1442 info->delay = header.display_rate;
1444 icon_chunk = fram_chunk.data;
1445 icon_data = fram_chunk.data + (2 * sizeof(DWORD));
1446 for (i=0; i<header.num_frames; i++)
1448 const DWORD chunk_size = *(const DWORD *)(icon_chunk + sizeof(DWORD));
1449 const CURSORICONFILEDIRENTRY *entry;
1450 INT frameWidth, frameHeight;
1451 const BITMAPINFO *bmi;
1453 entry = CURSORICON_FindBestIconFile((const CURSORICONFILEDIR *) icon_data,
1454 bits + bits_size - icon_data,
1455 width, height, depth, loadflags );
1457 info->hotspot.x = entry->xHotspot;
1458 info->hotspot.y = entry->yHotspot;
1459 if (!header.width || !header.height)
1461 frameWidth = entry->bWidth;
1462 frameHeight = entry->bHeight;
1464 else
1466 frameWidth = header.width;
1467 frameHeight = header.height;
1470 frames[i] = NULL;
1471 if (entry->dwDIBOffset < bits + bits_size - icon_data)
1473 bmi = (const BITMAPINFO *) (icon_data + entry->dwDIBOffset);
1474 /* Grab a frame from the animation */
1475 frames[i] = create_icon_from_bmi( bmi, bits + bits_size - (const BYTE *)bmi,
1476 NULL, NULL, NULL, info->hotspot,
1477 is_icon, frameWidth, frameHeight, loadflags );
1480 if (!frames[i])
1482 FIXME_(cursor)("failed to convert animated cursor frame.\n");
1483 error = TRUE;
1484 if (i == 0)
1486 FIXME_(cursor)("Completely failed to create animated cursor!\n");
1487 ani_icon_data->num_frames = 0;
1488 release_user_handle_ptr( info );
1489 free_icon_handle( cursor );
1490 HeapFree( GetProcessHeap(), 0, frames );
1491 return 0;
1493 break;
1496 /* Advance to the next chunk */
1497 icon_chunk += chunk_size + (2 * sizeof(DWORD));
1498 icon_data = icon_chunk + (2 * sizeof(DWORD));
1501 /* There was an error but we at least decoded the first frame, so just use that frame */
1502 if (error)
1504 FIXME_(cursor)("Error creating animated cursor, only using first frame!\n");
1505 for (i=1; i<ani_icon_data->num_frames; i++)
1506 free_icon_handle( ani_icon_data->frames[i] );
1507 use_seq = FALSE;
1508 info->delay = 0;
1509 ani_icon_data->num_steps = 1;
1510 ani_icon_data->num_frames = 1;
1513 /* Setup the animated frames in the correct sequence */
1514 for (i=0; i<ani_icon_data->num_steps; i++)
1516 DWORD frame_id = use_seq ? frame_seq[i] : i;
1517 struct cursoricon_frame *frame;
1519 if (frame_id >= ani_icon_data->num_frames)
1521 frame_id = ani_icon_data->num_frames-1;
1522 ERR_(cursor)("Sequence indicates frame past end of list, corrupt?\n");
1524 ani_icon_data->frames[i] = frames[frame_id];
1525 frame = get_icon_frame( info, i );
1526 if (frame_rates)
1527 frame->delay = frame_rates[i];
1528 else
1529 frame->delay = ~0;
1530 release_icon_frame( info, frame );
1533 HeapFree( GetProcessHeap(), 0, frames );
1534 release_user_handle_ptr( info );
1536 return cursor;
1540 /**********************************************************************
1541 * CreateIconFromResourceEx (USER32.@)
1543 * FIXME: Convert to mono when cFlag is LR_MONOCHROME.
1545 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1546 BOOL bIcon, DWORD dwVersion,
1547 INT width, INT height,
1548 UINT cFlag )
1550 POINT hotspot;
1551 const BITMAPINFO *bmi;
1553 TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s %s\n",
1554 bits, cbSize, dwVersion, width, height,
1555 bIcon ? "icon" : "cursor", (cFlag & LR_MONOCHROME) ? "mono" : "" );
1557 if (!bits) return 0;
1559 if (dwVersion == 0x00020000)
1561 FIXME_(cursor)("\t2.xx resources are not supported\n");
1562 return 0;
1565 /* Check if the resource is an animated icon/cursor */
1566 if (!memcmp(bits, "RIFF", 4))
1567 return CURSORICON_CreateIconFromANI( bits, cbSize, width, height,
1568 0 /* default depth */, bIcon, cFlag );
1570 if (bIcon)
1572 hotspot.x = width / 2;
1573 hotspot.y = height / 2;
1574 bmi = (BITMAPINFO *)bits;
1576 else /* get the hotspot */
1578 const SHORT *pt = (const SHORT *)bits;
1579 hotspot.x = pt[0];
1580 hotspot.y = pt[1];
1581 bmi = (const BITMAPINFO *)(pt + 2);
1582 cbSize -= 2 * sizeof(*pt);
1585 return create_icon_from_bmi( bmi, cbSize, NULL, NULL, NULL, hotspot, bIcon, width, height, cFlag );
1589 /**********************************************************************
1590 * CreateIconFromResource (USER32.@)
1592 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1593 BOOL bIcon, DWORD dwVersion)
1595 return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0, 0, LR_DEFAULTSIZE | LR_SHARED );
1599 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1600 INT width, INT height, INT depth,
1601 BOOL fCursor, UINT loadflags)
1603 const CURSORICONFILEDIRENTRY *entry;
1604 const CURSORICONFILEDIR *dir;
1605 DWORD filesize = 0;
1606 HICON hIcon = 0;
1607 const BYTE *bits;
1608 POINT hotspot;
1610 TRACE("loading %s\n", debugstr_w( filename ));
1612 bits = map_fileW( filename, &filesize );
1613 if (!bits)
1614 return hIcon;
1616 /* Check for .ani. */
1617 if (memcmp( bits, "RIFF", 4 ) == 0)
1619 hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height, depth, !fCursor, loadflags );
1620 goto end;
1623 dir = (const CURSORICONFILEDIR*) bits;
1624 if ( filesize < FIELD_OFFSET( CURSORICONFILEDIR, idEntries[dir->idCount] ))
1625 goto end;
1627 if ( fCursor )
1628 entry = CURSORICON_FindBestCursorFile( dir, filesize, width, height, depth, loadflags );
1629 else
1630 entry = CURSORICON_FindBestIconFile( dir, filesize, width, height, depth, loadflags );
1632 if ( !entry )
1633 goto end;
1635 /* check that we don't run off the end of the file */
1636 if ( entry->dwDIBOffset > filesize )
1637 goto end;
1638 if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1639 goto end;
1641 hotspot.x = entry->xHotspot;
1642 hotspot.y = entry->yHotspot;
1643 hIcon = create_icon_from_bmi( (const BITMAPINFO *)&bits[entry->dwDIBOffset], filesize - entry->dwDIBOffset,
1644 NULL, NULL, NULL, hotspot, !fCursor, width, height, loadflags );
1645 end:
1646 TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1647 UnmapViewOfFile( bits );
1648 return hIcon;
1651 /**********************************************************************
1652 * CURSORICON_Load
1654 * Load a cursor or icon from resource or file.
1656 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1657 INT width, INT height, INT depth,
1658 BOOL fCursor, UINT loadflags)
1660 HANDLE handle = 0;
1661 HICON hIcon = 0;
1662 HRSRC hRsrc;
1663 DWORD size;
1664 const CURSORICONDIR *dir;
1665 const CURSORICONDIRENTRY *dirEntry;
1666 const BYTE *bits;
1667 WORD wResId;
1668 POINT hotspot;
1670 TRACE("%p, %s, %dx%d, depth %d, fCursor %d, flags 0x%04x\n",
1671 hInstance, debugstr_w(name), width, height, depth, fCursor, loadflags);
1673 if ( loadflags & LR_LOADFROMFILE ) /* Load from file */
1674 return CURSORICON_LoadFromFile( name, width, height, depth, fCursor, loadflags );
1676 if (!hInstance) hInstance = user32_module; /* Load OEM cursor/icon */
1678 /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1679 if ((ULONG_PTR)hInstance >> 16 == 0) loadflags &= ~LR_SHARED;
1681 /* Get directory resource ID */
1683 if (!(hRsrc = FindResourceW( hInstance, name,
1684 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1686 /* try animated resource */
1687 if (!(hRsrc = FindResourceW( hInstance, name,
1688 (LPWSTR)(fCursor ? RT_ANICURSOR : RT_ANIICON) ))) return 0;
1689 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1690 bits = LockResource( handle );
1691 return CURSORICON_CreateIconFromANI( bits, SizeofResource( hInstance, handle ),
1692 width, height, depth, !fCursor, loadflags );
1695 /* Find the best entry in the directory */
1697 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1698 if (!(dir = LockResource( handle ))) return 0;
1699 size = SizeofResource( hInstance, hRsrc );
1700 if (fCursor)
1701 dirEntry = CURSORICON_FindBestCursorRes( dir, size, width, height, depth, loadflags );
1702 else
1703 dirEntry = CURSORICON_FindBestIconRes( dir, size, width, height, depth, loadflags );
1704 if (!dirEntry) return 0;
1705 wResId = dirEntry->wResId;
1706 FreeResource( handle );
1708 /* Load the resource */
1710 if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1711 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1713 /* If shared icon, check whether it was already loaded */
1714 if (loadflags & LR_SHARED)
1716 struct cursoricon_object *ptr;
1718 USER_Lock();
1719 LIST_FOR_EACH_ENTRY( ptr, &icon_cache, struct cursoricon_object, entry )
1721 if (ptr->module != hInstance) continue;
1722 if (ptr->rsrc != hRsrc) continue;
1723 hIcon = ptr->obj.handle;
1724 break;
1726 USER_Unlock();
1727 if (hIcon) return hIcon;
1730 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1731 size = SizeofResource( hInstance, hRsrc );
1732 bits = LockResource( handle );
1734 if (!fCursor)
1736 hotspot.x = width / 2;
1737 hotspot.y = height / 2;
1739 else /* get the hotspot */
1741 const SHORT *pt = (const SHORT *)bits;
1742 hotspot.x = pt[0];
1743 hotspot.y = pt[1];
1744 bits += 2 * sizeof(SHORT);
1745 size -= 2 * sizeof(SHORT);
1747 hIcon = create_icon_from_bmi( (const BITMAPINFO *)bits, size, hInstance, name, hRsrc,
1748 hotspot, !fCursor, width, height, loadflags );
1749 FreeResource( handle );
1750 return hIcon;
1754 static HBITMAP create_masked_bitmap( int width, int height, const void *and, const void *xor )
1756 HBITMAP and_bitmap, xor_bitmap, bitmap;
1757 HDC src_dc, dst_dc;
1759 and_bitmap = CreateBitmap( width, height, 1, 1, and );
1760 xor_bitmap = CreateBitmap( width, height, 1, 1, xor );
1761 bitmap = CreateBitmap( width, height * 2, 1, 1, NULL );
1762 src_dc = CreateCompatibleDC( 0 );
1763 dst_dc = CreateCompatibleDC( 0 );
1765 SelectObject( dst_dc, bitmap );
1766 SelectObject( src_dc, and_bitmap );
1767 BitBlt( dst_dc, 0, 0, width, height, src_dc, 0, 0, SRCCOPY );
1768 SelectObject( src_dc, xor_bitmap );
1769 BitBlt( dst_dc, 0, height, width, height, src_dc, 0, 0, SRCCOPY );
1771 DeleteObject( and_bitmap );
1772 DeleteObject( xor_bitmap );
1773 DeleteDC( src_dc );
1774 DeleteDC( dst_dc );
1775 return bitmap;
1779 /***********************************************************************
1780 * CreateCursor (USER32.@)
1782 HCURSOR WINAPI CreateCursor( HINSTANCE instance, int hotspot_x, int hotspot_y,
1783 int width, int height, const void *and, const void *xor )
1785 ICONINFO info;
1786 HCURSOR cursor;
1788 TRACE( "hotspot (%d,%d), size %dx%d\n", hotspot_x, hotspot_y, width, height );
1790 info.fIcon = FALSE;
1791 info.xHotspot = hotspot_x;
1792 info.yHotspot = hotspot_y;
1793 info.hbmColor = NULL;
1794 info.hbmMask = create_masked_bitmap( width, height, and, xor );
1795 cursor = CreateIconIndirect( &info );
1796 DeleteObject( info.hbmMask );
1797 return cursor;
1801 /***********************************************************************
1802 * CreateIcon (USER32.@)
1804 * Creates an icon based on the specified bitmaps. The bitmaps must be
1805 * provided in a device dependent format and will be resized to
1806 * (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1807 * depth. The provided bitmaps must be top-down bitmaps.
1808 * Although Windows does not support 15bpp(*) this API must support it
1809 * for Winelib applications.
1811 * (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1812 * format!
1814 * RETURNS
1815 * Success: handle to an icon
1816 * Failure: NULL
1818 * FIXME: Do we need to resize the bitmaps?
1820 HICON WINAPI CreateIcon( HINSTANCE instance, int width, int height, BYTE planes,
1821 BYTE depth, const void *and, const void *xor )
1823 ICONINFO info;
1824 HICON icon;
1826 TRACE_(icon)( "%dx%d, planes %d, depth %d\n", width, height, planes, depth );
1828 info.fIcon = TRUE;
1829 info.xHotspot = width / 2;
1830 info.yHotspot = height / 2;
1831 if (depth == 1)
1833 info.hbmColor = NULL;
1834 info.hbmMask = create_masked_bitmap( width, height, and, xor );
1836 else
1838 info.hbmColor = CreateBitmap( width, height, planes, depth, xor );
1839 info.hbmMask = CreateBitmap( width, height, 1, 1, and );
1842 icon = CreateIconIndirect( &info );
1844 DeleteObject( info.hbmMask );
1845 DeleteObject( info.hbmColor );
1847 return icon;
1851 /***********************************************************************
1852 * CopyIcon (USER32.@)
1854 HICON WINAPI CopyIcon( HICON icon )
1856 ICONINFOEXW info;
1857 HICON res;
1859 info.cbSize = sizeof(info);
1860 if (!GetIconInfoExW( icon, &info ))
1861 return NULL;
1863 res = CopyImage( icon, info.fIcon ? IMAGE_ICON : IMAGE_CURSOR, 0, 0, 0 );
1864 DeleteObject( info.hbmColor );
1865 DeleteObject( info.hbmMask );
1866 return res;
1870 /***********************************************************************
1871 * DestroyIcon (USER32.@)
1873 BOOL WINAPI DestroyIcon( HICON hIcon )
1875 BOOL ret = FALSE;
1876 struct cursoricon_object *obj = get_icon_ptr( hIcon );
1878 TRACE_(icon)("%p\n", hIcon );
1880 if (obj)
1882 BOOL shared = obj->is_shared;
1883 release_user_handle_ptr( obj );
1884 ret = (NtUserGetCursor() != hIcon);
1885 if (!shared) free_icon_handle( hIcon );
1887 return ret;
1891 /***********************************************************************
1892 * DestroyCursor (USER32.@)
1894 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
1896 return DestroyIcon( hCursor );
1899 /***********************************************************************
1900 * DrawIcon (USER32.@)
1902 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
1904 return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
1907 /***********************************************************************
1908 * SetCursor (USER32.@)
1910 * Set the cursor shape.
1912 * RETURNS
1913 * A handle to the previous cursor shape.
1915 HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1917 struct cursoricon_object *obj;
1918 HCURSOR hOldCursor;
1919 int show_count;
1920 BOOL ret;
1922 TRACE("%p\n", hCursor);
1924 SERVER_START_REQ( set_cursor )
1926 req->flags = SET_CURSOR_HANDLE;
1927 req->handle = wine_server_user_handle( hCursor );
1928 if ((ret = !wine_server_call_err( req )))
1930 hOldCursor = wine_server_ptr_handle( reply->prev_handle );
1931 show_count = reply->prev_count;
1934 SERVER_END_REQ;
1936 if (!ret) return 0;
1937 USER_Driver->pSetCursor( show_count >= 0 ? hCursor : 0 );
1939 if (!(obj = get_icon_ptr( hOldCursor ))) return 0;
1940 release_user_handle_ptr( obj );
1941 return hOldCursor;
1945 /***********************************************************************
1946 * ClipCursor (USER32.@)
1948 BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
1950 UINT dpi;
1951 BOOL ret;
1952 RECT new_rect;
1954 TRACE( "Clipping to %s\n", wine_dbgstr_rect(rect) );
1956 if (rect)
1958 if (rect->left > rect->right || rect->top > rect->bottom) return FALSE;
1959 if ((dpi = get_thread_dpi()))
1961 new_rect = map_dpi_rect( *rect, dpi,
1962 get_monitor_dpi( MonitorFromRect( rect, MONITOR_DEFAULTTOPRIMARY )));
1963 rect = &new_rect;
1967 SERVER_START_REQ( set_cursor )
1969 req->clip_msg = WM_WINE_CLIPCURSOR;
1970 if (rect)
1972 req->flags = SET_CURSOR_CLIP;
1973 req->clip.left = rect->left;
1974 req->clip.top = rect->top;
1975 req->clip.right = rect->right;
1976 req->clip.bottom = rect->bottom;
1978 else req->flags = SET_CURSOR_NOCLIP;
1980 if ((ret = !wine_server_call( req )))
1982 new_rect.left = reply->new_clip.left;
1983 new_rect.top = reply->new_clip.top;
1984 new_rect.right = reply->new_clip.right;
1985 new_rect.bottom = reply->new_clip.bottom;
1988 SERVER_END_REQ;
1989 if (ret) USER_Driver->pClipCursor( &new_rect );
1990 return ret;
1994 /***********************************************************************
1995 * GetClipCursor (USER32.@)
1997 BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
1999 DPI_AWARENESS_CONTEXT context;
2000 UINT dpi;
2001 BOOL ret;
2003 if (!rect) return FALSE;
2005 SERVER_START_REQ( set_cursor )
2007 req->flags = 0;
2008 if ((ret = !wine_server_call( req )))
2010 rect->left = reply->new_clip.left;
2011 rect->top = reply->new_clip.top;
2012 rect->right = reply->new_clip.right;
2013 rect->bottom = reply->new_clip.bottom;
2016 SERVER_END_REQ;
2018 if (ret && (dpi = get_thread_dpi()))
2020 context = SetThreadDpiAwarenessContext( DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE );
2021 *rect = map_dpi_rect( *rect, get_monitor_dpi( MonitorFromRect( rect, MONITOR_DEFAULTTOPRIMARY )), dpi );
2022 SetThreadDpiAwarenessContext( context );
2024 return ret;
2028 /***********************************************************************
2029 * SetSystemCursor (USER32.@)
2031 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
2033 FIXME("(%p,%08x),stub!\n", hcur, id);
2034 return TRUE;
2038 /**********************************************************************
2039 * LookupIconIdFromDirectoryEx (USER32.@)
2041 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
2042 INT width, INT height, UINT cFlag )
2044 const CURSORICONDIR *dir = (const CURSORICONDIR*)xdir;
2045 UINT retVal = 0;
2046 if( dir && !dir->idReserved && (dir->idType & 3) )
2048 const CURSORICONDIRENTRY* entry;
2049 int depth = (cFlag & LR_MONOCHROME) ? 1 : get_display_bpp();
2051 if( bIcon )
2052 entry = CURSORICON_FindBestIconRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
2053 else
2054 entry = CURSORICON_FindBestCursorRes( dir, ~0u, width, height, depth, LR_DEFAULTSIZE );
2056 if( entry ) retVal = entry->wResId;
2058 else WARN_(cursor)("invalid resource directory\n");
2059 return retVal;
2062 /**********************************************************************
2063 * LookupIconIdFromDirectory (USER32.@)
2065 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
2067 return LookupIconIdFromDirectoryEx( dir, bIcon, 0, 0, bIcon ? 0 : LR_MONOCHROME );
2070 /***********************************************************************
2071 * LoadCursorW (USER32.@)
2073 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
2075 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2077 return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
2078 LR_SHARED | LR_DEFAULTSIZE );
2081 /***********************************************************************
2082 * LoadCursorA (USER32.@)
2084 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
2086 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2088 return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
2089 LR_SHARED | LR_DEFAULTSIZE );
2092 /***********************************************************************
2093 * LoadCursorFromFileW (USER32.@)
2095 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
2097 TRACE("%s\n", debugstr_w(name));
2099 return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
2100 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2103 /***********************************************************************
2104 * LoadCursorFromFileA (USER32.@)
2106 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
2108 TRACE("%s\n", debugstr_a(name));
2110 return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
2111 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2114 /***********************************************************************
2115 * LoadIconW (USER32.@)
2117 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
2119 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2121 return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
2122 LR_SHARED | LR_DEFAULTSIZE );
2125 /***********************************************************************
2126 * LoadIconA (USER32.@)
2128 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
2130 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2132 return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
2133 LR_SHARED | LR_DEFAULTSIZE );
2136 /**********************************************************************
2137 * GetCursorFrameInfo (USER32.@)
2139 * NOTES
2140 * So far no use has been found for the second parameter, it is currently presumed
2141 * that this parameter is reserved for future use.
2143 * PARAMS
2144 * hCursor [I] Handle to cursor for which to retrieve information
2145 * reserved [I] No purpose has been found for this parameter (may be NULL)
2146 * istep [I] The step of the cursor for which to retrieve information
2147 * rate_jiffies [O] Pointer to DWORD that receives the frame-specific delay (cannot be NULL)
2148 * num_steps [O] Pointer to DWORD that receives the number of steps in the cursor (cannot be NULL)
2150 * RETURNS
2151 * Success: Handle to a frame of the cursor (specified by istep)
2152 * Failure: NULL cursor (0)
2154 HCURSOR WINAPI GetCursorFrameInfo(HCURSOR hCursor, DWORD reserved, DWORD istep, DWORD *rate_jiffies, DWORD *num_steps)
2156 struct cursoricon_object *ptr;
2157 HCURSOR ret = 0;
2158 UINT icon_steps;
2160 if (rate_jiffies == NULL || num_steps == NULL) return 0;
2162 if (!(ptr = get_icon_ptr( hCursor ))) return 0;
2164 TRACE("%p => %d %d %p %p\n", hCursor, reserved, istep, rate_jiffies, num_steps);
2165 if (reserved != 0)
2166 FIXME("Second parameter non-zero (%d), please report this!\n", reserved);
2168 icon_steps = get_icon_steps(ptr);
2169 if (istep < icon_steps || !ptr->is_ani)
2171 struct animated_cursoricon_object *ani_icon_data = (struct animated_cursoricon_object *) ptr;
2172 UINT icon_frames = 1;
2174 if (ptr->is_ani)
2175 icon_frames = ani_icon_data->num_frames;
2176 if (ptr->is_ani && icon_frames > 1)
2177 ret = ani_icon_data->frames[istep];
2178 else
2179 ret = hCursor;
2180 if (icon_frames == 1)
2182 *rate_jiffies = 0;
2183 *num_steps = 1;
2185 else if (icon_steps == 1)
2187 *num_steps = ~0;
2188 *rate_jiffies = ptr->delay;
2190 else if (istep < icon_steps)
2192 struct cursoricon_frame *frame;
2194 *num_steps = icon_steps;
2195 frame = get_icon_frame( ptr, istep );
2196 if (get_icon_steps(ptr) == 1)
2197 *num_steps = ~0;
2198 else
2199 *num_steps = get_icon_steps(ptr);
2200 /* If this specific frame does not have a delay then use the global delay */
2201 if (frame->delay == ~0)
2202 *rate_jiffies = ptr->delay;
2203 else
2204 *rate_jiffies = frame->delay;
2205 release_icon_frame( ptr, frame );
2209 release_user_handle_ptr( ptr );
2211 return ret;
2214 /**********************************************************************
2215 * GetIconInfo (USER32.@)
2217 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
2219 ICONINFOEXW infoW;
2221 infoW.cbSize = sizeof(infoW);
2222 if (!GetIconInfoExW( hIcon, &infoW )) return FALSE;
2223 iconinfo->fIcon = infoW.fIcon;
2224 iconinfo->xHotspot = infoW.xHotspot;
2225 iconinfo->yHotspot = infoW.yHotspot;
2226 iconinfo->hbmColor = infoW.hbmColor;
2227 iconinfo->hbmMask = infoW.hbmMask;
2228 return TRUE;
2231 /**********************************************************************
2232 * GetIconInfoExA (USER32.@)
2234 BOOL WINAPI GetIconInfoExA( HICON icon, ICONINFOEXA *info )
2236 ICONINFOEXW infoW;
2238 if (info->cbSize != sizeof(*info))
2240 SetLastError( ERROR_INVALID_PARAMETER );
2241 return FALSE;
2243 infoW.cbSize = sizeof(infoW);
2244 if (!GetIconInfoExW( icon, &infoW )) return FALSE;
2245 info->fIcon = infoW.fIcon;
2246 info->xHotspot = infoW.xHotspot;
2247 info->yHotspot = infoW.yHotspot;
2248 info->hbmColor = infoW.hbmColor;
2249 info->hbmMask = infoW.hbmMask;
2250 info->wResID = infoW.wResID;
2251 WideCharToMultiByte( CP_ACP, 0, infoW.szModName, -1, info->szModName, MAX_PATH, NULL, NULL );
2252 WideCharToMultiByte( CP_ACP, 0, infoW.szResName, -1, info->szResName, MAX_PATH, NULL, NULL );
2253 return TRUE;
2256 /**********************************************************************
2257 * GetIconInfoExW (USER32.@)
2259 BOOL WINAPI GetIconInfoExW( HICON icon, ICONINFOEXW *info )
2261 struct cursoricon_frame *frame;
2262 struct cursoricon_object *ptr;
2263 HMODULE module;
2264 BOOL ret = TRUE;
2266 if (info->cbSize != sizeof(*info))
2268 SetLastError( ERROR_INVALID_PARAMETER );
2269 return FALSE;
2271 if (!(ptr = get_icon_ptr( icon )))
2273 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
2274 return FALSE;
2277 frame = get_icon_frame( ptr, 0 );
2278 if (!frame)
2280 release_user_handle_ptr( ptr );
2281 SetLastError( ERROR_INVALID_CURSOR_HANDLE );
2282 return FALSE;
2285 TRACE("%p => %dx%d\n", icon, frame->width, frame->height);
2287 info->fIcon = ptr->is_icon;
2288 info->xHotspot = ptr->hotspot.x;
2289 info->yHotspot = ptr->hotspot.y;
2290 info->hbmColor = copy_bitmap( frame->color );
2291 info->hbmMask = copy_bitmap( frame->mask );
2292 info->wResID = 0;
2293 info->szModName[0] = 0;
2294 info->szResName[0] = 0;
2295 if (ptr->module)
2297 if (IS_INTRESOURCE( ptr->resname )) info->wResID = LOWORD( ptr->resname );
2298 else lstrcpynW( info->szResName, ptr->resname, MAX_PATH );
2300 if (!info->hbmMask || (!info->hbmColor && frame->color))
2302 DeleteObject( info->hbmMask );
2303 DeleteObject( info->hbmColor );
2304 ret = FALSE;
2306 module = ptr->module;
2307 release_icon_frame( ptr, frame );
2308 release_user_handle_ptr( ptr );
2309 if (ret && module) GetModuleFileNameW( module, info->szModName, MAX_PATH );
2310 return ret;
2313 /* copy an icon bitmap, even when it can't be selected into a DC */
2314 /* helper for CreateIconIndirect */
2315 static void stretch_blt_icon( HDC hdc_dst, int dst_x, int dst_y, int dst_width, int dst_height,
2316 HBITMAP src, int width, int height )
2318 HDC hdc = CreateCompatibleDC( 0 );
2320 if (!SelectObject( hdc, src )) /* do it the hard way */
2322 BITMAPINFO *info;
2323 void *bits;
2325 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) return;
2326 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2327 info->bmiHeader.biWidth = width;
2328 info->bmiHeader.biHeight = height;
2329 info->bmiHeader.biPlanes = GetDeviceCaps( hdc_dst, PLANES );
2330 info->bmiHeader.biBitCount = GetDeviceCaps( hdc_dst, BITSPIXEL );
2331 info->bmiHeader.biCompression = BI_RGB;
2332 info->bmiHeader.biSizeImage = get_dib_image_size( width, height, info->bmiHeader.biBitCount );
2333 info->bmiHeader.biXPelsPerMeter = 0;
2334 info->bmiHeader.biYPelsPerMeter = 0;
2335 info->bmiHeader.biClrUsed = 0;
2336 info->bmiHeader.biClrImportant = 0;
2337 bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
2338 if (bits && GetDIBits( hdc, src, 0, height, bits, info, DIB_RGB_COLORS ))
2339 StretchDIBits( hdc_dst, dst_x, dst_y, dst_width, dst_height,
2340 0, 0, width, height, bits, info, DIB_RGB_COLORS, SRCCOPY );
2342 HeapFree( GetProcessHeap(), 0, bits );
2343 HeapFree( GetProcessHeap(), 0, info );
2345 else StretchBlt( hdc_dst, dst_x, dst_y, dst_width, dst_height, hdc, 0, 0, width, height, SRCCOPY );
2347 DeleteDC( hdc );
2350 /**********************************************************************
2351 * CreateIconIndirect (USER32.@)
2353 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
2355 BITMAP bmpXor, bmpAnd;
2356 HICON hObj;
2357 HBITMAP color = 0, mask;
2358 int width, height;
2359 HDC hdc;
2361 TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
2362 iconinfo->hbmColor, iconinfo->hbmMask,
2363 iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
2365 if (!iconinfo->hbmMask) return 0;
2367 GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
2368 TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2369 bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
2370 bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
2372 if (iconinfo->hbmColor)
2374 GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2375 TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2376 bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
2377 bmpXor.bmPlanes, bmpXor.bmBitsPixel);
2379 width = bmpXor.bmWidth;
2380 height = bmpXor.bmHeight;
2381 color = create_color_bitmap( width, height );
2383 else
2385 width = bmpAnd.bmWidth;
2386 height = bmpAnd.bmHeight;
2388 mask = CreateBitmap( width, height, 1, 1, NULL );
2390 hdc = CreateCompatibleDC( 0 );
2391 SelectObject( hdc, mask );
2392 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
2394 if (color)
2396 SelectObject( hdc, color );
2397 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
2399 else height /= 2;
2401 DeleteDC( hdc );
2403 hObj = alloc_icon_handle( FALSE, 0 );
2404 if (hObj)
2406 struct cursoricon_object *info = get_icon_ptr( hObj );
2407 struct cursoricon_frame *frame;
2409 info->is_icon = iconinfo->fIcon;
2410 frame = get_icon_frame( info, 0 );
2411 frame->delay = ~0;
2412 frame->width = width;
2413 frame->height = height;
2414 frame->color = color;
2415 frame->mask = mask;
2416 frame->alpha = create_alpha_bitmap( iconinfo->hbmColor, NULL, NULL );
2417 release_icon_frame( info, frame );
2418 if (info->is_icon)
2420 info->hotspot.x = width / 2;
2421 info->hotspot.y = height / 2;
2423 else
2425 info->hotspot.x = iconinfo->xHotspot;
2426 info->hotspot.y = iconinfo->yHotspot;
2429 release_user_handle_ptr( info );
2431 return hObj;
2434 /******************************************************************************
2435 * DrawIconEx (USER32.@) Draws an icon or cursor on device context
2437 * NOTES
2438 * Why is this using SM_CXICON instead of SM_CXCURSOR?
2440 * PARAMS
2441 * hdc [I] Handle to device context
2442 * x0 [I] X coordinate of upper left corner
2443 * y0 [I] Y coordinate of upper left corner
2444 * hIcon [I] Handle to icon to draw
2445 * cxWidth [I] Width of icon
2446 * cyWidth [I] Height of icon
2447 * istep [I] Index of frame in animated cursor
2448 * hbr [I] Handle to background brush
2449 * flags [I] Icon-drawing flags
2451 * RETURNS
2452 * Success: TRUE
2453 * Failure: FALSE
2455 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2456 INT cxWidth, INT cyWidth, UINT istep,
2457 HBRUSH hbr, UINT flags )
2459 struct cursoricon_frame *frame;
2460 struct cursoricon_object *ptr;
2461 HDC hdc_dest, hMemDC;
2462 BOOL result = FALSE, DoOffscreen;
2463 HBITMAP hB_off = 0;
2464 COLORREF oldFg, oldBg;
2465 INT x, y, nStretchMode;
2467 TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2468 hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2470 if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2471 if (istep >= get_icon_steps( ptr ))
2473 TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
2474 release_user_handle_ptr( ptr );
2475 return FALSE;
2477 if (!(frame = get_icon_frame( ptr, istep )))
2479 FIXME_(icon)("Error retrieving icon frame %d\n", istep);
2480 release_user_handle_ptr( ptr );
2481 return FALSE;
2483 if (!(hMemDC = CreateCompatibleDC( hdc )))
2485 release_icon_frame( ptr, frame );
2486 release_user_handle_ptr( ptr );
2487 return FALSE;
2490 if (flags & DI_NOMIRROR)
2491 FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
2493 /* Calculate the size of the destination image. */
2494 if (cxWidth == 0)
2496 if (flags & DI_DEFAULTSIZE)
2497 cxWidth = GetSystemMetrics (SM_CXICON);
2498 else
2499 cxWidth = frame->width;
2501 if (cyWidth == 0)
2503 if (flags & DI_DEFAULTSIZE)
2504 cyWidth = GetSystemMetrics (SM_CYICON);
2505 else
2506 cyWidth = frame->height;
2509 DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2511 if (DoOffscreen) {
2512 RECT r;
2514 SetRect(&r, 0, 0, cxWidth, cxWidth);
2516 if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
2517 if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
2519 DeleteDC( hdc_dest );
2520 goto failed;
2522 SelectObject(hdc_dest, hB_off);
2523 FillRect(hdc_dest, &r, hbr);
2524 x = y = 0;
2526 else
2528 hdc_dest = hdc;
2529 x = x0;
2530 y = y0;
2533 nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2535 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2536 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2538 if (frame->alpha && (flags & DI_IMAGE))
2540 BOOL alpha_blend = TRUE;
2542 if (GetObjectType( hdc_dest ) == OBJ_MEMDC)
2544 BITMAP bm;
2545 HBITMAP bmp = GetCurrentObject( hdc_dest, OBJ_BITMAP );
2546 alpha_blend = GetObjectW( bmp, sizeof(bm), &bm ) && bm.bmBitsPixel > 8;
2548 if (alpha_blend)
2550 BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2551 SelectObject( hMemDC, frame->alpha );
2552 if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
2553 0, 0, frame->width, frame->height,
2554 pixelblend )) goto done;
2558 if (flags & DI_MASK)
2560 DWORD rop = (flags & DI_IMAGE) ? SRCAND : SRCCOPY;
2561 SelectObject( hMemDC, frame->mask );
2562 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2563 hMemDC, 0, 0, frame->width, frame->height, rop );
2566 if (flags & DI_IMAGE)
2568 if (frame->color)
2570 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2571 SelectObject( hMemDC, frame->color );
2572 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2573 hMemDC, 0, 0, frame->width, frame->height, rop );
2575 else
2577 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2578 SelectObject( hMemDC, frame->mask );
2579 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2580 hMemDC, 0, frame->height, frame->width,
2581 frame->height, rop );
2585 done:
2586 if (DoOffscreen) BitBlt( hdc, x0, y0, cxWidth, cyWidth, hdc_dest, 0, 0, SRCCOPY );
2588 SetTextColor( hdc, oldFg );
2589 SetBkColor( hdc, oldBg );
2590 SetStretchBltMode (hdc, nStretchMode);
2591 result = TRUE;
2592 if (hdc_dest != hdc) DeleteDC( hdc_dest );
2593 if (hB_off) DeleteObject(hB_off);
2594 failed:
2595 DeleteDC( hMemDC );
2596 release_icon_frame( ptr, frame );
2597 release_user_handle_ptr( ptr );
2598 return result;
2601 /***********************************************************************
2602 * DIB_FixColorsToLoadflags
2604 * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2605 * are in loadflags
2607 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2609 int colors;
2610 COLORREF c_W, c_S, c_F, c_L, c_C;
2611 int incr,i;
2612 RGBQUAD *ptr;
2613 int bitmap_type;
2614 LONG width;
2615 LONG height;
2616 WORD bpp;
2617 DWORD compr;
2619 if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2621 WARN_(resource)("Invalid bitmap\n");
2622 return;
2625 if (bpp > 8) return;
2627 if (bitmap_type == 0) /* BITMAPCOREHEADER */
2629 incr = 3;
2630 colors = 1 << bpp;
2632 else
2634 incr = 4;
2635 colors = bmi->bmiHeader.biClrUsed;
2636 if (colors > 256) colors = 256;
2637 if (!colors && (bpp <= 8)) colors = 1 << bpp;
2640 c_W = GetSysColor(COLOR_WINDOW);
2641 c_S = GetSysColor(COLOR_3DSHADOW);
2642 c_F = GetSysColor(COLOR_3DFACE);
2643 c_L = GetSysColor(COLOR_3DLIGHT);
2645 if (loadflags & LR_LOADTRANSPARENT) {
2646 switch (bpp) {
2647 case 1: pix = pix >> 7; break;
2648 case 4: pix = pix >> 4; break;
2649 case 8: break;
2650 default:
2651 WARN_(resource)("(%d): Unsupported depth\n", bpp);
2652 return;
2654 if (pix >= colors) {
2655 WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2656 return;
2658 if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2659 ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2660 ptr->rgbBlue = GetBValue(c_W);
2661 ptr->rgbGreen = GetGValue(c_W);
2662 ptr->rgbRed = GetRValue(c_W);
2664 if (loadflags & LR_LOADMAP3DCOLORS)
2665 for (i=0; i<colors; i++) {
2666 ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2667 c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2668 if (c_C == RGB(128, 128, 128)) {
2669 ptr->rgbRed = GetRValue(c_S);
2670 ptr->rgbGreen = GetGValue(c_S);
2671 ptr->rgbBlue = GetBValue(c_S);
2672 } else if (c_C == RGB(192, 192, 192)) {
2673 ptr->rgbRed = GetRValue(c_F);
2674 ptr->rgbGreen = GetGValue(c_F);
2675 ptr->rgbBlue = GetBValue(c_F);
2676 } else if (c_C == RGB(223, 223, 223)) {
2677 ptr->rgbRed = GetRValue(c_L);
2678 ptr->rgbGreen = GetGValue(c_L);
2679 ptr->rgbBlue = GetBValue(c_L);
2685 /**********************************************************************
2686 * BITMAP_Load
2688 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2689 INT desiredx, INT desiredy, UINT loadflags )
2691 HBITMAP hbitmap = 0, orig_bm;
2692 HRSRC hRsrc;
2693 HGLOBAL handle;
2694 const char *ptr = NULL;
2695 BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2696 int size;
2697 BYTE pix;
2698 char *bits;
2699 LONG width, height, new_width, new_height;
2700 WORD bpp_dummy;
2701 DWORD compr_dummy, offbits = 0;
2702 INT bm_type;
2703 HDC screen_mem_dc = NULL;
2705 if (!(loadflags & LR_LOADFROMFILE))
2707 if (!instance)
2709 /* OEM bitmap: try to load the resource from user32.dll */
2710 instance = user32_module;
2713 if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2714 if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2716 if ((info = LockResource( handle )) == NULL) return 0;
2718 else
2720 BITMAPFILEHEADER * bmfh;
2722 if (!(ptr = map_fileW( name, NULL ))) return 0;
2723 info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2724 bmfh = (BITMAPFILEHEADER *)ptr;
2725 if (bmfh->bfType != 0x4d42 /* 'BM' */)
2727 WARN("Invalid/unsupported bitmap format!\n");
2728 goto end;
2730 if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2733 bm_type = DIB_GetBitmapInfo( &info->bmiHeader, &width, &height,
2734 &bpp_dummy, &compr_dummy);
2735 if (bm_type == -1)
2737 WARN("Invalid bitmap format!\n");
2738 goto end;
2741 size = bitmap_info_size(info, DIB_RGB_COLORS);
2742 fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2743 scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2745 if (!fix_info || !scaled_info) goto end;
2746 memcpy(fix_info, info, size);
2748 pix = *((LPBYTE)info + size);
2749 DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2751 memcpy(scaled_info, fix_info, size);
2753 if(desiredx != 0)
2754 new_width = desiredx;
2755 else
2756 new_width = width;
2758 if(desiredy != 0)
2759 new_height = height > 0 ? desiredy : -desiredy;
2760 else
2761 new_height = height;
2763 if(bm_type == 0)
2765 BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2766 core->bcWidth = new_width;
2767 core->bcHeight = new_height;
2769 else
2771 /* Some sanity checks for BITMAPINFO (not applicable to BITMAPCOREINFO) */
2772 if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
2773 WARN("Broken BitmapInfoHeader!\n");
2774 goto end;
2777 scaled_info->bmiHeader.biWidth = new_width;
2778 scaled_info->bmiHeader.biHeight = new_height;
2781 if (new_height < 0) new_height = -new_height;
2783 if (!(screen_mem_dc = CreateCompatibleDC( 0 ))) goto end;
2785 bits = (char *)info + (offbits ? offbits : size);
2787 if (loadflags & LR_CREATEDIBSECTION)
2789 scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2790 hbitmap = CreateDIBSection(0, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2792 else
2794 if (is_dib_monochrome(fix_info))
2795 hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2796 else
2797 hbitmap = create_color_bitmap(new_width, new_height);
2800 orig_bm = SelectObject(screen_mem_dc, hbitmap);
2801 if (info->bmiHeader.biBitCount > 1)
2802 SetStretchBltMode(screen_mem_dc, HALFTONE);
2803 StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2804 SelectObject(screen_mem_dc, orig_bm);
2806 end:
2807 if (screen_mem_dc) DeleteDC(screen_mem_dc);
2808 HeapFree(GetProcessHeap(), 0, scaled_info);
2809 HeapFree(GetProcessHeap(), 0, fix_info);
2810 if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2812 return hbitmap;
2815 /**********************************************************************
2816 * LoadImageA (USER32.@)
2818 * See LoadImageW.
2820 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2821 INT desiredx, INT desiredy, UINT loadflags)
2823 HANDLE res;
2824 LPWSTR u_name;
2826 if (IS_INTRESOURCE(name))
2827 return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2829 __TRY {
2830 DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2831 u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2832 MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2834 __EXCEPT_PAGE_FAULT {
2835 SetLastError( ERROR_INVALID_PARAMETER );
2836 return 0;
2838 __ENDTRY
2839 res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2840 HeapFree(GetProcessHeap(), 0, u_name);
2841 return res;
2845 /******************************************************************************
2846 * LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2848 * PARAMS
2849 * hinst [I] Handle of instance that contains image
2850 * name [I] Name of image
2851 * type [I] Type of image
2852 * desiredx [I] Desired width
2853 * desiredy [I] Desired height
2854 * loadflags [I] Load flags
2856 * RETURNS
2857 * Success: Handle to newly loaded image
2858 * Failure: NULL
2860 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2862 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2863 INT desiredx, INT desiredy, UINT loadflags )
2865 int depth;
2866 WCHAR path[MAX_PATH];
2868 TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
2869 hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
2871 if (loadflags & LR_LOADFROMFILE)
2873 loadflags &= ~LR_SHARED;
2874 /* relative paths are not only relative to the current working directory */
2875 if (SearchPathW(NULL, name, NULL, ARRAY_SIZE(path), path, NULL)) name = path;
2877 switch (type) {
2878 case IMAGE_BITMAP:
2879 return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2881 case IMAGE_ICON:
2882 case IMAGE_CURSOR:
2883 depth = 1;
2884 if (!(loadflags & LR_MONOCHROME)) depth = get_display_bpp();
2885 return CURSORICON_Load(hinst, name, desiredx, desiredy, depth, (type == IMAGE_CURSOR), loadflags);
2887 return 0;
2891 /* StretchBlt from src to dest; helper for CopyImage(). */
2892 static void stretch_bitmap( HBITMAP dst, HBITMAP src, int dst_width, int dst_height, int src_width, int src_height )
2894 HDC src_dc = CreateCompatibleDC( 0 ), dst_dc = CreateCompatibleDC( 0 );
2896 SelectObject( src_dc, src );
2897 SelectObject( dst_dc, dst );
2898 StretchBlt( dst_dc, 0, 0, dst_width, dst_height, src_dc, 0, 0, src_width, src_height, SRCCOPY );
2900 DeleteDC( src_dc );
2901 DeleteDC( dst_dc );
2905 /******************************************************************************
2906 * CopyImage (USER32.@) Creates new image and copies attributes to it
2908 * PARAMS
2909 * hnd [I] Handle to image to copy
2910 * type [I] Type of image to copy
2911 * desiredx [I] Desired width of new image
2912 * desiredy [I] Desired height of new image
2913 * flags [I] Copy flags
2915 * RETURNS
2916 * Success: Handle to newly created image
2917 * Failure: NULL
2919 * BUGS
2920 * Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
2921 * all other versions (95/2000/XP have been tested) ignore it.
2923 * NOTES
2924 * If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
2925 * a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
2926 * the copy will have the same depth as the screen.
2927 * The content of the image will only be copied if the bit depth of the
2928 * original image is compatible with the bit depth of the screen, or
2929 * if the source is a DIB section.
2930 * The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
2932 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2933 INT desiredy, UINT flags )
2935 TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
2936 hnd, type, desiredx, desiredy, flags);
2938 switch (type)
2940 case IMAGE_BITMAP:
2942 HBITMAP res = NULL;
2943 DIBSECTION ds;
2944 int objSize;
2945 BITMAPINFO * bi;
2947 objSize = GetObjectW( hnd, sizeof(ds), &ds );
2948 if (!objSize) return 0;
2949 if ((desiredx < 0) || (desiredy < 0)) return 0;
2951 if (flags & LR_COPYFROMRESOURCE)
2953 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
2956 if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
2957 if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
2959 /* Allocate memory for a BITMAPINFOHEADER structure and a
2960 color table. The maximum number of colors in a color table
2961 is 256 which corresponds to a bitmap with depth 8.
2962 Bitmaps with higher depths don't have color tables. */
2963 bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
2964 if (!bi) return 0;
2966 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
2967 bi->bmiHeader.biPlanes = ds.dsBm.bmPlanes;
2968 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
2969 bi->bmiHeader.biCompression = BI_RGB;
2971 if (flags & LR_CREATEDIBSECTION)
2973 /* Create a DIB section. LR_MONOCHROME is ignored */
2974 void * bits;
2975 HDC dc = CreateCompatibleDC(NULL);
2977 if (objSize == sizeof(DIBSECTION))
2979 /* The source bitmap is a DIB.
2980 Get its attributes to create an exact copy */
2981 memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
2984 bi->bmiHeader.biWidth = desiredx;
2985 bi->bmiHeader.biHeight = desiredy;
2987 /* Get the color table or the color masks */
2988 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2990 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
2991 DeleteDC(dc);
2993 else
2995 /* Create a device-dependent bitmap */
2997 BOOL monochrome = (flags & LR_MONOCHROME);
2999 if (objSize == sizeof(DIBSECTION))
3001 /* The source bitmap is a DIB section.
3002 Get its attributes */
3003 HDC dc = CreateCompatibleDC(NULL);
3004 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
3005 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
3006 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3007 DeleteDC(dc);
3009 if (!monochrome && ds.dsBm.bmBitsPixel == 1)
3011 /* Look if the colors of the DIB are black and white */
3013 monochrome =
3014 (bi->bmiColors[0].rgbRed == 0xff
3015 && bi->bmiColors[0].rgbGreen == 0xff
3016 && bi->bmiColors[0].rgbBlue == 0xff
3017 && bi->bmiColors[0].rgbReserved == 0
3018 && bi->bmiColors[1].rgbRed == 0
3019 && bi->bmiColors[1].rgbGreen == 0
3020 && bi->bmiColors[1].rgbBlue == 0
3021 && bi->bmiColors[1].rgbReserved == 0)
3023 (bi->bmiColors[0].rgbRed == 0
3024 && bi->bmiColors[0].rgbGreen == 0
3025 && bi->bmiColors[0].rgbBlue == 0
3026 && bi->bmiColors[0].rgbReserved == 0
3027 && bi->bmiColors[1].rgbRed == 0xff
3028 && bi->bmiColors[1].rgbGreen == 0xff
3029 && bi->bmiColors[1].rgbBlue == 0xff
3030 && bi->bmiColors[1].rgbReserved == 0);
3033 else if (!monochrome)
3035 monochrome = ds.dsBm.bmBitsPixel == 1;
3038 if (monochrome)
3039 res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
3040 else
3041 res = create_color_bitmap(desiredx, desiredy);
3044 if (res)
3046 /* Only copy the bitmap if it's a DIB section or if it's
3047 compatible to the screen */
3048 if (objSize == sizeof(DIBSECTION) ||
3049 ds.dsBm.bmBitsPixel == 1 ||
3050 ds.dsBm.bmBitsPixel == get_display_bpp())
3052 /* The source bitmap may already be selected in a device context,
3053 use GetDIBits/StretchDIBits and not StretchBlt */
3055 HDC dc;
3056 void * bits;
3058 dc = CreateCompatibleDC(NULL);
3059 if (ds.dsBm.bmBitsPixel > 1)
3060 SetStretchBltMode(dc, HALFTONE);
3062 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
3063 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
3064 bi->bmiHeader.biSizeImage = 0;
3065 bi->bmiHeader.biClrUsed = 0;
3066 bi->bmiHeader.biClrImportant = 0;
3068 /* Fill in biSizeImage */
3069 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3070 bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
3072 if (bits)
3074 HBITMAP oldBmp;
3076 /* Get the image bits of the source bitmap */
3077 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
3079 /* Copy it to the destination bitmap */
3080 oldBmp = SelectObject(dc, res);
3081 StretchDIBits(dc, 0, 0, desiredx, desiredy,
3082 0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
3083 bits, bi, DIB_RGB_COLORS, SRCCOPY);
3084 SelectObject(dc, oldBmp);
3086 HeapFree(GetProcessHeap(), 0, bits);
3089 DeleteDC(dc);
3092 if (flags & LR_COPYDELETEORG)
3094 DeleteObject(hnd);
3097 HeapFree(GetProcessHeap(), 0, bi);
3098 return res;
3100 case IMAGE_ICON:
3101 case IMAGE_CURSOR:
3103 struct cursoricon_frame *frame;
3104 struct cursoricon_object *icon;
3105 int depth = (flags & LR_MONOCHROME) ? 1 : get_display_bpp();
3106 HICON resource_icon = NULL;
3107 ICONINFO info;
3108 HICON res;
3110 if (!(icon = get_icon_ptr( hnd ))) return 0;
3112 if (icon->rsrc && (flags & LR_COPYFROMRESOURCE))
3114 resource_icon = CURSORICON_Load( icon->module, icon->resname, desiredx,
3115 desiredy, depth, !icon->is_icon, flags );
3116 release_user_handle_ptr( icon );
3117 if (!(icon = get_icon_ptr( resource_icon )))
3119 if (resource_icon) DestroyIcon( resource_icon );
3120 return 0;
3123 frame = get_icon_frame( icon, 0 );
3125 if (flags & LR_DEFAULTSIZE)
3127 if (!desiredx) desiredx = GetSystemMetrics( type == IMAGE_ICON ? SM_CXICON : SM_CXCURSOR );
3128 if (!desiredy) desiredy = GetSystemMetrics( type == IMAGE_ICON ? SM_CYICON : SM_CYCURSOR );
3130 else
3132 if (!desiredx) desiredx = frame->width;
3133 if (!desiredy) desiredy = frame->height;
3136 info.fIcon = icon->is_icon;
3137 info.xHotspot = icon->hotspot.x;
3138 info.yHotspot = icon->hotspot.y;
3140 if (desiredx == frame->width && desiredy == frame->height)
3142 info.hbmColor = frame->color;
3143 info.hbmMask = frame->mask;
3144 res = CreateIconIndirect( &info );
3146 else
3148 if (frame->color)
3150 if (!(info.hbmColor = create_color_bitmap( desiredx, desiredy )))
3152 release_icon_frame( icon, frame );
3153 release_user_handle_ptr( icon );
3154 if (resource_icon) DestroyIcon( resource_icon );
3155 return 0;
3157 stretch_bitmap( info.hbmColor, frame->color, desiredx, desiredy,
3158 frame->width, frame->height );
3160 if (!(info.hbmMask = CreateBitmap( desiredx, desiredy, 1, 1, NULL )))
3162 DeleteObject( info.hbmColor );
3163 release_icon_frame( icon, frame );
3164 release_user_handle_ptr( icon );
3165 if (resource_icon) DestroyIcon( resource_icon );
3166 return 0;
3168 stretch_bitmap( info.hbmMask, frame->mask, desiredx, desiredy,
3169 frame->width, frame->height );
3171 else
3173 info.hbmColor = NULL;
3175 if (!(info.hbmMask = CreateBitmap( desiredx, desiredy * 2, 1, 1, NULL )))
3177 release_user_handle_ptr( icon );
3178 if (resource_icon) DestroyIcon( resource_icon );
3179 return 0;
3181 stretch_bitmap( info.hbmMask, frame->mask, desiredx, desiredy * 2,
3182 frame->width, frame->height * 2 );
3185 res = CreateIconIndirect( &info );
3187 DeleteObject( info.hbmColor );
3188 DeleteObject( info.hbmMask );
3191 release_icon_frame( icon, frame );
3192 release_user_handle_ptr( icon );
3194 if (res && (flags & LR_COPYDELETEORG)) DestroyIcon( hnd );
3195 if (resource_icon) DestroyIcon( resource_icon );
3196 return res;
3199 return 0;
3203 /******************************************************************************
3204 * LoadBitmapW (USER32.@) Loads bitmap from the executable file
3206 * RETURNS
3207 * Success: Handle to specified bitmap
3208 * Failure: NULL
3210 HBITMAP WINAPI LoadBitmapW(
3211 HINSTANCE instance, /* [in] Handle to application instance */
3212 LPCWSTR name) /* [in] Address of bitmap resource name */
3214 return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
3217 /**********************************************************************
3218 * LoadBitmapA (USER32.@)
3220 * See LoadBitmapW.
3222 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
3224 return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );