user32: Make sure the driver CreateCursorIcon() entry point is always called.
[wine.git] / dlls / user32 / cursoricon.c
blobce25a9d649b97657c6ff4af801c6d67f78c51ec1
1 /*
2 * Cursor and icon support
4 * Copyright 1995 Alexandre Julliard
5 * 1996 Martin Von Loewis
6 * 1997 Alex Korobka
7 * 1998 Turchanov Sergey
8 * 2007 Henri Verbeet
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "config.h"
26 #include "wine/port.h"
28 #include <stdarg.h>
29 #include <string.h>
30 #include <stdlib.h>
32 #include "windef.h"
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "winerror.h"
36 #include "winnls.h"
37 #include "wine/exception.h"
38 #include "wine/server.h"
39 #include "controls.h"
40 #include "user_private.h"
41 #include "wine/debug.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
44 WINE_DECLARE_DEBUG_CHANNEL(icon);
45 WINE_DECLARE_DEBUG_CHANNEL(resource);
47 #include "pshpack1.h"
49 typedef struct {
50 BYTE bWidth;
51 BYTE bHeight;
52 BYTE bColorCount;
53 BYTE bReserved;
54 WORD xHotspot;
55 WORD yHotspot;
56 DWORD dwDIBSize;
57 DWORD dwDIBOffset;
58 } CURSORICONFILEDIRENTRY;
60 typedef struct
62 WORD idReserved;
63 WORD idType;
64 WORD idCount;
65 CURSORICONFILEDIRENTRY idEntries[1];
66 } CURSORICONFILEDIR;
68 #include "poppack.h"
70 static RECT CURSOR_ClipRect; /* Cursor clipping rect */
72 static HDC screen_dc;
74 static const WCHAR DISPLAYW[] = {'D','I','S','P','L','A','Y',0};
77 /**********************************************************************
78 * ICONCACHE for cursors/icons loaded with LR_SHARED.
80 * FIXME: This should not be allocated on the system heap, but on a
81 * subsystem-global heap (i.e. one for all Win16 processes,
82 * and one for each Win32 process).
84 typedef struct tagICONCACHE
86 struct tagICONCACHE *next;
88 HMODULE hModule;
89 HRSRC hRsrc;
90 HRSRC hGroupRsrc;
91 HICON hIcon;
93 INT count;
95 } ICONCACHE;
97 static ICONCACHE *IconAnchor = NULL;
99 static CRITICAL_SECTION IconCrst;
100 static CRITICAL_SECTION_DEBUG critsect_debug =
102 0, 0, &IconCrst,
103 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
104 0, 0, { (DWORD_PTR)(__FILE__ ": IconCrst") }
106 static CRITICAL_SECTION IconCrst = { &critsect_debug, -1, 0, 0, 0, 0 };
109 /**********************************************************************
110 * User objects management
113 struct cursoricon_frame
115 HBITMAP color; /* color bitmap */
116 HBITMAP alpha; /* pre-multiplied alpha bitmap for 32-bpp icons */
117 HBITMAP mask; /* mask bitmap (followed by color for 1-bpp icons) */
120 struct cursoricon_object
122 struct user_object obj; /* object header */
123 ULONG_PTR param; /* opaque param used by 16-bit code */
124 BOOL is_icon; /* whether icon or cursor */
125 UINT width;
126 UINT height;
127 POINT hotspot;
128 UINT num_frames; /* number of frames in the icon/cursor */
129 UINT ms_delay; /* delay between frames (in milliseconds) */
130 struct cursoricon_frame frames[1]; /* icon frame information */
133 static HICON alloc_icon_handle( UINT num_frames )
135 struct cursoricon_object *obj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
136 FIELD_OFFSET( struct cursoricon_object, frames[num_frames] ));
138 if (!obj) return 0;
139 obj->num_frames = num_frames;
140 return alloc_user_handle( &obj->obj, USER_ICON );
143 static struct cursoricon_object *get_icon_ptr( HICON handle )
145 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
146 if (obj == OBJ_OTHER_PROCESS)
148 WARN( "icon handle %p from other process\n", handle );
149 obj = NULL;
151 return obj;
154 static void release_icon_ptr( HICON handle, struct cursoricon_object *ptr )
156 release_user_handle_ptr( ptr );
159 static BOOL free_icon_handle( HICON handle )
161 struct cursoricon_object *obj = free_user_handle( handle, USER_ICON );
163 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
164 else if (obj)
166 ULONG_PTR param = obj->param;
167 UINT i;
169 for (i=0; i<obj->num_frames; i++)
171 if (obj->frames[i].alpha) DeleteObject( obj->frames[i].alpha );
172 if (obj->frames[i].color) DeleteObject( obj->frames[i].color );
173 DeleteObject( obj->frames[i].mask );
175 HeapFree( GetProcessHeap(), 0, obj );
176 if (wow_handlers.free_icon_param && param) wow_handlers.free_icon_param( param );
177 USER_Driver->pDestroyCursorIcon( handle );
178 return TRUE;
180 return FALSE;
183 ULONG_PTR get_icon_param( HICON handle )
185 ULONG_PTR ret = 0;
186 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
188 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
189 else if (obj)
191 ret = obj->param;
192 release_user_handle_ptr( obj );
194 return ret;
197 ULONG_PTR set_icon_param( HICON handle, ULONG_PTR param )
199 ULONG_PTR ret = 0;
200 struct cursoricon_object *obj = get_user_handle_ptr( handle, USER_ICON );
202 if (obj == OBJ_OTHER_PROCESS) WARN( "icon handle %p from other process\n", handle );
203 else if (obj)
205 ret = obj->param;
206 obj->param = param;
207 release_user_handle_ptr( obj );
209 return ret;
213 /***********************************************************************
214 * map_fileW
216 * Helper function to map a file to memory:
217 * name - file name
218 * [RETURN] ptr - pointer to mapped file
219 * [RETURN] filesize - pointer size of file to be stored if not NULL
221 static void *map_fileW( LPCWSTR name, LPDWORD filesize )
223 HANDLE hFile, hMapping;
224 LPVOID ptr = NULL;
226 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
227 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
228 if (hFile != INVALID_HANDLE_VALUE)
230 hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
231 if (hMapping)
233 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
234 CloseHandle( hMapping );
235 if (filesize)
236 *filesize = GetFileSize( hFile, NULL );
238 CloseHandle( hFile );
240 return ptr;
244 /***********************************************************************
245 * get_dib_width_bytes
247 * Return the width of a DIB bitmap in bytes. DIB bitmap data is 32-bit aligned.
249 static int get_dib_width_bytes( int width, int depth )
251 int words;
253 switch(depth)
255 case 1: words = (width + 31) / 32; break;
256 case 4: words = (width + 7) / 8; break;
257 case 8: words = (width + 3) / 4; break;
258 case 15:
259 case 16: words = (width + 1) / 2; break;
260 case 24: words = (width * 3 + 3)/4; break;
261 default:
262 WARN("(%d): Unsupported depth\n", depth );
263 /* fall through */
264 case 32:
265 words = width;
267 return 4 * words;
271 /***********************************************************************
272 * bitmap_info_size
274 * Return the size of the bitmap info structure including color table.
276 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
278 unsigned int colors, size, masks = 0;
280 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
282 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
283 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
284 return sizeof(BITMAPCOREHEADER) + colors *
285 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
287 else /* assume BITMAPINFOHEADER */
289 colors = info->bmiHeader.biClrUsed;
290 if (colors > 256) /* buffer overflow otherwise */
291 colors = 256;
292 if (!colors && (info->bmiHeader.biBitCount <= 8))
293 colors = 1 << info->bmiHeader.biBitCount;
294 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
295 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
296 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
301 /***********************************************************************
302 * copy_bitmap
304 * Helper function to duplicate a bitmap.
306 static HBITMAP copy_bitmap( HBITMAP bitmap )
308 HDC src, dst;
309 HBITMAP new_bitmap;
310 BITMAP bmp;
312 if (!bitmap) return 0;
313 if (!GetObjectW( bitmap, sizeof(bmp), &bmp )) return 0;
315 src = CreateCompatibleDC( 0 );
316 dst = CreateCompatibleDC( 0 );
317 SelectObject( src, bitmap );
318 new_bitmap = CreateCompatibleBitmap( src, bmp.bmWidth, bmp.bmHeight );
319 SelectObject( dst, new_bitmap );
320 BitBlt( dst, 0, 0, bmp.bmWidth, bmp.bmHeight, src, 0, 0, SRCCOPY );
321 DeleteDC( dst );
322 DeleteDC( src );
323 return new_bitmap;
327 /***********************************************************************
328 * is_dib_monochrome
330 * Returns whether a DIB can be converted to a monochrome DDB.
332 * A DIB can be converted if its color table contains only black and
333 * white. Black must be the first color in the color table.
335 * Note : If the first color in the color table is white followed by
336 * black, we can't convert it to a monochrome DDB with
337 * SetDIBits, because black and white would be inverted.
339 static BOOL is_dib_monochrome( const BITMAPINFO* info )
341 if (info->bmiHeader.biBitCount != 1) return FALSE;
343 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
345 const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
347 /* Check if the first color is black */
348 if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
350 rgb++;
352 /* Check if the second color is white */
353 return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
354 && (rgb->rgbtBlue == 0xff));
356 else return FALSE;
358 else /* assume BITMAPINFOHEADER */
360 const RGBQUAD *rgb = info->bmiColors;
362 /* Check if the first color is black */
363 if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
364 (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
366 rgb++;
368 /* Check if the second color is white */
369 return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
370 && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
372 else return FALSE;
376 /***********************************************************************
377 * DIB_GetBitmapInfo
379 * Get the info from a bitmap header.
380 * Return 1 for INFOHEADER, 0 for COREHEADER, -1 in case of failure.
382 static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
383 LONG *height, WORD *bpp, DWORD *compr )
385 if (header->biSize == sizeof(BITMAPCOREHEADER))
387 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
388 *width = core->bcWidth;
389 *height = core->bcHeight;
390 *bpp = core->bcBitCount;
391 *compr = 0;
392 return 0;
394 else if (header->biSize >= sizeof(BITMAPINFOHEADER))
396 *width = header->biWidth;
397 *height = header->biHeight;
398 *bpp = header->biBitCount;
399 *compr = header->biCompression;
400 return 1;
402 ERR("(%d): unknown/wrong size for header\n", header->biSize );
403 return -1;
406 /**********************************************************************
407 * CURSORICON_FindSharedIcon
409 static HICON CURSORICON_FindSharedIcon( HMODULE hModule, HRSRC hRsrc )
411 HICON hIcon = 0;
412 ICONCACHE *ptr;
414 EnterCriticalSection( &IconCrst );
416 for ( ptr = IconAnchor; ptr; ptr = ptr->next )
417 if ( ptr->hModule == hModule && ptr->hRsrc == hRsrc )
419 ptr->count++;
420 hIcon = ptr->hIcon;
421 break;
424 LeaveCriticalSection( &IconCrst );
426 return hIcon;
429 /*************************************************************************
430 * CURSORICON_FindCache
432 * Given a handle, find the corresponding cache element
434 * PARAMS
435 * Handle [I] handle to an Image
437 * RETURNS
438 * Success: The cache entry
439 * Failure: NULL
442 static ICONCACHE* CURSORICON_FindCache(HICON hIcon)
444 ICONCACHE *ptr;
445 ICONCACHE *pRet=NULL;
446 BOOL IsFound = FALSE;
448 EnterCriticalSection( &IconCrst );
450 for (ptr = IconAnchor; ptr != NULL && !IsFound; ptr = ptr->next)
452 if ( hIcon == ptr->hIcon )
454 IsFound = TRUE;
455 pRet = ptr;
459 LeaveCriticalSection( &IconCrst );
461 return pRet;
464 /**********************************************************************
465 * CURSORICON_AddSharedIcon
467 static void CURSORICON_AddSharedIcon( HMODULE hModule, HRSRC hRsrc, HRSRC hGroupRsrc, HICON hIcon )
469 ICONCACHE *ptr = HeapAlloc( GetProcessHeap(), 0, sizeof(ICONCACHE) );
470 if ( !ptr ) return;
472 ptr->hModule = hModule;
473 ptr->hRsrc = hRsrc;
474 ptr->hIcon = hIcon;
475 ptr->hGroupRsrc = hGroupRsrc;
476 ptr->count = 1;
478 EnterCriticalSection( &IconCrst );
479 ptr->next = IconAnchor;
480 IconAnchor = ptr;
481 LeaveCriticalSection( &IconCrst );
484 /**********************************************************************
485 * CURSORICON_DelSharedIcon
487 static INT CURSORICON_DelSharedIcon( HICON hIcon )
489 INT count = -1;
490 ICONCACHE *ptr;
492 EnterCriticalSection( &IconCrst );
494 for ( ptr = IconAnchor; ptr; ptr = ptr->next )
495 if ( ptr->hIcon == hIcon )
497 if ( ptr->count > 0 ) ptr->count--;
498 count = ptr->count;
499 break;
502 LeaveCriticalSection( &IconCrst );
504 return count;
507 /**********************************************************************
508 * get_icon_size
510 BOOL get_icon_size( HICON handle, SIZE *size )
512 struct cursoricon_object *info;
514 if (!(info = get_icon_ptr( handle ))) return FALSE;
515 size->cx = info->width;
516 size->cy = info->height;
517 release_icon_ptr( handle, info );
518 return TRUE;
522 * The following macro functions account for the irregularities of
523 * accessing cursor and icon resources in files and resource entries.
525 typedef BOOL (*fnGetCIEntry)( LPVOID dir, int n,
526 int *width, int *height, int *bits );
528 /**********************************************************************
529 * CURSORICON_FindBestIcon
531 * Find the icon closest to the requested size and bit depth.
533 static int CURSORICON_FindBestIcon( LPVOID dir, fnGetCIEntry get_entry,
534 int width, int height, int depth )
536 int i, cx, cy, bits, bestEntry = -1;
537 UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
538 UINT iTempXDiff, iTempYDiff, iTempColorDiff;
540 /* Find Best Fit */
541 iTotalDiff = 0xFFFFFFFF;
542 iColorDiff = 0xFFFFFFFF;
543 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
545 iTempXDiff = abs(width - cx);
546 iTempYDiff = abs(height - cy);
548 if(iTotalDiff > (iTempXDiff + iTempYDiff))
550 iXDiff = iTempXDiff;
551 iYDiff = iTempYDiff;
552 iTotalDiff = iXDiff + iYDiff;
556 /* Find Best Colors for Best Fit */
557 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
559 if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
561 iTempColorDiff = abs(depth - bits);
562 if(iColorDiff > iTempColorDiff)
564 bestEntry = i;
565 iColorDiff = iTempColorDiff;
570 return bestEntry;
573 static BOOL CURSORICON_GetResIconEntry( LPVOID dir, int n,
574 int *width, int *height, int *bits )
576 CURSORICONDIR *resdir = dir;
577 ICONRESDIR *icon;
579 if ( resdir->idCount <= n )
580 return FALSE;
581 icon = &resdir->idEntries[n].ResInfo.icon;
582 *width = icon->bWidth;
583 *height = icon->bHeight;
584 *bits = resdir->idEntries[n].wBitCount;
585 return TRUE;
588 /**********************************************************************
589 * CURSORICON_FindBestCursor
591 * Find the cursor closest to the requested size.
593 * FIXME: parameter 'color' ignored.
595 static int CURSORICON_FindBestCursor( LPVOID dir, fnGetCIEntry get_entry,
596 int width, int height, int depth )
598 int i, maxwidth, maxheight, cx, cy, bits, bestEntry = -1;
600 /* Double height to account for AND and XOR masks */
602 height *= 2;
604 /* First find the largest one smaller than or equal to the requested size*/
606 maxwidth = maxheight = 0;
607 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
609 if ((cx <= width) && (cy <= height) &&
610 (cx > maxwidth) && (cy > maxheight))
612 bestEntry = i;
613 maxwidth = cx;
614 maxheight = cy;
617 if (bestEntry != -1) return bestEntry;
619 /* Now find the smallest one larger than the requested size */
621 maxwidth = maxheight = 255;
622 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
624 if (((cx < maxwidth) && (cy < maxheight)) || (bestEntry == -1))
626 bestEntry = i;
627 maxwidth = cx;
628 maxheight = cy;
632 return bestEntry;
635 static BOOL CURSORICON_GetResCursorEntry( LPVOID dir, int n,
636 int *width, int *height, int *bits )
638 CURSORICONDIR *resdir = dir;
639 CURSORDIR *cursor;
641 if ( resdir->idCount <= n )
642 return FALSE;
643 cursor = &resdir->idEntries[n].ResInfo.cursor;
644 *width = cursor->wWidth;
645 *height = cursor->wHeight;
646 *bits = resdir->idEntries[n].wBitCount;
647 return TRUE;
650 static CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( CURSORICONDIR * dir,
651 int width, int height, int depth )
653 int n;
655 n = CURSORICON_FindBestIcon( dir, CURSORICON_GetResIconEntry,
656 width, height, depth );
657 if ( n < 0 )
658 return NULL;
659 return &dir->idEntries[n];
662 static CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( CURSORICONDIR *dir,
663 int width, int height, int depth )
665 int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetResCursorEntry,
666 width, height, depth );
667 if ( n < 0 )
668 return NULL;
669 return &dir->idEntries[n];
672 static BOOL CURSORICON_GetFileEntry( LPVOID dir, int n,
673 int *width, int *height, int *bits )
675 CURSORICONFILEDIR *filedir = dir;
676 CURSORICONFILEDIRENTRY *entry;
677 BITMAPINFOHEADER *info;
679 if ( filedir->idCount <= n )
680 return FALSE;
681 entry = &filedir->idEntries[n];
682 /* FIXME: check against file size */
683 info = (BITMAPINFOHEADER *)((char *)dir + entry->dwDIBOffset);
684 *width = entry->bWidth;
685 *height = entry->bHeight;
686 *bits = info->biBitCount;
687 return TRUE;
690 static CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( CURSORICONFILEDIR *dir,
691 int width, int height, int depth )
693 int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetFileEntry,
694 width, height, depth );
695 if ( n < 0 )
696 return NULL;
697 return &dir->idEntries[n];
700 static CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( CURSORICONFILEDIR *dir,
701 int width, int height, int depth )
703 int n = CURSORICON_FindBestIcon( dir, CURSORICON_GetFileEntry,
704 width, height, depth );
705 if ( n < 0 )
706 return NULL;
707 return &dir->idEntries[n];
710 /***********************************************************************
711 * bmi_has_alpha
713 static BOOL bmi_has_alpha( const BITMAPINFO *info, const void *bits )
715 int i;
716 BOOL has_alpha = FALSE;
717 const unsigned char *ptr = bits;
719 if (info->bmiHeader.biBitCount != 32) return FALSE;
720 for (i = 0; i < info->bmiHeader.biWidth * abs(info->bmiHeader.biHeight); i++, ptr += 4)
721 if ((has_alpha = (ptr[3] != 0))) break;
722 return has_alpha;
725 /***********************************************************************
726 * create_alpha_bitmap
728 * Create the alpha bitmap for a 32-bpp icon that has an alpha channel.
730 static HBITMAP create_alpha_bitmap( HBITMAP color, HBITMAP mask,
731 const BITMAPINFO *src_info, const void *color_bits )
733 HBITMAP alpha = 0;
734 BITMAPINFO *info = NULL;
735 BITMAP bm;
736 HDC hdc;
737 void *bits;
738 unsigned char *ptr;
739 int i;
741 if (!GetObjectW( color, sizeof(bm), &bm )) return 0;
742 if (bm.bmBitsPixel != 32) return 0;
744 if (!(hdc = CreateCompatibleDC( 0 ))) return 0;
745 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto done;
746 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
747 info->bmiHeader.biWidth = bm.bmWidth;
748 info->bmiHeader.biHeight = -bm.bmHeight;
749 info->bmiHeader.biPlanes = 1;
750 info->bmiHeader.biBitCount = 32;
751 info->bmiHeader.biCompression = BI_RGB;
752 info->bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
753 info->bmiHeader.biXPelsPerMeter = 0;
754 info->bmiHeader.biYPelsPerMeter = 0;
755 info->bmiHeader.biClrUsed = 0;
756 info->bmiHeader.biClrImportant = 0;
757 if (!(alpha = CreateDIBSection( hdc, info, DIB_RGB_COLORS, &bits, NULL, 0 ))) goto done;
759 if (src_info)
761 SelectObject( hdc, alpha );
762 StretchDIBits( hdc, 0, 0, bm.bmWidth, bm.bmHeight,
763 0, 0, src_info->bmiHeader.biWidth, src_info->bmiHeader.biHeight,
764 color_bits, src_info, DIB_RGB_COLORS, SRCCOPY );
767 else
769 GetDIBits( hdc, color, 0, bm.bmHeight, bits, info, DIB_RGB_COLORS );
770 if (!bmi_has_alpha( info, bits ))
772 DeleteObject( alpha );
773 alpha = 0;
774 goto done;
778 /* pre-multiply by alpha */
779 for (i = 0, ptr = bits; i < bm.bmWidth * bm.bmHeight; i++, ptr += 4)
781 unsigned int alpha = ptr[3];
782 ptr[0] = ptr[0] * alpha / 255;
783 ptr[1] = ptr[1] * alpha / 255;
784 ptr[2] = ptr[2] * alpha / 255;
787 done:
788 DeleteDC( hdc );
789 HeapFree( GetProcessHeap(), 0, info );
790 return alpha;
794 /***********************************************************************
795 * create_icon_bitmaps
797 * Create the color, mask and alpha bitmaps from the DIB info.
799 static BOOL create_icon_bitmaps( const BITMAPINFO *bmi, int width, int height,
800 HBITMAP *color, HBITMAP *mask, HBITMAP *alpha )
802 BOOL monochrome = is_dib_monochrome( bmi );
803 unsigned int size = bitmap_info_size( bmi, DIB_RGB_COLORS );
804 BITMAPINFO *info;
805 void *color_bits, *mask_bits;
806 BOOL ret = FALSE;
807 HDC hdc = 0;
809 if (!(info = HeapAlloc( GetProcessHeap(), 0, max( size, FIELD_OFFSET( BITMAPINFO, bmiColors[2] )))))
810 return FALSE;
811 if (!(hdc = CreateCompatibleDC( 0 ))) goto done;
813 memcpy( info, bmi, size );
814 info->bmiHeader.biHeight /= 2;
816 color_bits = (char *)bmi + size;
817 mask_bits = (char *)color_bits +
818 get_dib_width_bytes( bmi->bmiHeader.biWidth,
819 bmi->bmiHeader.biBitCount ) * abs(info->bmiHeader.biHeight);
821 *alpha = 0;
822 if (monochrome)
824 if (!(*mask = CreateBitmap( width, height * 2, 1, 1, NULL ))) goto done;
825 *color = 0;
827 /* copy color data into second half of mask bitmap */
828 SelectObject( hdc, *mask );
829 StretchDIBits( hdc, 0, height, width, height,
830 0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
831 color_bits, info, DIB_RGB_COLORS, SRCCOPY );
833 else
835 if (!(*mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
836 if (!(*color = CreateBitmap( width, height, GetDeviceCaps( screen_dc, PLANES ),
837 GetDeviceCaps( screen_dc, BITSPIXEL ), NULL )))
839 DeleteObject( *mask );
840 goto done;
842 SelectObject( hdc, *color );
843 StretchDIBits( hdc, 0, 0, width, height,
844 0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
845 color_bits, info, DIB_RGB_COLORS, SRCCOPY );
847 if (bmi_has_alpha( info, color_bits ))
848 *alpha = create_alpha_bitmap( *color, *mask, info, color_bits );
850 /* convert info to monochrome to copy the mask */
851 info->bmiHeader.biBitCount = 1;
852 if (info->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
854 RGBQUAD *rgb = info->bmiColors;
856 info->bmiHeader.biClrUsed = info->bmiHeader.biClrImportant = 2;
857 rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
858 rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
859 rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
861 else
863 RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)info) + 1);
865 rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
866 rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
870 SelectObject( hdc, *mask );
871 StretchDIBits( hdc, 0, 0, width, height,
872 0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
873 mask_bits, info, DIB_RGB_COLORS, SRCCOPY );
874 ret = TRUE;
876 done:
877 DeleteDC( hdc );
878 HeapFree( GetProcessHeap(), 0, info );
879 return ret;
882 static HICON CURSORICON_CreateIconFromBMI( BITMAPINFO *bmi,
883 POINT hotspot, BOOL bIcon,
884 DWORD dwVersion,
885 INT width, INT height,
886 UINT cFlag )
888 HICON hObj;
889 HBITMAP color = 0, mask = 0, alpha = 0;
890 BOOL do_stretch;
892 if (dwVersion == 0x00020000)
894 FIXME_(cursor)("\t2.xx resources are not supported\n");
895 return 0;
898 /* Check bitmap header */
900 if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
901 (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER) ||
902 bmi->bmiHeader.biCompression != BI_RGB) )
904 WARN_(cursor)("\tinvalid resource bitmap header.\n");
905 return 0;
908 if (!width) width = bmi->bmiHeader.biWidth;
909 if (!height) height = bmi->bmiHeader.biHeight/2;
910 do_stretch = (bmi->bmiHeader.biHeight/2 != height) ||
911 (bmi->bmiHeader.biWidth != width);
913 /* Scale the hotspot */
914 if (bIcon)
916 hotspot.x = width / 2;
917 hotspot.y = height / 2;
919 else if (do_stretch)
921 hotspot.x = (hotspot.x * width) / bmi->bmiHeader.biWidth;
922 hotspot.y = (hotspot.y * height) / (bmi->bmiHeader.biHeight / 2);
925 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
926 if (!screen_dc) return 0;
928 if (!create_icon_bitmaps( bmi, width, height, &color, &mask, &alpha )) return 0;
930 hObj = alloc_icon_handle(1);
931 if (hObj)
933 struct cursoricon_object *info = get_icon_ptr( hObj );
935 info->is_icon = bIcon;
936 info->hotspot = hotspot;
937 info->width = width;
938 info->height = height;
939 info->frames[0].color = color;
940 info->frames[0].mask = mask;
941 info->frames[0].alpha = alpha;
942 release_icon_ptr( hObj, info );
944 else
946 DeleteObject( color );
947 DeleteObject( alpha );
948 DeleteObject( mask );
950 return hObj;
954 /**********************************************************************
955 * .ANI cursor support
957 #define RIFF_FOURCC( c0, c1, c2, c3 ) \
958 ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
959 ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
961 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
962 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
963 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
964 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
965 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
966 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
968 #define ANI_FLAG_ICON 0x1
969 #define ANI_FLAG_SEQUENCE 0x2
971 typedef struct {
972 DWORD header_size;
973 DWORD num_frames;
974 DWORD num_steps;
975 DWORD width;
976 DWORD height;
977 DWORD bpp;
978 DWORD num_planes;
979 DWORD display_rate;
980 DWORD flags;
981 } ani_header;
983 typedef struct {
984 DWORD data_size;
985 const unsigned char *data;
986 } riff_chunk_t;
988 static void dump_ani_header( const ani_header *header )
990 TRACE(" header size: %d\n", header->header_size);
991 TRACE(" frames: %d\n", header->num_frames);
992 TRACE(" steps: %d\n", header->num_steps);
993 TRACE(" width: %d\n", header->width);
994 TRACE(" height: %d\n", header->height);
995 TRACE(" bpp: %d\n", header->bpp);
996 TRACE(" planes: %d\n", header->num_planes);
997 TRACE(" display rate: %d\n", header->display_rate);
998 TRACE(" flags: 0x%08x\n", header->flags);
1003 * RIFF:
1004 * DWORD "RIFF"
1005 * DWORD size
1006 * DWORD riff_id
1007 * BYTE[] data
1009 * LIST:
1010 * DWORD "LIST"
1011 * DWORD size
1012 * DWORD list_id
1013 * BYTE[] data
1015 * CHUNK:
1016 * DWORD chunk_id
1017 * DWORD size
1018 * BYTE[] data
1020 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
1022 const unsigned char *ptr = parent_chunk->data;
1023 const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
1025 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
1027 while (ptr < end)
1029 if ((!chunk_type && *(const DWORD *)ptr == chunk_id )
1030 || (chunk_type && *(const DWORD *)ptr == chunk_type && *((const DWORD *)ptr + 2) == chunk_id ))
1032 ptr += sizeof(DWORD);
1033 chunk->data_size = (*(const DWORD *)ptr + 1) & ~1;
1034 ptr += sizeof(DWORD);
1035 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
1036 chunk->data = ptr;
1038 return;
1041 ptr += sizeof(DWORD);
1042 ptr += (*(const DWORD *)ptr + 1) & ~1;
1043 ptr += sizeof(DWORD);
1049 * .ANI layout:
1051 * RIFF:'ACON' RIFF chunk
1052 * |- CHUNK:'anih' Header
1053 * |- CHUNK:'seq ' Sequence information (optional)
1054 * \- LIST:'fram' Frame list
1055 * |- CHUNK:icon Cursor frames
1056 * |- CHUNK:icon
1057 * |- ...
1058 * \- CHUNK:icon
1060 static HCURSOR CURSORICON_CreateIconFromANI( const LPBYTE bits, DWORD bits_size,
1061 INT width, INT height, INT depth )
1063 struct cursoricon_object *info;
1064 ani_header header = {0};
1065 HCURSOR cursor = 0;
1066 UINT i, error = 0;
1068 riff_chunk_t root_chunk = { bits_size, bits };
1069 riff_chunk_t ACON_chunk = {0};
1070 riff_chunk_t anih_chunk = {0};
1071 riff_chunk_t fram_chunk = {0};
1072 const unsigned char *icon_chunk;
1073 const unsigned char *icon_data;
1075 TRACE("bits %p, bits_size %d\n", bits, bits_size);
1077 riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1078 if (!ACON_chunk.data)
1080 ERR("Failed to get root chunk.\n");
1081 return 0;
1084 riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1085 if (!anih_chunk.data)
1087 ERR("Failed to get 'anih' chunk.\n");
1088 return 0;
1090 memcpy( &header, anih_chunk.data, sizeof(header) );
1091 dump_ani_header( &header );
1093 riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1094 if (!fram_chunk.data)
1096 ERR("Failed to get icon list.\n");
1097 return 0;
1100 cursor = alloc_icon_handle( header.num_frames );
1101 if (!cursor) return 0;
1103 info = get_icon_ptr( cursor );
1104 info->is_icon = FALSE;
1106 /* The .ANI stores the display rate in 1/60s, we store the delay between frames in ms */
1107 info->ms_delay = (100 * header.display_rate) / 6;
1109 icon_chunk = fram_chunk.data;
1110 icon_data = fram_chunk.data + (2 * sizeof(DWORD));
1111 for (i=0; i<header.num_frames; i++)
1113 DWORD chunk_size = *(DWORD *)(icon_chunk + sizeof(DWORD));
1114 struct cursoricon_frame *frame = &info->frames[i];
1115 CURSORICONFILEDIRENTRY *entry;
1116 BITMAPINFO *bmi;
1118 entry = CURSORICON_FindBestIconFile( (CURSORICONFILEDIR *) icon_data,
1119 width, height, depth );
1121 bmi = (BITMAPINFO *) (icon_data + entry->dwDIBOffset);
1122 info->hotspot.x = entry->xHotspot;
1123 info->hotspot.y = entry->yHotspot;
1124 if (!header.width || !header.height)
1126 header.width = entry->bWidth;
1127 header.height = entry->bHeight;
1130 /* Grab a frame from the animation */
1131 if (!create_icon_bitmaps( bmi, header.width, header.height,
1132 &frame->color, &frame->mask, &frame->alpha ))
1134 FIXME_(cursor)("failed to convert animated cursor frame.\n");
1135 error = TRUE;
1136 if (i == 0)
1138 FIXME_(cursor)("Completely failed to create animated cursor!\n");
1139 info->num_frames = 0;
1140 release_icon_ptr( cursor, info );
1141 free_icon_handle( cursor );
1142 return 0;
1144 break;
1147 /* Advance to the next chunk */
1148 icon_chunk += chunk_size + (2 * sizeof(DWORD));
1149 icon_data = icon_chunk + (2 * sizeof(DWORD));
1152 /* There was an error but we at least decoded the first frame, so just use that frame */
1153 if (error)
1155 FIXME_(cursor)("Error creating animated cursor, only using first frame!\n");
1156 for (i=1; i<info->num_frames; i++)
1158 if (info->frames[i].mask) DeleteObject( info->frames[i].mask );
1159 if (info->frames[i].color) DeleteObject( info->frames[i].color );
1160 if (info->frames[i].alpha) DeleteObject( info->frames[i].alpha );
1162 info->num_frames = 1;
1163 info->ms_delay = 0;
1165 info->width = header.width;
1166 info->height = header.height;
1167 release_icon_ptr( cursor, info );
1169 return cursor;
1173 /**********************************************************************
1174 * CreateIconFromResourceEx (USER32.@)
1176 * FIXME: Convert to mono when cFlag is LR_MONOCHROME. Do something
1177 * with cbSize parameter as well.
1179 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1180 BOOL bIcon, DWORD dwVersion,
1181 INT width, INT height,
1182 UINT cFlag )
1184 POINT hotspot;
1185 BITMAPINFO *bmi;
1186 HICON icon;
1188 TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s %s\n",
1189 bits, cbSize, dwVersion, width, height,
1190 bIcon ? "icon" : "cursor", (cFlag & LR_MONOCHROME) ? "mono" : "" );
1192 if (!bits) return 0;
1194 if (bIcon)
1196 hotspot.x = width / 2;
1197 hotspot.y = height / 2;
1198 bmi = (BITMAPINFO *)bits;
1200 else /* get the hotspot */
1202 SHORT *pt = (SHORT *)bits;
1203 hotspot.x = pt[0];
1204 hotspot.y = pt[1];
1205 bmi = (BITMAPINFO *)(pt + 2);
1208 icon = CURSORICON_CreateIconFromBMI( bmi, hotspot, bIcon, dwVersion,
1209 width, height, cFlag );
1210 if (icon) USER_Driver->pCreateCursorIcon( icon );
1211 return icon;
1215 /**********************************************************************
1216 * CreateIconFromResource (USER32.@)
1218 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1219 BOOL bIcon, DWORD dwVersion)
1221 return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
1225 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1226 INT width, INT height, INT depth,
1227 BOOL fCursor, UINT loadflags)
1229 CURSORICONFILEDIRENTRY *entry;
1230 CURSORICONFILEDIR *dir;
1231 DWORD filesize = 0;
1232 HICON hIcon = 0;
1233 LPBYTE bits;
1234 POINT hotspot;
1236 TRACE("loading %s\n", debugstr_w( filename ));
1238 bits = map_fileW( filename, &filesize );
1239 if (!bits)
1240 return hIcon;
1242 /* Check for .ani. */
1243 if (memcmp( bits, "RIFF", 4 ) == 0)
1245 hIcon = CURSORICON_CreateIconFromANI( bits, filesize, width, height,
1246 depth );
1247 goto end;
1250 dir = (CURSORICONFILEDIR*) bits;
1251 if ( filesize < sizeof(*dir) )
1252 goto end;
1254 if ( filesize < (sizeof(*dir) + sizeof(dir->idEntries[0])*(dir->idCount-1)) )
1255 goto end;
1257 if ( fCursor )
1258 entry = CURSORICON_FindBestCursorFile( dir, width, height, depth );
1259 else
1260 entry = CURSORICON_FindBestIconFile( dir, width, height, depth );
1262 if ( !entry )
1263 goto end;
1265 /* check that we don't run off the end of the file */
1266 if ( entry->dwDIBOffset > filesize )
1267 goto end;
1268 if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1269 goto end;
1271 hotspot.x = entry->xHotspot;
1272 hotspot.y = entry->yHotspot;
1273 hIcon = CURSORICON_CreateIconFromBMI( (BITMAPINFO *)&bits[entry->dwDIBOffset],
1274 hotspot, !fCursor, 0x00030000,
1275 width, height, loadflags );
1276 end:
1277 TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1278 UnmapViewOfFile( bits );
1279 if (hIcon) USER_Driver->pCreateCursorIcon( hIcon );
1280 return hIcon;
1283 /**********************************************************************
1284 * CURSORICON_Load
1286 * Load a cursor or icon from resource or file.
1288 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1289 INT width, INT height, INT depth,
1290 BOOL fCursor, UINT loadflags)
1292 HANDLE handle = 0;
1293 HICON hIcon = 0;
1294 HRSRC hRsrc, hGroupRsrc;
1295 CURSORICONDIR *dir;
1296 CURSORICONDIRENTRY *dirEntry;
1297 LPBYTE bits;
1298 WORD wResId;
1299 DWORD dwBytesInRes;
1301 TRACE("%p, %s, %dx%d, depth %d, fCursor %d, flags 0x%04x\n",
1302 hInstance, debugstr_w(name), width, height, depth, fCursor, loadflags);
1304 if ( loadflags & LR_LOADFROMFILE ) /* Load from file */
1305 return CURSORICON_LoadFromFile( name, width, height, depth, fCursor, loadflags );
1307 if (!hInstance) hInstance = user32_module; /* Load OEM cursor/icon */
1309 /* don't cache 16-bit instances (FIXME: should never get 16-bit instances in the first place) */
1310 if ((ULONG_PTR)hInstance >> 16 == 0) loadflags &= ~LR_SHARED;
1312 /* Get directory resource ID */
1314 if (!(hRsrc = FindResourceW( hInstance, name,
1315 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1316 return 0;
1317 hGroupRsrc = hRsrc;
1319 /* Find the best entry in the directory */
1321 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1322 if (!(dir = LockResource( handle ))) return 0;
1323 if (fCursor)
1324 dirEntry = CURSORICON_FindBestCursorRes( dir, width, height, depth );
1325 else
1326 dirEntry = CURSORICON_FindBestIconRes( dir, width, height, depth );
1327 if (!dirEntry) return 0;
1328 wResId = dirEntry->wResId;
1329 dwBytesInRes = dirEntry->dwBytesInRes;
1330 FreeResource( handle );
1332 /* Load the resource */
1334 if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1335 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1337 /* If shared icon, check whether it was already loaded */
1338 if ( (loadflags & LR_SHARED)
1339 && (hIcon = CURSORICON_FindSharedIcon( hInstance, hRsrc ) ) != 0 )
1340 return hIcon;
1342 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1343 bits = LockResource( handle );
1344 hIcon = CreateIconFromResourceEx( bits, dwBytesInRes,
1345 !fCursor, 0x00030000, width, height, loadflags);
1346 FreeResource( handle );
1348 /* If shared icon, add to icon cache */
1350 if ( hIcon && (loadflags & LR_SHARED) )
1351 CURSORICON_AddSharedIcon( hInstance, hRsrc, hGroupRsrc, hIcon );
1353 return hIcon;
1357 /*************************************************************************
1358 * CURSORICON_ExtCopy
1360 * Copies an Image from the Cache if LR_COPYFROMRESOURCE is specified
1362 * PARAMS
1363 * Handle [I] handle to an Image
1364 * nType [I] Type of Handle (IMAGE_CURSOR | IMAGE_ICON)
1365 * iDesiredCX [I] The Desired width of the Image
1366 * iDesiredCY [I] The desired height of the Image
1367 * nFlags [I] The flags from CopyImage
1369 * RETURNS
1370 * Success: The new handle of the Image
1372 * NOTES
1373 * LR_COPYDELETEORG and LR_MONOCHROME are currently not implemented.
1374 * LR_MONOCHROME should be implemented by CreateIconFromResourceEx.
1375 * LR_COPYFROMRESOURCE will only work if the Image is in the Cache.
1380 static HICON CURSORICON_ExtCopy(HICON hIcon, UINT nType,
1381 INT iDesiredCX, INT iDesiredCY,
1382 UINT nFlags)
1384 HICON hNew=0;
1386 TRACE_(icon)("hIcon %p, nType %u, iDesiredCX %i, iDesiredCY %i, nFlags %u\n",
1387 hIcon, nType, iDesiredCX, iDesiredCY, nFlags);
1389 if(hIcon == 0)
1391 return 0;
1394 /* Best Fit or Monochrome */
1395 if( (nFlags & LR_COPYFROMRESOURCE
1396 && (iDesiredCX > 0 || iDesiredCY > 0))
1397 || nFlags & LR_MONOCHROME)
1399 ICONCACHE* pIconCache = CURSORICON_FindCache(hIcon);
1401 /* Not Found in Cache, then do a straight copy
1403 if(pIconCache == NULL)
1405 hNew = CopyIcon( hIcon );
1406 if(nFlags & LR_COPYFROMRESOURCE)
1408 TRACE_(icon)("LR_COPYFROMRESOURCE: Failed to load from cache\n");
1411 else
1413 int iTargetCY = iDesiredCY, iTargetCX = iDesiredCX;
1414 LPBYTE pBits;
1415 HANDLE hMem;
1416 HRSRC hRsrc;
1417 DWORD dwBytesInRes;
1418 WORD wResId;
1419 CURSORICONDIR *pDir;
1420 CURSORICONDIRENTRY *pDirEntry;
1421 BOOL bIsIcon = (nType == IMAGE_ICON);
1423 /* Completing iDesiredCX CY for Monochrome Bitmaps if needed
1425 if(((nFlags & LR_MONOCHROME) && !(nFlags & LR_COPYFROMRESOURCE))
1426 || (iDesiredCX == 0 && iDesiredCY == 0))
1428 iDesiredCY = GetSystemMetrics(bIsIcon ?
1429 SM_CYICON : SM_CYCURSOR);
1430 iDesiredCX = GetSystemMetrics(bIsIcon ?
1431 SM_CXICON : SM_CXCURSOR);
1434 /* Retrieve the CURSORICONDIRENTRY
1436 if (!(hMem = LoadResource( pIconCache->hModule ,
1437 pIconCache->hGroupRsrc)))
1439 return 0;
1441 if (!(pDir = LockResource( hMem )))
1443 return 0;
1446 /* Find Best Fit
1448 if(bIsIcon)
1450 pDirEntry = CURSORICON_FindBestIconRes(
1451 pDir, iDesiredCX, iDesiredCY, 256 );
1453 else
1455 pDirEntry = CURSORICON_FindBestCursorRes(
1456 pDir, iDesiredCX, iDesiredCY, 1);
1459 wResId = pDirEntry->wResId;
1460 dwBytesInRes = pDirEntry->dwBytesInRes;
1461 FreeResource(hMem);
1463 TRACE_(icon)("ResID %u, BytesInRes %u, Width %d, Height %d DX %d, DY %d\n",
1464 wResId, dwBytesInRes, pDirEntry->ResInfo.icon.bWidth,
1465 pDirEntry->ResInfo.icon.bHeight, iDesiredCX, iDesiredCY);
1467 /* Get the Best Fit
1469 if (!(hRsrc = FindResourceW(pIconCache->hModule ,
1470 MAKEINTRESOURCEW(wResId), (LPWSTR)(bIsIcon ? RT_ICON : RT_CURSOR))))
1472 return 0;
1474 if (!(hMem = LoadResource( pIconCache->hModule , hRsrc )))
1476 return 0;
1479 pBits = LockResource( hMem );
1481 if(nFlags & LR_DEFAULTSIZE)
1483 iTargetCY = GetSystemMetrics(SM_CYICON);
1484 iTargetCX = GetSystemMetrics(SM_CXICON);
1487 /* Create a New Icon with the proper dimension
1489 hNew = CreateIconFromResourceEx( pBits, dwBytesInRes,
1490 bIsIcon, 0x00030000, iTargetCX, iTargetCY, nFlags);
1491 FreeResource(hMem);
1494 else hNew = CopyIcon( hIcon );
1495 return hNew;
1499 /***********************************************************************
1500 * CreateCursor (USER32.@)
1502 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
1503 INT xHotSpot, INT yHotSpot,
1504 INT nWidth, INT nHeight,
1505 LPCVOID lpANDbits, LPCVOID lpXORbits )
1507 ICONINFO info;
1508 HCURSOR hCursor;
1510 TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
1511 nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1513 info.fIcon = FALSE;
1514 info.xHotspot = xHotSpot;
1515 info.yHotspot = yHotSpot;
1516 info.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1517 info.hbmColor = CreateBitmap( nWidth, nHeight, 1, 1, lpXORbits );
1518 hCursor = CreateIconIndirect( &info );
1519 DeleteObject( info.hbmMask );
1520 DeleteObject( info.hbmColor );
1521 return hCursor;
1525 /***********************************************************************
1526 * CreateIcon (USER32.@)
1528 * Creates an icon based on the specified bitmaps. The bitmaps must be
1529 * provided in a device dependent format and will be resized to
1530 * (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1531 * depth. The provided bitmaps must be top-down bitmaps.
1532 * Although Windows does not support 15bpp(*) this API must support it
1533 * for Winelib applications.
1535 * (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1536 * format!
1538 * RETURNS
1539 * Success: handle to an icon
1540 * Failure: NULL
1542 * FIXME: Do we need to resize the bitmaps?
1544 HICON WINAPI CreateIcon(
1545 HINSTANCE hInstance, /* [in] the application's hInstance */
1546 INT nWidth, /* [in] the width of the provided bitmaps */
1547 INT nHeight, /* [in] the height of the provided bitmaps */
1548 BYTE bPlanes, /* [in] the number of planes in the provided bitmaps */
1549 BYTE bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1550 LPCVOID lpANDbits, /* [in] a monochrome bitmap representing the icon's mask */
1551 LPCVOID lpXORbits) /* [in] the icon's 'color' bitmap */
1553 ICONINFO iinfo;
1554 HICON hIcon;
1556 TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
1557 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1559 iinfo.fIcon = TRUE;
1560 iinfo.xHotspot = nWidth / 2;
1561 iinfo.yHotspot = nHeight / 2;
1562 iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1563 iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );
1565 hIcon = CreateIconIndirect( &iinfo );
1567 DeleteObject( iinfo.hbmMask );
1568 DeleteObject( iinfo.hbmColor );
1570 return hIcon;
1574 /***********************************************************************
1575 * CopyIcon (USER32.@)
1577 HICON WINAPI CopyIcon( HICON hIcon )
1579 struct cursoricon_object *ptrOld, *ptrNew;
1580 HICON hNew;
1582 if (!(ptrOld = get_icon_ptr( hIcon ))) return 0;
1583 if ((hNew = alloc_icon_handle(1)))
1585 ptrNew = get_icon_ptr( hNew );
1586 ptrNew->is_icon = ptrOld->is_icon;
1587 ptrNew->width = ptrOld->width;
1588 ptrNew->height = ptrOld->height;
1589 ptrNew->hotspot = ptrOld->hotspot;
1590 ptrNew->frames[0].mask = copy_bitmap( ptrOld->frames[0].mask );
1591 ptrNew->frames[0].color = copy_bitmap( ptrOld->frames[0].color );
1592 ptrNew->frames[0].alpha = copy_bitmap( ptrOld->frames[0].alpha );
1593 release_icon_ptr( hNew, ptrNew );
1595 release_icon_ptr( hIcon, ptrOld );
1596 if (hNew) USER_Driver->pCreateCursorIcon( hNew );
1597 return hNew;
1601 /***********************************************************************
1602 * DestroyIcon (USER32.@)
1604 BOOL WINAPI DestroyIcon( HICON hIcon )
1606 TRACE_(icon)("%p\n", hIcon );
1608 if (CURSORICON_DelSharedIcon( hIcon ) == -1)
1609 free_icon_handle( hIcon );
1610 return TRUE;
1614 /***********************************************************************
1615 * DestroyCursor (USER32.@)
1617 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
1619 if (GetCursor() == hCursor)
1621 WARN_(cursor)("Destroying active cursor!\n" );
1622 return FALSE;
1624 return DestroyIcon( hCursor );
1627 /***********************************************************************
1628 * DrawIcon (USER32.@)
1630 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
1632 return DrawIconEx( hdc, x, y, hIcon, 0, 0, 0, 0, DI_NORMAL | DI_COMPAT | DI_DEFAULTSIZE );
1635 /***********************************************************************
1636 * SetCursor (USER32.@)
1638 * Set the cursor shape.
1640 * RETURNS
1641 * A handle to the previous cursor shape.
1643 HCURSOR WINAPI DECLSPEC_HOTPATCH SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1645 HCURSOR hOldCursor;
1646 int show_count;
1647 BOOL ret;
1649 TRACE("%p\n", hCursor);
1651 SERVER_START_REQ( set_cursor )
1653 req->flags = SET_CURSOR_HANDLE;
1654 req->handle = wine_server_user_handle( hCursor );
1655 if ((ret = !wine_server_call_err( req )))
1657 hOldCursor = wine_server_ptr_handle( reply->prev_handle );
1658 show_count = reply->prev_count;
1661 SERVER_END_REQ;
1663 if (!ret) return 0;
1665 /* Change the cursor shape only if it is visible */
1666 if (show_count >= 0 && hOldCursor != hCursor) USER_Driver->pSetCursor( hCursor );
1667 return hOldCursor;
1670 /***********************************************************************
1671 * ShowCursor (USER32.@)
1673 INT WINAPI DECLSPEC_HOTPATCH ShowCursor( BOOL bShow )
1675 HCURSOR cursor;
1676 int increment = bShow ? 1 : -1;
1677 int count;
1679 SERVER_START_REQ( set_cursor )
1681 req->flags = SET_CURSOR_COUNT;
1682 req->show_count = increment;
1683 wine_server_call( req );
1684 cursor = wine_server_ptr_handle( reply->prev_handle );
1685 count = reply->prev_count + increment;
1687 SERVER_END_REQ;
1689 TRACE("%d, count=%d\n", bShow, count );
1691 if (bShow && !count) USER_Driver->pSetCursor( cursor );
1692 else if (!bShow && count == -1) USER_Driver->pSetCursor( 0 );
1694 return count;
1697 /***********************************************************************
1698 * GetCursor (USER32.@)
1700 HCURSOR WINAPI GetCursor(void)
1702 HCURSOR ret;
1704 SERVER_START_REQ( set_cursor )
1706 req->flags = 0;
1707 wine_server_call( req );
1708 ret = wine_server_ptr_handle( reply->prev_handle );
1710 SERVER_END_REQ;
1711 return ret;
1715 /***********************************************************************
1716 * ClipCursor (USER32.@)
1718 BOOL WINAPI DECLSPEC_HOTPATCH ClipCursor( const RECT *rect )
1720 RECT virt;
1722 SetRect( &virt, 0, 0, GetSystemMetrics( SM_CXVIRTUALSCREEN ),
1723 GetSystemMetrics( SM_CYVIRTUALSCREEN ) );
1724 OffsetRect( &virt, GetSystemMetrics( SM_XVIRTUALSCREEN ),
1725 GetSystemMetrics( SM_YVIRTUALSCREEN ) );
1727 TRACE( "Clipping to: %s was: %s screen: %s\n", wine_dbgstr_rect(rect),
1728 wine_dbgstr_rect(&CURSOR_ClipRect), wine_dbgstr_rect(&virt) );
1730 if (!IntersectRect( &CURSOR_ClipRect, &virt, rect ))
1731 CURSOR_ClipRect = virt;
1733 USER_Driver->pClipCursor( rect );
1734 return TRUE;
1738 /***********************************************************************
1739 * GetClipCursor (USER32.@)
1741 BOOL WINAPI DECLSPEC_HOTPATCH GetClipCursor( RECT *rect )
1743 /* If this is first time - initialize the rect */
1744 if (IsRectEmpty( &CURSOR_ClipRect )) ClipCursor( NULL );
1746 return CopyRect( rect, &CURSOR_ClipRect );
1750 /***********************************************************************
1751 * SetSystemCursor (USER32.@)
1753 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
1755 FIXME("(%p,%08x),stub!\n", hcur, id);
1756 return TRUE;
1760 /**********************************************************************
1761 * LookupIconIdFromDirectoryEx (USER32.@)
1763 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
1764 INT width, INT height, UINT cFlag )
1766 CURSORICONDIR *dir = (CURSORICONDIR*)xdir;
1767 UINT retVal = 0;
1768 if( dir && !dir->idReserved && (dir->idType & 3) )
1770 CURSORICONDIRENTRY* entry;
1772 const HDC hdc = GetDC(0);
1773 const int depth = (cFlag & LR_MONOCHROME) ?
1774 1 : GetDeviceCaps(hdc, BITSPIXEL);
1775 ReleaseDC(0, hdc);
1777 if( bIcon )
1778 entry = CURSORICON_FindBestIconRes( dir, width, height, depth );
1779 else
1780 entry = CURSORICON_FindBestCursorRes( dir, width, height, depth );
1782 if( entry ) retVal = entry->wResId;
1784 else WARN_(cursor)("invalid resource directory\n");
1785 return retVal;
1788 /**********************************************************************
1789 * LookupIconIdFromDirectory (USER32.@)
1791 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
1793 return LookupIconIdFromDirectoryEx( dir, bIcon,
1794 bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
1795 bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
1798 /***********************************************************************
1799 * LoadCursorW (USER32.@)
1801 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
1803 TRACE("%p, %s\n", hInstance, debugstr_w(name));
1805 return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1806 LR_SHARED | LR_DEFAULTSIZE );
1809 /***********************************************************************
1810 * LoadCursorA (USER32.@)
1812 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
1814 TRACE("%p, %s\n", hInstance, debugstr_a(name));
1816 return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1817 LR_SHARED | LR_DEFAULTSIZE );
1820 /***********************************************************************
1821 * LoadCursorFromFileW (USER32.@)
1823 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1825 TRACE("%s\n", debugstr_w(name));
1827 return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1828 LR_LOADFROMFILE | LR_DEFAULTSIZE );
1831 /***********************************************************************
1832 * LoadCursorFromFileA (USER32.@)
1834 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1836 TRACE("%s\n", debugstr_a(name));
1838 return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1839 LR_LOADFROMFILE | LR_DEFAULTSIZE );
1842 /***********************************************************************
1843 * LoadIconW (USER32.@)
1845 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
1847 TRACE("%p, %s\n", hInstance, debugstr_w(name));
1849 return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1850 LR_SHARED | LR_DEFAULTSIZE );
1853 /***********************************************************************
1854 * LoadIconA (USER32.@)
1856 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
1858 TRACE("%p, %s\n", hInstance, debugstr_a(name));
1860 return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1861 LR_SHARED | LR_DEFAULTSIZE );
1864 /**********************************************************************
1865 * GetIconInfo (USER32.@)
1867 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
1869 struct cursoricon_object *ptr;
1871 if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
1873 TRACE("%p => %dx%d\n", hIcon, ptr->width, ptr->height);
1875 iconinfo->fIcon = ptr->is_icon;
1876 iconinfo->xHotspot = ptr->hotspot.x;
1877 iconinfo->yHotspot = ptr->hotspot.y;
1878 iconinfo->hbmColor = copy_bitmap( ptr->frames[0].color );
1879 iconinfo->hbmMask = copy_bitmap( ptr->frames[0].mask );
1880 release_icon_ptr( hIcon, ptr );
1882 return TRUE;
1885 /* copy an icon bitmap, even when it can't be selected into a DC */
1886 /* helper for CreateIconIndirect */
1887 static void stretch_blt_icon( HDC hdc_dst, int dst_x, int dst_y, int dst_width, int dst_height,
1888 HBITMAP src, int width, int height )
1890 HDC hdc = CreateCompatibleDC( 0 );
1892 if (!SelectObject( hdc, src )) /* do it the hard way */
1894 BITMAPINFO *info;
1895 void *bits;
1897 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) return;
1898 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1899 info->bmiHeader.biWidth = width;
1900 info->bmiHeader.biHeight = height;
1901 info->bmiHeader.biPlanes = GetDeviceCaps( hdc_dst, PLANES );
1902 info->bmiHeader.biBitCount = GetDeviceCaps( hdc_dst, BITSPIXEL );
1903 info->bmiHeader.biCompression = BI_RGB;
1904 info->bmiHeader.biSizeImage = height * get_dib_width_bytes( width, info->bmiHeader.biBitCount );
1905 info->bmiHeader.biXPelsPerMeter = 0;
1906 info->bmiHeader.biYPelsPerMeter = 0;
1907 info->bmiHeader.biClrUsed = 0;
1908 info->bmiHeader.biClrImportant = 0;
1909 bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage );
1910 if (bits && GetDIBits( hdc, src, 0, height, bits, info, DIB_RGB_COLORS ))
1911 StretchDIBits( hdc_dst, dst_x, dst_y, dst_width, dst_height,
1912 0, 0, width, height, bits, info, DIB_RGB_COLORS, SRCCOPY );
1914 HeapFree( GetProcessHeap(), 0, bits );
1915 HeapFree( GetProcessHeap(), 0, info );
1917 else StretchBlt( hdc_dst, dst_x, dst_y, dst_width, dst_height, hdc, 0, 0, width, height, SRCCOPY );
1919 DeleteDC( hdc );
1922 /**********************************************************************
1923 * CreateIconIndirect (USER32.@)
1925 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
1927 BITMAP bmpXor, bmpAnd;
1928 HICON hObj;
1929 HBITMAP color = 0, mask;
1930 int width, height;
1931 HDC hdc;
1933 TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
1934 iconinfo->hbmColor, iconinfo->hbmMask,
1935 iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
1937 if (!iconinfo->hbmMask) return 0;
1939 GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
1940 TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
1941 bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
1942 bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
1944 if (iconinfo->hbmColor)
1946 GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
1947 TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
1948 bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
1949 bmpXor.bmPlanes, bmpXor.bmBitsPixel);
1951 width = bmpXor.bmWidth;
1952 height = bmpXor.bmHeight;
1953 if (bmpXor.bmPlanes * bmpXor.bmBitsPixel != 1)
1955 color = CreateCompatibleBitmap( screen_dc, width, height );
1956 mask = CreateBitmap( width, height, 1, 1, NULL );
1958 else mask = CreateBitmap( width, height * 2, 1, 1, NULL );
1960 else
1962 width = bmpAnd.bmWidth;
1963 height = bmpAnd.bmHeight;
1964 mask = CreateBitmap( width, height, 1, 1, NULL );
1967 hdc = CreateCompatibleDC( 0 );
1968 SelectObject( hdc, mask );
1969 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmMask, bmpAnd.bmWidth, bmpAnd.bmHeight );
1971 if (color)
1973 SelectObject( hdc, color );
1974 stretch_blt_icon( hdc, 0, 0, width, height, iconinfo->hbmColor, width, height );
1976 else if (iconinfo->hbmColor)
1978 stretch_blt_icon( hdc, 0, height, width, height, iconinfo->hbmColor, width, height );
1980 else height /= 2;
1982 DeleteDC( hdc );
1984 hObj = alloc_icon_handle(1);
1985 if (hObj)
1987 struct cursoricon_object *info = get_icon_ptr( hObj );
1989 info->is_icon = iconinfo->fIcon;
1990 info->width = width;
1991 info->height = height;
1992 info->frames[0].color = color;
1993 info->frames[0].mask = mask;
1994 info->frames[0].alpha = create_alpha_bitmap( iconinfo->hbmColor, mask, NULL, NULL );
1995 if (info->is_icon)
1997 info->hotspot.x = width / 2;
1998 info->hotspot.y = height / 2;
2000 else
2002 info->hotspot.x = iconinfo->xHotspot;
2003 info->hotspot.y = iconinfo->yHotspot;
2006 release_icon_ptr( hObj, info );
2007 USER_Driver->pCreateCursorIcon( hObj );
2009 return hObj;
2012 /******************************************************************************
2013 * DrawIconEx (USER32.@) Draws an icon or cursor on device context
2015 * NOTES
2016 * Why is this using SM_CXICON instead of SM_CXCURSOR?
2018 * PARAMS
2019 * hdc [I] Handle to device context
2020 * x0 [I] X coordinate of upper left corner
2021 * y0 [I] Y coordinate of upper left corner
2022 * hIcon [I] Handle to icon to draw
2023 * cxWidth [I] Width of icon
2024 * cyWidth [I] Height of icon
2025 * istep [I] Index of frame in animated cursor
2026 * hbr [I] Handle to background brush
2027 * flags [I] Icon-drawing flags
2029 * RETURNS
2030 * Success: TRUE
2031 * Failure: FALSE
2033 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2034 INT cxWidth, INT cyWidth, UINT istep,
2035 HBRUSH hbr, UINT flags )
2037 struct cursoricon_object *ptr;
2038 HDC hdc_dest, hMemDC;
2039 BOOL result = FALSE, DoOffscreen;
2040 HBITMAP hB_off = 0;
2041 COLORREF oldFg, oldBg;
2042 INT x, y, nStretchMode;
2044 TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2045 hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2047 if (!(ptr = get_icon_ptr( hIcon ))) return FALSE;
2048 if (!(hMemDC = CreateCompatibleDC( hdc )))
2050 release_icon_ptr( hIcon, ptr );
2051 return FALSE;
2054 if (istep >= ptr->num_frames)
2056 TRACE_(icon)("Stepped past end of animated frames=%d\n", istep);
2057 release_icon_ptr( hIcon, ptr );
2058 return FALSE;
2060 if (flags & DI_NOMIRROR)
2061 FIXME_(icon)("Ignoring flag DI_NOMIRROR\n");
2063 /* Calculate the size of the destination image. */
2064 if (cxWidth == 0)
2066 if (flags & DI_DEFAULTSIZE)
2067 cxWidth = GetSystemMetrics (SM_CXICON);
2068 else
2069 cxWidth = ptr->width;
2071 if (cyWidth == 0)
2073 if (flags & DI_DEFAULTSIZE)
2074 cyWidth = GetSystemMetrics (SM_CYICON);
2075 else
2076 cyWidth = ptr->height;
2079 DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2081 if (DoOffscreen) {
2082 RECT r;
2084 r.left = 0;
2085 r.top = 0;
2086 r.right = cxWidth;
2087 r.bottom = cxWidth;
2089 if (!(hdc_dest = CreateCompatibleDC(hdc))) goto failed;
2090 if (!(hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth)))
2092 DeleteDC( hdc_dest );
2093 goto failed;
2095 SelectObject(hdc_dest, hB_off);
2096 FillRect(hdc_dest, &r, hbr);
2097 x = y = 0;
2099 else
2101 hdc_dest = hdc;
2102 x = x0;
2103 y = y0;
2106 nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2108 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2109 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2111 if (ptr->frames[istep].alpha && (flags & DI_IMAGE))
2113 BOOL is_mono = FALSE;
2115 if (GetObjectType( hdc_dest ) == OBJ_MEMDC)
2117 BITMAP bm;
2118 HBITMAP bmp = GetCurrentObject( hdc_dest, OBJ_BITMAP );
2119 is_mono = GetObjectW( bmp, sizeof(bm), &bm ) && bm.bmBitsPixel == 1;
2121 if (!is_mono)
2123 BLENDFUNCTION pixelblend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
2124 SelectObject( hMemDC, ptr->frames[istep].alpha );
2125 if (GdiAlphaBlend( hdc_dest, x, y, cxWidth, cyWidth, hMemDC,
2126 0, 0, ptr->width, ptr->height, pixelblend )) goto done;
2130 if (flags & DI_MASK)
2132 SelectObject( hMemDC, ptr->frames[istep].mask );
2133 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2134 hMemDC, 0, 0, ptr->width, ptr->height, SRCAND );
2137 if (flags & DI_IMAGE)
2139 if (ptr->frames[istep].color)
2141 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2142 SelectObject( hMemDC, ptr->frames[istep].color );
2143 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2144 hMemDC, 0, 0, ptr->width, ptr->height, rop );
2146 else
2148 DWORD rop = (flags & DI_MASK) ? SRCINVERT : SRCCOPY;
2149 SelectObject( hMemDC, ptr->frames[istep].mask );
2150 StretchBlt( hdc_dest, x, y, cxWidth, cyWidth,
2151 hMemDC, 0, ptr->height, ptr->width, ptr->height, rop );
2155 done:
2156 if (DoOffscreen) BitBlt( hdc, x0, y0, cxWidth, cyWidth, hdc_dest, 0, 0, SRCCOPY );
2158 SetTextColor( hdc, oldFg );
2159 SetBkColor( hdc, oldBg );
2160 SetStretchBltMode (hdc, nStretchMode);
2161 result = TRUE;
2162 if (hdc_dest != hdc) DeleteDC( hdc_dest );
2163 if (hB_off) DeleteObject(hB_off);
2164 failed:
2165 DeleteDC( hMemDC );
2166 release_icon_ptr( hIcon, ptr );
2167 return result;
2170 /***********************************************************************
2171 * DIB_FixColorsToLoadflags
2173 * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2174 * are in loadflags
2176 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2178 int colors;
2179 COLORREF c_W, c_S, c_F, c_L, c_C;
2180 int incr,i;
2181 RGBQUAD *ptr;
2182 int bitmap_type;
2183 LONG width;
2184 LONG height;
2185 WORD bpp;
2186 DWORD compr;
2188 if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2190 WARN_(resource)("Invalid bitmap\n");
2191 return;
2194 if (bpp > 8) return;
2196 if (bitmap_type == 0) /* BITMAPCOREHEADER */
2198 incr = 3;
2199 colors = 1 << bpp;
2201 else
2203 incr = 4;
2204 colors = bmi->bmiHeader.biClrUsed;
2205 if (colors > 256) colors = 256;
2206 if (!colors && (bpp <= 8)) colors = 1 << bpp;
2209 c_W = GetSysColor(COLOR_WINDOW);
2210 c_S = GetSysColor(COLOR_3DSHADOW);
2211 c_F = GetSysColor(COLOR_3DFACE);
2212 c_L = GetSysColor(COLOR_3DLIGHT);
2214 if (loadflags & LR_LOADTRANSPARENT) {
2215 switch (bpp) {
2216 case 1: pix = pix >> 7; break;
2217 case 4: pix = pix >> 4; break;
2218 case 8: break;
2219 default:
2220 WARN_(resource)("(%d): Unsupported depth\n", bpp);
2221 return;
2223 if (pix >= colors) {
2224 WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2225 return;
2227 if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2228 ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2229 ptr->rgbBlue = GetBValue(c_W);
2230 ptr->rgbGreen = GetGValue(c_W);
2231 ptr->rgbRed = GetRValue(c_W);
2233 if (loadflags & LR_LOADMAP3DCOLORS)
2234 for (i=0; i<colors; i++) {
2235 ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2236 c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2237 if (c_C == RGB(128, 128, 128)) {
2238 ptr->rgbRed = GetRValue(c_S);
2239 ptr->rgbGreen = GetGValue(c_S);
2240 ptr->rgbBlue = GetBValue(c_S);
2241 } else if (c_C == RGB(192, 192, 192)) {
2242 ptr->rgbRed = GetRValue(c_F);
2243 ptr->rgbGreen = GetGValue(c_F);
2244 ptr->rgbBlue = GetBValue(c_F);
2245 } else if (c_C == RGB(223, 223, 223)) {
2246 ptr->rgbRed = GetRValue(c_L);
2247 ptr->rgbGreen = GetGValue(c_L);
2248 ptr->rgbBlue = GetBValue(c_L);
2254 /**********************************************************************
2255 * BITMAP_Load
2257 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2258 INT desiredx, INT desiredy, UINT loadflags )
2260 HBITMAP hbitmap = 0, orig_bm;
2261 HRSRC hRsrc;
2262 HGLOBAL handle;
2263 char *ptr = NULL;
2264 BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2265 int size;
2266 BYTE pix;
2267 char *bits;
2268 LONG width, height, new_width, new_height;
2269 WORD bpp_dummy;
2270 DWORD compr_dummy, offbits = 0;
2271 INT bm_type;
2272 HDC screen_mem_dc = NULL;
2274 if (!(loadflags & LR_LOADFROMFILE))
2276 if (!instance)
2278 /* OEM bitmap: try to load the resource from user32.dll */
2279 instance = user32_module;
2282 if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2283 if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2285 if ((info = LockResource( handle )) == NULL) return 0;
2287 else
2289 BITMAPFILEHEADER * bmfh;
2291 if (!(ptr = map_fileW( name, NULL ))) return 0;
2292 info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2293 bmfh = (BITMAPFILEHEADER *)ptr;
2294 if (bmfh->bfType != 0x4d42 /* 'BM' */)
2296 WARN("Invalid/unsupported bitmap format!\n");
2297 goto end;
2299 if (bmfh->bfOffBits) offbits = bmfh->bfOffBits - sizeof(BITMAPFILEHEADER);
2302 size = bitmap_info_size(info, DIB_RGB_COLORS);
2303 fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2304 scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2306 if (!fix_info || !scaled_info) goto end;
2307 memcpy(fix_info, info, size);
2309 pix = *((LPBYTE)info + size);
2310 DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2312 memcpy(scaled_info, fix_info, size);
2313 bm_type = DIB_GetBitmapInfo( &fix_info->bmiHeader, &width, &height,
2314 &bpp_dummy, &compr_dummy);
2315 if (bm_type == -1)
2317 WARN("Invalid bitmap format!\n");
2318 goto end;
2321 if(desiredx != 0)
2322 new_width = desiredx;
2323 else
2324 new_width = width;
2326 if(desiredy != 0)
2327 new_height = height > 0 ? desiredy : -desiredy;
2328 else
2329 new_height = height;
2331 if(bm_type == 0)
2333 BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2334 core->bcWidth = new_width;
2335 core->bcHeight = new_height;
2337 else
2339 /* Some sanity checks for BITMAPINFO (not applicable to BITMAPCOREINFO) */
2340 if (info->bmiHeader.biHeight > 65535 || info->bmiHeader.biWidth > 65535) {
2341 WARN("Broken BitmapInfoHeader!\n");
2342 goto end;
2345 scaled_info->bmiHeader.biWidth = new_width;
2346 scaled_info->bmiHeader.biHeight = new_height;
2349 if (new_height < 0) new_height = -new_height;
2351 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2352 if (!(screen_mem_dc = CreateCompatibleDC( screen_dc ))) goto end;
2354 bits = (char *)info + (offbits ? offbits : size);
2356 if (loadflags & LR_CREATEDIBSECTION)
2358 scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2359 hbitmap = CreateDIBSection(screen_dc, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2361 else
2363 if (is_dib_monochrome(fix_info))
2364 hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2365 else
2366 hbitmap = CreateCompatibleBitmap(screen_dc, new_width, new_height);
2369 orig_bm = SelectObject(screen_mem_dc, hbitmap);
2370 StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2371 SelectObject(screen_mem_dc, orig_bm);
2373 end:
2374 if (screen_mem_dc) DeleteDC(screen_mem_dc);
2375 HeapFree(GetProcessHeap(), 0, scaled_info);
2376 HeapFree(GetProcessHeap(), 0, fix_info);
2377 if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2379 return hbitmap;
2382 /**********************************************************************
2383 * LoadImageA (USER32.@)
2385 * See LoadImageW.
2387 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2388 INT desiredx, INT desiredy, UINT loadflags)
2390 HANDLE res;
2391 LPWSTR u_name;
2393 if (IS_INTRESOURCE(name))
2394 return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2396 __TRY {
2397 DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2398 u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2399 MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2401 __EXCEPT_PAGE_FAULT {
2402 SetLastError( ERROR_INVALID_PARAMETER );
2403 return 0;
2405 __ENDTRY
2406 res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2407 HeapFree(GetProcessHeap(), 0, u_name);
2408 return res;
2412 /******************************************************************************
2413 * LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2415 * PARAMS
2416 * hinst [I] Handle of instance that contains image
2417 * name [I] Name of image
2418 * type [I] Type of image
2419 * desiredx [I] Desired width
2420 * desiredy [I] Desired height
2421 * loadflags [I] Load flags
2423 * RETURNS
2424 * Success: Handle to newly loaded image
2425 * Failure: NULL
2427 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2429 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2430 INT desiredx, INT desiredy, UINT loadflags )
2432 TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
2433 hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
2435 if (loadflags & LR_DEFAULTSIZE) {
2436 if (type == IMAGE_ICON) {
2437 if (!desiredx) desiredx = GetSystemMetrics(SM_CXICON);
2438 if (!desiredy) desiredy = GetSystemMetrics(SM_CYICON);
2439 } else if (type == IMAGE_CURSOR) {
2440 if (!desiredx) desiredx = GetSystemMetrics(SM_CXCURSOR);
2441 if (!desiredy) desiredy = GetSystemMetrics(SM_CYCURSOR);
2444 if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
2445 switch (type) {
2446 case IMAGE_BITMAP:
2447 return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2449 case IMAGE_ICON:
2450 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2451 if (screen_dc)
2453 return CURSORICON_Load(hinst, name, desiredx, desiredy,
2454 GetDeviceCaps(screen_dc, BITSPIXEL),
2455 FALSE, loadflags);
2457 break;
2459 case IMAGE_CURSOR:
2460 return CURSORICON_Load(hinst, name, desiredx, desiredy,
2461 1, TRUE, loadflags);
2463 return 0;
2466 /******************************************************************************
2467 * CopyImage (USER32.@) Creates new image and copies attributes to it
2469 * PARAMS
2470 * hnd [I] Handle to image to copy
2471 * type [I] Type of image to copy
2472 * desiredx [I] Desired width of new image
2473 * desiredy [I] Desired height of new image
2474 * flags [I] Copy flags
2476 * RETURNS
2477 * Success: Handle to newly created image
2478 * Failure: NULL
2480 * BUGS
2481 * Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
2482 * all other versions (95/2000/XP have been tested) ignore it.
2484 * NOTES
2485 * If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
2486 * a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
2487 * the copy will have the same depth as the screen.
2488 * The content of the image will only be copied if the bit depth of the
2489 * original image is compatible with the bit depth of the screen, or
2490 * if the source is a DIB section.
2491 * The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
2493 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2494 INT desiredy, UINT flags )
2496 TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
2497 hnd, type, desiredx, desiredy, flags);
2499 switch (type)
2501 case IMAGE_BITMAP:
2503 HBITMAP res = NULL;
2504 DIBSECTION ds;
2505 int objSize;
2506 BITMAPINFO * bi;
2508 objSize = GetObjectW( hnd, sizeof(ds), &ds );
2509 if (!objSize) return 0;
2510 if ((desiredx < 0) || (desiredy < 0)) return 0;
2512 if (flags & LR_COPYFROMRESOURCE)
2514 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
2517 if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
2518 if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
2520 /* Allocate memory for a BITMAPINFOHEADER structure and a
2521 color table. The maximum number of colors in a color table
2522 is 256 which corresponds to a bitmap with depth 8.
2523 Bitmaps with higher depths don't have color tables. */
2524 bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
2525 if (!bi) return 0;
2527 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
2528 bi->bmiHeader.biPlanes = ds.dsBm.bmPlanes;
2529 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
2530 bi->bmiHeader.biCompression = BI_RGB;
2532 if (flags & LR_CREATEDIBSECTION)
2534 /* Create a DIB section. LR_MONOCHROME is ignored */
2535 void * bits;
2536 HDC dc = CreateCompatibleDC(NULL);
2538 if (objSize == sizeof(DIBSECTION))
2540 /* The source bitmap is a DIB.
2541 Get its attributes to create an exact copy */
2542 memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
2545 /* Get the color table or the color masks */
2546 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2548 bi->bmiHeader.biWidth = desiredx;
2549 bi->bmiHeader.biHeight = desiredy;
2550 bi->bmiHeader.biSizeImage = 0;
2552 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
2553 DeleteDC(dc);
2555 else
2557 /* Create a device-dependent bitmap */
2559 BOOL monochrome = (flags & LR_MONOCHROME);
2561 if (objSize == sizeof(DIBSECTION))
2563 /* The source bitmap is a DIB section.
2564 Get its attributes */
2565 HDC dc = CreateCompatibleDC(NULL);
2566 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
2567 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
2568 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2569 DeleteDC(dc);
2571 if (!monochrome && ds.dsBm.bmBitsPixel == 1)
2573 /* Look if the colors of the DIB are black and white */
2575 monochrome =
2576 (bi->bmiColors[0].rgbRed == 0xff
2577 && bi->bmiColors[0].rgbGreen == 0xff
2578 && bi->bmiColors[0].rgbBlue == 0xff
2579 && bi->bmiColors[0].rgbReserved == 0
2580 && bi->bmiColors[1].rgbRed == 0
2581 && bi->bmiColors[1].rgbGreen == 0
2582 && bi->bmiColors[1].rgbBlue == 0
2583 && bi->bmiColors[1].rgbReserved == 0)
2585 (bi->bmiColors[0].rgbRed == 0
2586 && bi->bmiColors[0].rgbGreen == 0
2587 && bi->bmiColors[0].rgbBlue == 0
2588 && bi->bmiColors[0].rgbReserved == 0
2589 && bi->bmiColors[1].rgbRed == 0xff
2590 && bi->bmiColors[1].rgbGreen == 0xff
2591 && bi->bmiColors[1].rgbBlue == 0xff
2592 && bi->bmiColors[1].rgbReserved == 0);
2595 else if (!monochrome)
2597 monochrome = ds.dsBm.bmBitsPixel == 1;
2600 if (monochrome)
2602 res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
2604 else
2606 HDC screenDC = GetDC(NULL);
2607 res = CreateCompatibleBitmap(screenDC, desiredx, desiredy);
2608 ReleaseDC(NULL, screenDC);
2612 if (res)
2614 /* Only copy the bitmap if it's a DIB section or if it's
2615 compatible to the screen */
2616 BOOL copyContents;
2618 if (objSize == sizeof(DIBSECTION))
2620 copyContents = TRUE;
2622 else
2624 HDC screenDC = GetDC(NULL);
2625 int screen_depth = GetDeviceCaps(screenDC, BITSPIXEL);
2626 ReleaseDC(NULL, screenDC);
2628 copyContents = (ds.dsBm.bmBitsPixel == 1 || ds.dsBm.bmBitsPixel == screen_depth);
2631 if (copyContents)
2633 /* The source bitmap may already be selected in a device context,
2634 use GetDIBits/StretchDIBits and not StretchBlt */
2636 HDC dc;
2637 void * bits;
2639 dc = CreateCompatibleDC(NULL);
2641 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
2642 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
2643 bi->bmiHeader.biSizeImage = 0;
2644 bi->bmiHeader.biClrUsed = 0;
2645 bi->bmiHeader.biClrImportant = 0;
2647 /* Fill in biSizeImage */
2648 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
2649 bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
2651 if (bits)
2653 HBITMAP oldBmp;
2655 /* Get the image bits of the source bitmap */
2656 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
2658 /* Copy it to the destination bitmap */
2659 oldBmp = SelectObject(dc, res);
2660 StretchDIBits(dc, 0, 0, desiredx, desiredy,
2661 0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
2662 bits, bi, DIB_RGB_COLORS, SRCCOPY);
2663 SelectObject(dc, oldBmp);
2665 HeapFree(GetProcessHeap(), 0, bits);
2668 DeleteDC(dc);
2671 if (flags & LR_COPYDELETEORG)
2673 DeleteObject(hnd);
2676 HeapFree(GetProcessHeap(), 0, bi);
2677 return res;
2679 case IMAGE_ICON:
2680 return CURSORICON_ExtCopy(hnd,type, desiredx, desiredy, flags);
2681 case IMAGE_CURSOR:
2682 /* Should call CURSORICON_ExtCopy but more testing
2683 * needs to be done before we change this
2685 if (flags) FIXME("Flags are ignored\n");
2686 return CopyCursor(hnd);
2688 return 0;
2692 /******************************************************************************
2693 * LoadBitmapW (USER32.@) Loads bitmap from the executable file
2695 * RETURNS
2696 * Success: Handle to specified bitmap
2697 * Failure: NULL
2699 HBITMAP WINAPI LoadBitmapW(
2700 HINSTANCE instance, /* [in] Handle to application instance */
2701 LPCWSTR name) /* [in] Address of bitmap resource name */
2703 return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2706 /**********************************************************************
2707 * LoadBitmapA (USER32.@)
2709 * See LoadBitmapW.
2711 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
2713 return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );