push b59ba84f7e04af9ef068bd4c6e96701941f0256e
[wine/hacks.git] / dlls / user32 / cursoricon.c
blob6a8282fda285444cd1c2801031241a7c3d9b6505
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
26 * Theory:
28 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwui/html/msdn_icons.asp
30 * 32-bit cursors and icons are stored in the server.
32 * 16-bit cursors and icons are stored in a global heap block, with the
33 * following layout:
35 * CURSORICONINFO info;
36 * BYTE[] ANDbits;
37 * BYTE[] XORbits;
39 * The bits structures are in the format of a device-dependent bitmap.
41 * This layout is very sub-optimal, as the bitmap bits are stored in
42 * the X client instead of in the server like other bitmaps; however,
43 * some programs (notably Paint Brush) expect to be able to manipulate
44 * the bits directly :-(
47 #include "config.h"
48 #include "wine/port.h"
50 #include <stdarg.h>
51 #include <string.h>
52 #include <stdlib.h>
54 #include "ntstatus.h"
55 #define WIN32_NO_STATUS
56 #include "windef.h"
57 #include "winbase.h"
58 #include "wingdi.h"
59 #include "winerror.h"
60 #include "wine/winbase16.h"
61 #include "wine/winuser16.h"
62 #include "wine/exception.h"
63 #include "wine/debug.h"
64 #include "wine/list.h"
65 #include "wine/server.h"
66 #include "user_private.h"
68 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
69 WINE_DECLARE_DEBUG_CHANNEL(icon);
70 WINE_DECLARE_DEBUG_CHANNEL(resource);
72 #include "pshpack1.h"
74 typedef struct {
75 BYTE bWidth;
76 BYTE bHeight;
77 BYTE bColorCount;
78 BYTE bReserved;
79 WORD xHotspot;
80 WORD yHotspot;
81 DWORD dwDIBSize;
82 DWORD dwDIBOffset;
83 } CURSORICONFILEDIRENTRY;
85 typedef struct
87 WORD idReserved;
88 WORD idType;
89 WORD idCount;
90 CURSORICONFILEDIRENTRY idEntries[1];
91 } CURSORICONFILEDIR;
93 #include "poppack.h"
95 #define CID_RESOURCE 0x0001
96 #define CID_WIN32 0x0004
97 #define CID_NONSHARED 0x0008
99 static RECT CURSOR_ClipRect; /* Cursor clipping rect */
101 static HDC screen_dc;
103 static const WCHAR DISPLAYW[] = {'D','I','S','P','L','A','Y',0};
105 /**********************************************************************
106 * ICONCACHE for cursors/icons loaded with LR_SHARED.
108 * FIXME: This should not be allocated on the system heap, but on a
109 * subsystem-global heap (i.e. one for all Win16 processes,
110 * and one for each Win32 process).
112 typedef struct tagICONCACHE
114 struct tagICONCACHE *next;
116 HMODULE hModule;
117 HRSRC hRsrc;
118 HRSRC hGroupRsrc;
119 HICON hIcon;
121 INT count;
123 } ICONCACHE;
125 static ICONCACHE *IconAnchor = NULL;
127 static CRITICAL_SECTION IconCrst;
128 static CRITICAL_SECTION_DEBUG critsect_debug =
130 0, 0, &IconCrst,
131 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
132 0, 0, { (DWORD_PTR)(__FILE__ ": IconCrst") }
134 static CRITICAL_SECTION IconCrst = { &critsect_debug, -1, 0, 0, 0, 0 };
136 static const WORD ICON_HOTSPOT = 0x4242;
138 /* What is a good table size? */
139 #define CURSOR_HASH_SIZE 97
141 typedef struct {
142 HCURSOR16 cursor16;
143 HCURSOR cursor32;
144 struct list entry16;
145 struct list entry32;
146 } cursor_map_entry_t;
148 static int get_bitmap_width_bytes( int width, int bpp );
150 static struct list cursor16to32[CURSOR_HASH_SIZE];
151 static struct list cursor32to16[CURSOR_HASH_SIZE];
153 static inline int hash_cursor_handle( DWORD handle )
155 return handle % CURSOR_HASH_SIZE;
158 static void add_cursor16to32_entry( cursor_map_entry_t *entry )
160 int idx = hash_cursor_handle( entry->cursor16 );
162 if (!cursor16to32[idx].next) list_init( &cursor16to32[idx] );
164 list_add_head( &cursor16to32[idx], &entry->entry16 );
167 static void add_cursor32to16_entry( cursor_map_entry_t *entry )
169 int idx = hash_cursor_handle( (DWORD)entry->cursor32 );
171 if (!cursor32to16[idx].next) list_init( &cursor32to16[idx] );
173 list_add_head( &cursor32to16[idx], &entry->entry32 );
176 static cursor_map_entry_t *remove_cursor16to32_entry( HCURSOR16 cursor16 )
178 cursor_map_entry_t *entry = NULL;
179 int idx = hash_cursor_handle( cursor16 );
181 if (cursor16to32[idx].next)
183 LIST_FOR_EACH_ENTRY( entry, &cursor16to32[idx], cursor_map_entry_t, entry16 )
184 if (entry->cursor16 == cursor16)
186 list_remove( &entry->entry16 );
187 return entry;
191 return entry;
194 static cursor_map_entry_t *remove_cursor32to16_entry( HCURSOR cursor32 )
196 cursor_map_entry_t *entry = NULL;
197 int idx = hash_cursor_handle( (DWORD)cursor32 );
199 if (cursor32to16[idx].next)
201 LIST_FOR_EACH_ENTRY( entry, &cursor32to16[idx], cursor_map_entry_t, entry32 )
202 if (entry->cursor32 == cursor32)
204 list_remove( &entry->entry32 );
205 return entry;
209 return entry;
212 /* Ask the server for a cursor */
213 static HCURSOR create_cursor( unsigned int num_frames, unsigned int delay )
215 HCURSOR cursor = 0;
217 SERVER_START_REQ(create_cursor)
219 req->num_frames = num_frames;
220 req->delay = delay;
221 if (!wine_server_call_err( req )) cursor = reply->handle;
223 SERVER_END_REQ;
225 return cursor;
228 /* Tell the server to kill a cursor */
229 static HCURSOR16 destroy_cursor( HCURSOR cursor )
231 cursor_map_entry_t *entry;
232 HCURSOR16 cursor16 = 0;
234 if (!cursor) return 0;
236 SERVER_START_REQ(destroy_cursor)
238 req->handle = cursor;
239 wine_server_call( req );
241 SERVER_END_REQ;
243 entry = remove_cursor32to16_entry( cursor );
244 if (entry)
246 cursor16 = entry->cursor16;
247 remove_cursor16to32_entry( cursor16 );
248 HeapFree( GetProcessHeap(), 0, entry );
251 return GlobalFree16( cursor16 );
254 /* Upload a cursor frame to the server */
255 static void set_cursor_frame( HCURSOR cursor, unsigned int frame_idx, cursor_frame_t *frame )
257 SERVER_START_REQ(set_cursor_frame)
259 req->handle = cursor;
260 req->frame_idx = frame_idx;
261 req->xhot = frame->xhot;
262 req->yhot = frame->yhot;
263 req->width = frame->width;
264 req->height = frame->height;
265 req->and_width_bytes = frame->and_width_bytes;
266 req->xor_width_bytes = frame->xor_width_bytes;
267 req->planes = frame->planes;
268 req->bpp = frame->bpp;
269 wine_server_add_data( req, frame->bits, (frame->and_width_bytes + frame->xor_width_bytes) * frame->height );
270 wine_server_call( req );
272 SERVER_END_REQ;
275 /* Download a cursor frame from the server */
276 static BOOL get_cursor_frame( HCURSOR cursor, unsigned int frame_idx, cursor_frame_t *frame )
278 NTSTATUS res;
279 /* Enough for a 32-bits 32x32 cursor / icon. */
280 unsigned int buffer_size = 4224;
281 unsigned int count = 0;
285 frame->bits = HeapAlloc(GetProcessHeap(), 0, buffer_size);
286 SERVER_START_REQ(get_cursor_frame)
288 req->handle = cursor;
289 req->frame_idx = frame_idx;
290 wine_server_set_reply( req, frame->bits, buffer_size);
291 if (!(res = wine_server_call_err( req )))
293 frame->xhot = reply->xhot;
294 frame->yhot = reply->yhot;
295 frame->width = reply->width;
296 frame->height = reply->height;
297 frame->and_width_bytes = reply->and_width_bytes;
298 frame->xor_width_bytes = reply->xor_width_bytes;
299 frame->planes = reply->planes;
300 frame->bpp = reply->bpp;
301 } else {
302 HeapFree( GetProcessHeap(), 0, frame->bits );
303 buffer_size = (reply->and_width_bytes + reply->xor_width_bytes) * reply->height;
306 SERVER_END_REQ;
307 } while (res == STATUS_BUFFER_OVERFLOW && !count++);
309 if (!frame->height)
311 HeapFree( GetProcessHeap(), 0, frame->bits );
313 return FALSE;
316 return TRUE;
319 /* Retrieve a cursor and all its frames from the server */
320 static cursor_t *get_cursor_object( HCURSOR handle )
322 unsigned int i;
323 cursor_t *cursor = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(cursor_t) );
325 SERVER_START_REQ(get_cursor_info)
327 req->handle = handle;
328 if (!wine_server_call_err( req ))
330 cursor->num_frames = reply->num_frames;
331 cursor->delay = reply->delay;
334 SERVER_END_REQ;
336 if (!cursor->num_frames)
338 HeapFree( GetProcessHeap(), 0, cursor );
339 return NULL;
342 cursor->frames = HeapAlloc( GetProcessHeap(), 0, cursor->num_frames * sizeof(cursor_frame_t) );
343 for (i = 0; i < cursor->num_frames; ++i)
345 if (!get_cursor_frame( handle, i, &cursor->frames[i] ))
347 unsigned int j;
349 for (j = 0; j < i; ++j)
351 HeapFree( GetProcessHeap(), 0, cursor->frames[j].bits );
353 HeapFree( GetProcessHeap(), 0, cursor->frames );
354 HeapFree( GetProcessHeap(), 0, cursor );
356 return NULL;
360 return cursor;
363 static void destroy_cursor_object( cursor_t *cursor )
365 unsigned int i;
367 if (!cursor) return;
369 for (i = 0; i < cursor->num_frames; ++i)
371 HeapFree( GetProcessHeap(), 0, cursor->frames[i].bits );
373 HeapFree( GetProcessHeap(), 0, cursor->frames );
374 HeapFree( GetProcessHeap(), 0, cursor );
377 /* Lookup the cursor's 16-bit handle. Create one if it doesn't already exist. */
378 HCURSOR16 get_cursor_handle16( HCURSOR cursor32, BOOL create )
380 cursor_map_entry_t *entry;
381 int idx = hash_cursor_handle( (DWORD)cursor32 );
383 if (!cursor32) return 0;
385 if (cursor32to16[idx].next)
387 LIST_FOR_EACH_ENTRY( entry, &cursor32to16[idx], cursor_map_entry_t, entry32 )
388 if (entry->cursor32 == cursor32) return entry->cursor16;
391 /* 16-bit cursor handle not found, create one */
392 if (create)
394 size_t bits_size;
395 HCURSOR16 cursor16;
396 cursor_frame_t frame;
398 if (!get_cursor_frame( cursor32, 0, &frame )) return 0;
400 entry = HeapAlloc( GetProcessHeap(), 0, sizeof(cursor_map_entry_t) );
401 bits_size = (frame.and_width_bytes + frame.xor_width_bytes) * frame.height;
402 cursor16 = GlobalAlloc16( GMEM_MOVEABLE, sizeof(CURSORICONINFO) + bits_size );
403 if (cursor16)
405 CURSORICONINFO *info;
407 info = (CURSORICONINFO *)GlobalLock16( cursor16 );
408 info->ptHotSpot.x = frame.xhot;
409 info->ptHotSpot.y = frame.yhot;
410 info->nWidth = frame.width;
411 info->nHeight = frame.height;
412 info->nWidthBytes = frame.xor_width_bytes;
413 info->bPlanes = frame.planes;
414 info->bBitsPerPixel = frame.bpp;
415 CopyMemory( info + 1, frame.bits, bits_size );
416 GlobalUnlock16( cursor16 );
418 HeapFree( GetProcessHeap(), 0, frame.bits );
420 entry->cursor16 = cursor16;
421 entry->cursor32 = cursor32;
422 add_cursor16to32_entry( entry );
423 add_cursor32to16_entry( entry );
425 return cursor16;
428 return 0;
431 HCURSOR get_cursor_handle32( HCURSOR16 cursor16 )
433 cursor_map_entry_t *entry;
434 int idx = hash_cursor_handle( cursor16 );
436 if (!cursor16) return 0;
438 if (cursor16to32[idx].next)
440 LIST_FOR_EACH_ENTRY( entry, &cursor16to32[idx], cursor_map_entry_t, entry16 )
441 if (entry->cursor16 == cursor16) return entry->cursor32;
444 return 0;
447 static void update_cursor_32from16( HCURSOR cursor32 )
449 size_t bits_size;
450 HCURSOR16 cursor16;
451 cursor_frame_t frame;
452 CURSORICONINFO *info;
454 if (!cursor32) return;
456 cursor16 = get_cursor_handle16( cursor32, FALSE );
457 if (!cursor16) return;
459 info = (CURSORICONINFO *)GlobalLock16( cursor16 );
460 frame.xhot = info->ptHotSpot.x;
461 frame.yhot = info->ptHotSpot.y;
462 frame.width = info->nWidth;
463 frame.height = info->nHeight;
464 frame.and_width_bytes = get_bitmap_width_bytes( info->nWidth, 1 );
465 frame.xor_width_bytes = info->nWidthBytes;
466 frame.planes = info->bPlanes;
467 frame.bpp = info->bBitsPerPixel;
468 bits_size = (frame.and_width_bytes + frame.xor_width_bytes) * frame.height;
469 frame.bits = HeapAlloc( GetProcessHeap(), 0, bits_size );
470 CopyMemory( frame.bits, info + 1, bits_size );
471 GlobalUnlock16( cursor16 );
473 set_cursor_frame( cursor32, 0, &frame );
474 HeapFree( GetProcessHeap(), 0, frame.bits );
477 /***********************************************************************
478 * map_fileW
480 * Helper function to map a file to memory:
481 * name - file name
482 * [RETURN] ptr - pointer to mapped file
483 * [RETURN] filesize - pointer size of file to be stored if not NULL
485 static void *map_fileW( LPCWSTR name, LPDWORD filesize )
487 HANDLE hFile, hMapping;
488 LPVOID ptr = NULL;
490 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
491 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
492 if (hFile != INVALID_HANDLE_VALUE)
494 hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
495 if (hMapping)
497 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
498 CloseHandle( hMapping );
499 if (filesize)
500 *filesize = GetFileSize( hFile, NULL );
502 CloseHandle( hFile );
504 return ptr;
508 /***********************************************************************
509 * get_bitmap_width_bytes
511 * Return number of bytes taken by a scanline of 16-bit aligned Windows DDB
512 * data.
514 static int get_bitmap_width_bytes( int width, int bpp )
516 switch(bpp)
518 case 1:
519 return 2 * ((width+15) / 16);
520 case 4:
521 return 2 * ((width+3) / 4);
522 case 24:
523 width *= 3;
524 /* fall through */
525 case 8:
526 return width + (width & 1);
527 case 16:
528 case 15:
529 return width * 2;
530 case 32:
531 return width * 4;
532 default:
533 WARN("Unknown depth %d, please report.\n", bpp );
535 return -1;
539 /***********************************************************************
540 * get_dib_width_bytes
542 * Return the width of a DIB bitmap in bytes. DIB bitmap data is 32-bit aligned.
544 static int get_dib_width_bytes( int width, int depth )
546 int words;
548 switch(depth)
550 case 1: words = (width + 31) / 32; break;
551 case 4: words = (width + 7) / 8; break;
552 case 8: words = (width + 3) / 4; break;
553 case 15:
554 case 16: words = (width + 1) / 2; break;
555 case 24: words = (width * 3 + 3)/4; break;
556 default:
557 WARN("(%d): Unsupported depth\n", depth );
558 /* fall through */
559 case 32:
560 words = width;
562 return 4 * words;
566 /***********************************************************************
567 * bitmap_info_size
569 * Return the size of the bitmap info structure including color table.
571 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
573 int colors;
575 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
577 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
578 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
579 return sizeof(BITMAPCOREHEADER) + colors *
580 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
582 else /* assume BITMAPINFOHEADER */
584 colors = info->bmiHeader.biClrUsed;
585 if (colors > 256) /* buffer overflow otherwise */
586 colors = 256;
587 if (!colors && (info->bmiHeader.biBitCount <= 8))
588 colors = 1 << info->bmiHeader.biBitCount;
589 return sizeof(BITMAPINFOHEADER) + colors *
590 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
595 /***********************************************************************
596 * is_dib_monochrome
598 * Returns whether a DIB can be converted to a monochrome DDB.
600 * A DIB can be converted if its color table contains only black and
601 * white. Black must be the first color in the color table.
603 * Note : If the first color in the color table is white followed by
604 * black, we can't convert it to a monochrome DDB with
605 * SetDIBits, because black and white would be inverted.
607 static BOOL is_dib_monochrome( const BITMAPINFO* info )
609 if (info->bmiHeader.biBitCount != 1) return FALSE;
611 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
613 const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
615 /* Check if the first color is black */
616 if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
618 rgb++;
620 /* Check if the second color is white */
621 return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
622 && (rgb->rgbtBlue == 0xff));
624 else return FALSE;
626 else /* assume BITMAPINFOHEADER */
628 const RGBQUAD *rgb = info->bmiColors;
630 /* Check if the first color is black */
631 if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
632 (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
634 rgb++;
636 /* Check if the second color is white */
637 return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
638 && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
640 else return FALSE;
644 /***********************************************************************
645 * DIB_GetBitmapInfo
647 * Get the info from a bitmap header.
648 * Return 1 for INFOHEADER, 0 for COREHEADER,
649 * 4 for V4HEADER, 5 for V5HEADER, -1 for error.
651 static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
652 LONG *height, WORD *bpp, DWORD *compr )
654 if (header->biSize == sizeof(BITMAPINFOHEADER))
656 *width = header->biWidth;
657 *height = header->biHeight;
658 *bpp = header->biBitCount;
659 *compr = header->biCompression;
660 return 1;
662 if (header->biSize == sizeof(BITMAPCOREHEADER))
664 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
665 *width = core->bcWidth;
666 *height = core->bcHeight;
667 *bpp = core->bcBitCount;
668 *compr = 0;
669 return 0;
671 if (header->biSize == sizeof(BITMAPV4HEADER))
673 const BITMAPV4HEADER *v4hdr = (const BITMAPV4HEADER *)header;
674 *width = v4hdr->bV4Width;
675 *height = v4hdr->bV4Height;
676 *bpp = v4hdr->bV4BitCount;
677 *compr = v4hdr->bV4V4Compression;
678 return 4;
680 if (header->biSize == sizeof(BITMAPV5HEADER))
682 const BITMAPV5HEADER *v5hdr = (const BITMAPV5HEADER *)header;
683 *width = v5hdr->bV5Width;
684 *height = v5hdr->bV5Height;
685 *bpp = v5hdr->bV5BitCount;
686 *compr = v5hdr->bV5Compression;
687 return 5;
689 ERR("(%d): unknown/wrong size for header\n", header->biSize );
690 return -1;
693 /**********************************************************************
694 * CURSORICON_FindSharedIcon
696 static HICON CURSORICON_FindSharedIcon( HMODULE hModule, HRSRC hRsrc )
698 HICON hIcon = 0;
699 ICONCACHE *ptr;
701 EnterCriticalSection( &IconCrst );
703 for ( ptr = IconAnchor; ptr; ptr = ptr->next )
704 if ( ptr->hModule == hModule && ptr->hRsrc == hRsrc )
706 ptr->count++;
707 hIcon = ptr->hIcon;
708 break;
711 LeaveCriticalSection( &IconCrst );
713 return hIcon;
716 /*************************************************************************
717 * CURSORICON_FindCache
719 * Given a handle, find the corresponding cache element
721 * PARAMS
722 * Handle [I] handle to an Image
724 * RETURNS
725 * Success: The cache entry
726 * Failure: NULL
729 static ICONCACHE* CURSORICON_FindCache(HICON hIcon)
731 ICONCACHE *ptr;
732 ICONCACHE *pRet=NULL;
733 BOOL IsFound = FALSE;
734 int count;
736 EnterCriticalSection( &IconCrst );
738 for (count = 0, ptr = IconAnchor; ptr != NULL && !IsFound; ptr = ptr->next, count++ )
740 if ( hIcon == ptr->hIcon )
742 IsFound = TRUE;
743 pRet = ptr;
747 LeaveCriticalSection( &IconCrst );
749 return pRet;
752 /**********************************************************************
753 * CURSORICON_AddSharedIcon
755 static void CURSORICON_AddSharedIcon( HMODULE hModule, HRSRC hRsrc, HRSRC hGroupRsrc, HICON hIcon )
757 ICONCACHE *ptr = HeapAlloc( GetProcessHeap(), 0, sizeof(ICONCACHE) );
758 if ( !ptr ) return;
760 ptr->hModule = hModule;
761 ptr->hRsrc = hRsrc;
762 ptr->hIcon = hIcon;
763 ptr->hGroupRsrc = hGroupRsrc;
764 ptr->count = 1;
766 EnterCriticalSection( &IconCrst );
767 ptr->next = IconAnchor;
768 IconAnchor = ptr;
769 LeaveCriticalSection( &IconCrst );
772 /**********************************************************************
773 * CURSORICON_DelSharedIcon
775 static INT CURSORICON_DelSharedIcon( HICON hIcon )
777 INT count = -1;
778 ICONCACHE *ptr;
780 EnterCriticalSection( &IconCrst );
782 for ( ptr = IconAnchor; ptr; ptr = ptr->next )
783 if ( ptr->hIcon == hIcon )
785 if ( ptr->count > 0 ) ptr->count--;
786 count = ptr->count;
787 break;
790 LeaveCriticalSection( &IconCrst );
792 return count;
795 /**********************************************************************
796 * CURSORICON_FreeModuleIcons
798 void CURSORICON_FreeModuleIcons( HMODULE16 hMod16 )
800 ICONCACHE **ptr = &IconAnchor;
801 HMODULE hModule = HMODULE_32(GetExePtr( hMod16 ));
803 EnterCriticalSection( &IconCrst );
805 while ( *ptr )
807 if ( (*ptr)->hModule == hModule )
809 ICONCACHE *freePtr = *ptr;
810 *ptr = freePtr->next;
812 destroy_cursor( freePtr->hIcon );
813 HeapFree( GetProcessHeap(), 0, freePtr );
814 continue;
816 ptr = &(*ptr)->next;
819 LeaveCriticalSection( &IconCrst );
823 * The following macro functions account for the irregularities of
824 * accessing cursor and icon resources in files and resource entries.
826 typedef BOOL (*fnGetCIEntry)( LPVOID dir, int n,
827 int *width, int *height, int *bits );
829 /**********************************************************************
830 * CURSORICON_FindBestIcon
832 * Find the icon closest to the requested size and number of colors.
834 static int CURSORICON_FindBestIcon( LPVOID dir, fnGetCIEntry get_entry,
835 int width, int height, int colors )
837 int i, cx, cy, bits, bestEntry = -1;
838 UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
839 UINT iTempXDiff, iTempYDiff, iTempColorDiff;
841 /* Find Best Fit */
842 iTotalDiff = 0xFFFFFFFF;
843 iColorDiff = 0xFFFFFFFF;
844 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
846 iTempXDiff = abs(width - cx);
847 iTempYDiff = abs(height - cy);
849 if(iTotalDiff > (iTempXDiff + iTempYDiff))
851 iXDiff = iTempXDiff;
852 iYDiff = iTempYDiff;
853 iTotalDiff = iXDiff + iYDiff;
857 /* Find Best Colors for Best Fit */
858 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
860 if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
862 iTempColorDiff = abs(colors - (1<<bits));
863 if(iColorDiff > iTempColorDiff)
865 bestEntry = i;
866 iColorDiff = iTempColorDiff;
871 return bestEntry;
874 static BOOL CURSORICON_GetResIconEntry( LPVOID dir, int n,
875 int *width, int *height, int *bits )
877 CURSORICONDIR *resdir = dir;
878 ICONRESDIR *icon;
880 if ( resdir->idCount <= n )
881 return FALSE;
882 icon = &resdir->idEntries[n].ResInfo.icon;
883 *width = icon->bWidth;
884 *height = icon->bHeight;
885 *bits = resdir->idEntries[n].wBitCount;
886 return TRUE;
889 /**********************************************************************
890 * CURSORICON_FindBestCursor
892 * Find the cursor closest to the requested size.
893 * FIXME: parameter 'color' ignored and entries with more than 1 bpp
894 * ignored too
896 static int CURSORICON_FindBestCursor( LPVOID dir, fnGetCIEntry get_entry,
897 int width, int height, int color )
899 int i, maxwidth, maxheight, cx, cy, bits, bestEntry = -1;
901 /* Double height to account for AND and XOR masks */
903 height *= 2;
905 /* First find the largest one smaller than or equal to the requested size*/
907 maxwidth = maxheight = 0;
908 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
910 if ((cx <= width) && (cy <= height) &&
911 (cx > maxwidth) && (cy > maxheight) &&
912 (bits == 1))
914 bestEntry = i;
915 maxwidth = cx;
916 maxheight = cy;
919 if (bestEntry != -1) return bestEntry;
921 /* Now find the smallest one larger than the requested size */
923 maxwidth = maxheight = 255;
924 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
926 if (((cx < maxwidth) && (cy < maxheight) && (bits == 1)) ||
927 (bestEntry==-1))
929 bestEntry = i;
930 maxwidth = cx;
931 maxheight = cy;
935 return bestEntry;
938 static BOOL CURSORICON_GetResCursorEntry( LPVOID dir, int n,
939 int *width, int *height, int *bits )
941 CURSORICONDIR *resdir = dir;
942 CURSORDIR *cursor;
944 if ( resdir->idCount <= n )
945 return FALSE;
946 cursor = &resdir->idEntries[n].ResInfo.cursor;
947 *width = cursor->wWidth;
948 *height = cursor->wHeight;
949 *bits = resdir->idEntries[n].wBitCount;
950 return TRUE;
953 static CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( CURSORICONDIR * dir,
954 int width, int height, int colors )
956 int n;
958 n = CURSORICON_FindBestIcon( dir, CURSORICON_GetResIconEntry,
959 width, height, colors );
960 if ( n < 0 )
961 return NULL;
962 return &dir->idEntries[n];
965 static CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( CURSORICONDIR *dir,
966 int width, int height, int color )
968 int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetResCursorEntry,
969 width, height, color );
970 if ( n < 0 )
971 return NULL;
972 return &dir->idEntries[n];
975 static BOOL CURSORICON_GetFileEntry( LPVOID dir, int n,
976 int *width, int *height, int *bits )
978 CURSORICONFILEDIR *filedir = dir;
979 CURSORICONFILEDIRENTRY *entry;
981 if ( filedir->idCount <= n )
982 return FALSE;
983 entry = &filedir->idEntries[n];
984 *width = entry->bWidth;
985 *height = entry->bHeight;
986 *bits = entry->bColorCount;
987 return TRUE;
990 static CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( CURSORICONFILEDIR *dir,
991 int width, int height, int color )
993 int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetFileEntry,
994 width, height, color );
995 if ( n < 0 )
996 return NULL;
997 return &dir->idEntries[n];
1000 static CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( CURSORICONFILEDIR *dir,
1001 int width, int height, int color )
1003 int n = CURSORICON_FindBestIcon( dir, CURSORICON_GetFileEntry,
1004 width, height, color );
1005 if ( n < 0 )
1006 return NULL;
1007 return &dir->idEntries[n];
1010 static BOOL load_cursor_frame( LPBYTE bits, UINT cbSize, POINT16 hotspot, DWORD dwVersion,
1011 INT width, INT height, UINT cFlag, cursor_frame_t *frame )
1013 static HDC hdcMem;
1014 int sizeAnd, sizeXor;
1015 HBITMAP hAndBits = 0, hXorBits = 0; /* error condition for later */
1016 BITMAP bmpXor, bmpAnd;
1017 BITMAPINFO *bmi;
1018 BOOL DoStretch;
1019 INT size;
1021 TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s\n",
1022 bits, cbSize, dwVersion, width, height,
1023 (cFlag & LR_MONOCHROME) ? "mono" : "" );
1024 if (dwVersion == 0x00020000)
1026 FIXME_(cursor)("\t2.xx resources are not supported\n");
1027 return FALSE;
1030 bmi = (BITMAPINFO *)bits;
1032 /* Check bitmap header */
1034 if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
1035 (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER) ||
1036 bmi->bmiHeader.biCompression != BI_RGB) )
1038 WARN_(cursor)("\tinvalid resource bitmap header.\n");
1039 return FALSE;
1042 size = bitmap_info_size( bmi, DIB_RGB_COLORS );
1044 if (!width) width = bmi->bmiHeader.biWidth;
1045 if (!height) height = bmi->bmiHeader.biHeight/2;
1046 DoStretch = (bmi->bmiHeader.biHeight/2 != height) ||
1047 (bmi->bmiHeader.biWidth != width);
1049 /* Scale the hotspot */
1050 if (DoStretch && hotspot.x != ICON_HOTSPOT && hotspot.y != ICON_HOTSPOT)
1052 hotspot.x = (hotspot.x * width) / bmi->bmiHeader.biWidth;
1053 hotspot.y = (hotspot.y * height) / (bmi->bmiHeader.biWidth / 2);
1056 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
1057 if (screen_dc)
1059 BITMAPINFO* pInfo;
1061 /* Make sure we have room for the monochrome bitmap later on.
1062 * Note that BITMAPINFOINFO and BITMAPCOREHEADER are the same
1063 * up to and including the biBitCount. In-memory icon resource
1064 * format is as follows:
1066 * BITMAPINFOHEADER icHeader // DIB header
1067 * RGBQUAD icColors[] // Color table
1068 * BYTE icXOR[] // DIB bits for XOR mask
1069 * BYTE icAND[] // DIB bits for AND mask
1072 if ((pInfo = HeapAlloc( GetProcessHeap(), 0,
1073 max(size, sizeof(BITMAPINFOHEADER) + 2*sizeof(RGBQUAD)))))
1075 memcpy( pInfo, bmi, size );
1076 pInfo->bmiHeader.biHeight /= 2;
1078 /* Create the XOR bitmap */
1080 if (DoStretch) {
1081 hXorBits = CreateCompatibleBitmap(screen_dc, width, height);
1082 if(hXorBits)
1084 HBITMAP hOld;
1085 BOOL res = FALSE;
1087 if (!hdcMem) hdcMem = CreateCompatibleDC(screen_dc);
1088 if (hdcMem) {
1089 hOld = SelectObject(hdcMem, hXorBits);
1090 res = StretchDIBits(hdcMem, 0, 0, width, height, 0, 0,
1091 bmi->bmiHeader.biWidth, bmi->bmiHeader.biHeight/2,
1092 (char*)bmi + size, pInfo, DIB_RGB_COLORS, SRCCOPY);
1093 SelectObject(hdcMem, hOld);
1095 if (!res) { DeleteObject(hXorBits); hXorBits = 0; }
1097 } else {
1098 if (is_dib_monochrome(bmi)) {
1099 hXorBits = CreateBitmap(width, height, 1, 1, NULL);
1100 SetDIBits(screen_dc, hXorBits, 0, height,
1101 (char*)bmi + size, pInfo, DIB_RGB_COLORS);
1102 } else if (bmi->bmiHeader.biBitCount == 32) {
1103 hXorBits = CreateDIBSection(screen_dc, pInfo, DIB_RGB_COLORS, NULL, NULL, 0);
1104 SetDIBits(screen_dc, hXorBits, 0, height,
1105 (char*)bmi + size, pInfo, DIB_RGB_COLORS);
1107 else
1108 hXorBits = CreateDIBitmap(screen_dc, &pInfo->bmiHeader,
1109 CBM_INIT, (char*)bmi + size, pInfo, DIB_RGB_COLORS);
1112 if( hXorBits )
1114 char* xbits = (char *)bmi + size +
1115 get_dib_width_bytes( bmi->bmiHeader.biWidth,
1116 bmi->bmiHeader.biBitCount ) * abs( bmi->bmiHeader.biHeight ) / 2;
1118 pInfo->bmiHeader.biBitCount = 1;
1119 if (pInfo->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
1121 RGBQUAD *rgb = pInfo->bmiColors;
1123 pInfo->bmiHeader.biClrUsed = pInfo->bmiHeader.biClrImportant = 2;
1124 rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
1125 rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
1126 rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
1128 else
1130 RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)pInfo) + 1);
1132 rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
1133 rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
1136 /* Create the AND bitmap */
1138 if (DoStretch) {
1139 if ((hAndBits = CreateBitmap(width, height, 1, 1, NULL))) {
1140 HBITMAP hOld;
1141 BOOL res = FALSE;
1143 if (!hdcMem) hdcMem = CreateCompatibleDC(screen_dc);
1144 if (hdcMem) {
1145 hOld = SelectObject(hdcMem, hAndBits);
1146 res = StretchDIBits(hdcMem, 0, 0, width, height, 0, 0,
1147 pInfo->bmiHeader.biWidth, pInfo->bmiHeader.biHeight,
1148 xbits, pInfo, DIB_RGB_COLORS, SRCCOPY);
1149 SelectObject(hdcMem, hOld);
1151 if (!res) { DeleteObject(hAndBits); hAndBits = 0; }
1153 } else {
1154 hAndBits = CreateBitmap(width, height, 1, 1, NULL);
1156 if (hAndBits) SetDIBits(screen_dc, hAndBits, 0, height,
1157 xbits, pInfo, DIB_RGB_COLORS);
1160 if( !hAndBits ) DeleteObject( hXorBits );
1162 HeapFree( GetProcessHeap(), 0, pInfo );
1166 if( !hXorBits || !hAndBits )
1168 WARN_(cursor)("\tunable to create an icon bitmap.\n");
1169 return FALSE;
1172 /* Setup a cursor frame, send it to the server */
1173 GetObjectA( hXorBits, sizeof(bmpXor), &bmpXor );
1174 GetObjectA( hAndBits, sizeof(bmpAnd), &bmpAnd );
1175 sizeXor = bmpXor.bmHeight * bmpXor.bmWidthBytes;
1176 sizeAnd = bmpAnd.bmHeight * bmpAnd.bmWidthBytes;
1178 frame->xhot = hotspot.x;
1179 frame->yhot = hotspot.y;
1180 frame->width = bmpXor.bmWidth;
1181 frame->height = bmpXor.bmHeight;
1182 frame->and_width_bytes = bmpAnd.bmWidthBytes;
1183 frame->xor_width_bytes = bmpXor.bmWidthBytes;
1184 frame->planes = bmpXor.bmPlanes;
1185 frame->bpp = bmpXor.bmBitsPixel;
1186 frame->bits = HeapAlloc( GetProcessHeap(), 0, sizeAnd + sizeXor );
1187 GetBitmapBits( hAndBits, sizeAnd, frame->bits );
1188 GetBitmapBits( hXorBits, sizeXor, frame->bits + sizeAnd );
1190 DeleteObject( hAndBits );
1191 DeleteObject( hXorBits );
1193 return TRUE;
1196 /**********************************************************************
1197 * .ANI cursor support
1199 #define RIFF_FOURCC( c0, c1, c2, c3 ) \
1200 ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
1201 ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
1203 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
1204 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
1205 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
1206 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
1207 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
1208 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
1210 #define ANI_FLAG_ICON 0x1
1211 #define ANI_FLAG_SEQUENCE 0x2
1213 typedef struct {
1214 DWORD header_size;
1215 DWORD num_frames;
1216 DWORD num_steps;
1217 DWORD width;
1218 DWORD height;
1219 DWORD bpp;
1220 DWORD num_planes;
1221 DWORD display_rate;
1222 DWORD flags;
1223 } ani_header;
1225 typedef struct {
1226 DWORD data_size;
1227 const unsigned char *data;
1228 } riff_chunk_t;
1230 static void dump_ani_header( const ani_header *header )
1232 TRACE(" header size: %d\n", header->header_size);
1233 TRACE(" frames: %d\n", header->num_frames);
1234 TRACE(" steps: %d\n", header->num_steps);
1235 TRACE(" width: %d\n", header->width);
1236 TRACE(" height: %d\n", header->height);
1237 TRACE(" bpp: %d\n", header->bpp);
1238 TRACE(" planes: %d\n", header->num_planes);
1239 TRACE(" display rate: %d\n", header->display_rate);
1240 TRACE(" flags: 0x%08x\n", header->flags);
1245 * RIFF:
1246 * DWORD "RIFF"
1247 * DWORD size
1248 * DWORD riff_id
1249 * BYTE[] data
1251 * LIST:
1252 * DWORD "LIST"
1253 * DWORD size
1254 * DWORD list_id
1255 * BYTE[] data
1257 * CHUNK:
1258 * DWORD chunk_id
1259 * DWORD size
1260 * BYTE[] data
1262 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
1264 const unsigned char *ptr = parent_chunk->data;
1265 const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
1267 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
1269 while (ptr < end)
1271 if ((!chunk_type && *(DWORD *)ptr == chunk_id )
1272 || (chunk_type && *(DWORD *)ptr == chunk_type && *((DWORD *)ptr + 2) == chunk_id ))
1274 ptr += sizeof(DWORD);
1275 chunk->data_size = *(DWORD *)ptr;
1276 ptr += sizeof(DWORD);
1277 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
1278 chunk->data = ptr;
1280 return;
1283 ptr += sizeof(DWORD);
1284 ptr += *(DWORD *)ptr;
1285 ptr += sizeof(DWORD);
1291 * .ANI layout:
1293 * RIFF:'ACON' RIFF chunk
1294 * |- CHUNK:'anih' Header
1295 * |- CHUNK:'seq ' Sequence information (optional)
1296 * \- LIST:'fram' Frame list
1297 * |- CHUNK:icon Cursor frames
1298 * |- CHUNK:icon
1299 * |- ...
1300 * \- CHUNK:icon
1302 static HCURSOR load_ani( const LPBYTE bits, DWORD bits_size, INT width, INT height )
1304 int i;
1305 WORD max_count = 0;
1306 HCURSOR cursor;
1307 CURSORICONFILEDIR *dir = 0;
1308 ani_header header = {0};
1309 DWORD *frame_seq = 0;
1310 cursor_frame_t *frames;
1311 unsigned int frame_bits_size = 0;
1312 LPBYTE frame_bits = 0;
1313 POINT16 hotspot;
1315 riff_chunk_t root_chunk = { bits_size, bits };
1316 riff_chunk_t ACON_chunk = {0};
1317 riff_chunk_t anih_chunk = {0};
1318 riff_chunk_t fram_chunk = {0};
1319 const unsigned char *icon_chunk;
1320 const unsigned char *icon_data;
1322 TRACE("bits %p, bits_size %d\n", bits, bits_size);
1324 if (!bits) return 0;
1326 riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1327 if (!ACON_chunk.data)
1329 ERR("Failed to get root chunk.\n");
1330 return 0;
1333 riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1334 if (!anih_chunk.data)
1336 ERR("Failed to get 'anih' chunk.\n");
1337 return 0;
1339 memcpy( &header, anih_chunk.data, sizeof(header) );
1340 dump_ani_header( &header );
1342 if (header.flags & ANI_FLAG_SEQUENCE)
1344 riff_chunk_t seq_chunk = {0};
1346 TRACE("Loading sequence data.\n");
1347 riff_find_chunk( ANI_seq__ID, 0, &ACON_chunk, &seq_chunk );
1348 if (!seq_chunk.data)
1350 ERR("Failed to get 'seq ' chunk\n");
1351 return 0;
1353 frame_seq = HeapAlloc( GetProcessHeap(), 0, sizeof(DWORD) * header.num_steps );
1354 memcpy( frame_seq, seq_chunk.data, sizeof(DWORD) * header.num_steps );
1357 riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1358 if (!fram_chunk.data)
1360 ERR("Failed to get icon list\n");
1361 return 0;
1364 icon_chunk = fram_chunk.data;
1365 icon_data = icon_chunk + (2 * sizeof(DWORD));
1366 /* The .ANI stores the display rate in 1/60s, we store the delay between frames in ms */
1367 cursor = create_cursor( header.num_steps, (100 * header.display_rate) / 6 );
1368 frames = HeapAlloc( GetProcessHeap(), 0, header.num_frames * sizeof(cursor_frame_t) );
1370 for (i = 0; i < header.num_frames; ++i)
1372 WORD count;
1373 CURSORICONFILEDIRENTRY *entry;
1374 DWORD chunk_size = *(DWORD *)(icon_chunk + sizeof(DWORD));
1376 /* Read icon count, skip magic */
1377 memcpy( &count, icon_data + sizeof(DWORD), sizeof(WORD) );
1379 /* There's a decent chance the amount of entries will be the same for each icon */
1380 if (count > max_count)
1382 HeapFree( GetProcessHeap(), 0, dir );
1383 /* sizeof(CURSORICONFILEDIRENTRY) for each entry, +6 for magic & count */
1384 dir = HeapAlloc( GetProcessHeap(), 0, (count * sizeof(CURSORICONFILEDIRENTRY)) + 6 );
1385 max_count = count;
1388 /* sizeof(CURSORICONFILEDIRENTRY) for each entry, +6 for magic & count */
1389 memcpy( dir, icon_data, (count * sizeof(CURSORICONFILEDIRENTRY)) + 6 );
1390 entry = CURSORICON_FindBestCursorFile( dir, width, height, 1 );
1392 if (frame_bits_size < entry->dwDIBSize)
1394 frame_bits_size = entry->dwDIBSize;
1395 HeapFree( GetProcessHeap(), 0, frame_bits );
1396 frame_bits = HeapAlloc( GetProcessHeap(), 0, frame_bits_size );
1399 if (!header.width || !header.height)
1401 header.width = entry->bWidth;
1402 header.height = entry->bHeight;
1405 hotspot.x = entry->xHotspot;
1406 hotspot.y = entry->yHotspot;
1408 memcpy( frame_bits, icon_data + entry->dwDIBOffset, entry->dwDIBSize );
1410 load_cursor_frame( frame_bits, entry->dwDIBSize, hotspot, 0x00030000, header.width, header.height, 0, &frames[i] );
1412 /* Advance to the next chunk */
1413 icon_chunk += chunk_size + (2 * sizeof(DWORD));
1414 icon_data = icon_chunk + (2 * sizeof(DWORD));
1416 HeapFree( GetProcessHeap(), 0, dir );
1418 /* Set the frames in the correct sequence */
1419 for (i = 0; i < header.num_steps; ++i)
1421 int frame_idx = (frame_seq ? frame_seq[i] : i);
1422 set_cursor_frame( cursor, i, &frames[frame_idx] );
1425 /* Cleanup */
1426 for (i = 0; i < header.num_frames; ++i)
1428 HeapFree( GetProcessHeap(), 0, frames[i].bits );
1430 HeapFree( GetProcessHeap(), 0, frame_seq );
1431 HeapFree( GetProcessHeap(), 0, frames );
1433 return cursor;
1437 /**********************************************************************
1438 * CreateIconFromResourceEx (USER32.@)
1440 * FIXME: Convert to mono when cFlag is LR_MONOCHROME. Do something
1441 * with cbSize parameter as well.
1443 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1444 BOOL bIcon, DWORD dwVersion,
1445 INT width, INT height,
1446 UINT cFlag )
1448 POINT16 hotspot;
1449 HCURSOR cursor = create_cursor( 1, 0 );
1450 cursor_frame_t frame = {0};
1452 if (bIcon)
1454 hotspot.x = ICON_HOTSPOT;
1455 hotspot.y = ICON_HOTSPOT;
1457 else
1459 hotspot = *(POINT16 *)bits;
1460 bits = (LPBYTE)(((POINT16 *)bits) + 1);
1463 if (load_cursor_frame( bits, cbSize, hotspot, dwVersion, width, height, cFlag, &frame ))
1465 set_cursor_frame( cursor, 0, &frame );
1467 else
1469 destroy_cursor( cursor );
1470 cursor = 0;
1473 HeapFree( GetProcessHeap(), 0, frame.bits );
1475 return cursor;
1479 /**********************************************************************
1480 * CreateIconFromResource (USER32.@)
1482 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1483 BOOL bIcon, DWORD dwVersion)
1485 return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
1489 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1490 INT width, INT height, INT colors,
1491 BOOL fCursor, UINT loadflags)
1493 CURSORICONFILEDIRENTRY *entry;
1494 cursor_frame_t frame = {0};
1495 CURSORICONFILEDIR *dir;
1496 DWORD filesize = 0;
1497 HICON hIcon = 0;
1498 POINT16 hotspot;
1499 LPBYTE bits;
1501 TRACE("loading %s\n", debugstr_w( filename ));
1503 bits = map_fileW( filename, &filesize );
1504 if (!bits)
1505 return hIcon;
1507 /* If the data contains the magic for an .ICO it's an .ICO,
1508 * regardless of what fCursor says. */
1509 if (!memcmp( bits, "\x00\x00\x01\x00", 4 )) fCursor = FALSE;
1510 /* Same thing for .CUR */
1511 else if (!memcmp( bits, "\x00\x00\x02\x00", 4 )) fCursor = TRUE;
1512 /* Check for .ani. */
1513 else if (!memcmp( bits, "RIFF", 4 ))
1515 hIcon = load_ani( bits, filesize, width, height );
1516 goto end;
1519 dir = (CURSORICONFILEDIR*) bits;
1520 if ( filesize < sizeof(*dir) )
1521 goto end;
1523 if ( filesize < (sizeof(*dir) + sizeof(dir->idEntries[0])*(dir->idCount-1)) )
1524 goto end;
1526 if ( fCursor )
1527 entry = CURSORICON_FindBestCursorFile( dir, width, height, colors );
1528 else
1529 entry = CURSORICON_FindBestIconFile( dir, width, height, colors );
1531 if ( !entry )
1532 goto end;
1534 /* check that we don't run off the end of the file */
1535 if ( entry->dwDIBOffset > filesize )
1536 goto end;
1537 if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1538 goto end;
1540 if ( fCursor )
1542 hotspot.x = entry->xHotspot;
1543 hotspot.y = entry->yHotspot;
1545 else
1547 hotspot.x = ICON_HOTSPOT;
1548 hotspot.y = ICON_HOTSPOT;
1551 hIcon = create_cursor( 1, 0 );
1552 load_cursor_frame( &bits[entry->dwDIBOffset], entry->dwDIBSize, hotspot,
1553 0x00030000, width, height, loadflags, &frame );
1554 set_cursor_frame( hIcon, 0, &frame );
1555 HeapFree( GetProcessHeap(), 0, frame.bits );
1557 end:
1558 TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1559 UnmapViewOfFile( bits );
1560 return hIcon;
1563 /**********************************************************************
1564 * CURSORICON_Load
1566 * Load a cursor or icon from resource or file.
1568 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1569 INT width, INT height, INT colors,
1570 BOOL fCursor, UINT loadflags)
1572 HANDLE handle = 0;
1573 HICON hIcon = 0;
1574 HRSRC hRsrc, hGroupRsrc;
1575 CURSORICONDIR *dir;
1576 CURSORICONDIRENTRY *dirEntry;
1577 LPBYTE bits;
1578 WORD wResId;
1579 DWORD dwBytesInRes;
1581 TRACE("%p, %s, %dx%d, colors %d, fCursor %d, flags 0x%04x\n",
1582 hInstance, debugstr_w(name), width, height, colors, fCursor, loadflags);
1584 if ( loadflags & LR_LOADFROMFILE ) /* Load from file */
1585 return CURSORICON_LoadFromFile( name, width, height, colors, fCursor, loadflags );
1587 if (!hInstance) hInstance = user32_module; /* Load OEM cursor/icon */
1589 /* Normalize hInstance (must be uniquely represented for icon cache) */
1591 if (!HIWORD( hInstance ))
1592 hInstance = HINSTANCE_32(GetExePtr( HINSTANCE_16(hInstance) ));
1594 /* Get directory resource ID */
1596 if (!(hRsrc = FindResourceW( hInstance, name,
1597 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1598 return 0;
1599 hGroupRsrc = hRsrc;
1601 /* Find the best entry in the directory */
1603 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1604 if (!(dir = (CURSORICONDIR*)LockResource( handle ))) return 0;
1605 if (fCursor)
1606 dirEntry = CURSORICON_FindBestCursorRes( dir, width, height, 1);
1607 else
1608 dirEntry = CURSORICON_FindBestIconRes( dir, width, height, colors );
1609 if (!dirEntry) return 0;
1610 wResId = dirEntry->wResId;
1611 dwBytesInRes = dirEntry->dwBytesInRes;
1612 FreeResource( handle );
1614 /* Load the resource */
1616 if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1617 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1619 /* If shared icon, check whether it was already loaded */
1620 if ( (loadflags & LR_SHARED)
1621 && (hIcon = CURSORICON_FindSharedIcon( hInstance, hRsrc ) ) != 0 )
1622 return hIcon;
1624 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1625 bits = (LPBYTE)LockResource( handle );
1626 hIcon = CreateIconFromResourceEx( bits, dwBytesInRes,
1627 !fCursor, 0x00030000, width, height, loadflags);
1628 FreeResource( handle );
1630 /* If shared icon, add to icon cache */
1632 if ( hIcon && (loadflags & LR_SHARED) )
1633 CURSORICON_AddSharedIcon( hInstance, hRsrc, hGroupRsrc, hIcon );
1635 return hIcon;
1638 /***********************************************************************
1639 * CURSORICON_Copy
1641 * Make a copy of a cursor or icon.
1643 static HICON CURSORICON_Copy( HINSTANCE16 hInst16, HICON hIcon )
1645 /* Should animated cursors be copyable like this as well? */
1646 HCURSOR new_cursor;
1647 cursor_frame_t frame;
1649 if (!hIcon || !get_cursor_frame( hIcon, 0, &frame ))
1651 return 0;
1654 new_cursor = create_cursor( 1, 0 );
1655 set_cursor_frame( new_cursor, 0, &frame );
1656 HeapFree( GetProcessHeap(), 0, frame.bits );
1658 return new_cursor;
1661 /*************************************************************************
1662 * CURSORICON_ExtCopy
1664 * Copies an Image from the Cache if LR_COPYFROMRESOURCE is specified
1666 * PARAMS
1667 * Handle [I] handle to an Image
1668 * nType [I] Type of Handle (IMAGE_CURSOR | IMAGE_ICON)
1669 * iDesiredCX [I] The Desired width of the Image
1670 * iDesiredCY [I] The desired height of the Image
1671 * nFlags [I] The flags from CopyImage
1673 * RETURNS
1674 * Success: The new handle of the Image
1676 * NOTES
1677 * LR_COPYDELETEORG and LR_MONOCHROME are currently not implemented.
1678 * LR_MONOCHROME should be implemented by CreateIconFromResourceEx.
1679 * LR_COPYFROMRESOURCE will only work if the Image is in the Cache.
1684 static HICON CURSORICON_ExtCopy(HICON hIcon, UINT nType,
1685 INT iDesiredCX, INT iDesiredCY,
1686 UINT nFlags)
1688 HICON hNew=0;
1690 TRACE_(icon)("hIcon %p, nType %u, iDesiredCX %i, iDesiredCY %i, nFlags %u\n",
1691 hIcon, nType, iDesiredCX, iDesiredCY, nFlags);
1693 if(hIcon == 0)
1695 return 0;
1698 /* Best Fit or Monochrome */
1699 if( (nFlags & LR_COPYFROMRESOURCE
1700 && (iDesiredCX > 0 || iDesiredCY > 0))
1701 || nFlags & LR_MONOCHROME)
1703 ICONCACHE* pIconCache = CURSORICON_FindCache(hIcon);
1705 /* Not Found in Cache, then do a straight copy
1707 if(pIconCache == NULL)
1709 hNew = CURSORICON_Copy(0, hIcon);
1710 if(nFlags & LR_COPYFROMRESOURCE)
1712 TRACE_(icon)("LR_COPYFROMRESOURCE: Failed to load from cache\n");
1715 else
1717 int iTargetCY = iDesiredCY, iTargetCX = iDesiredCX;
1718 LPBYTE pBits;
1719 HANDLE hMem;
1720 HRSRC hRsrc;
1721 DWORD dwBytesInRes;
1722 WORD wResId;
1723 CURSORICONDIR *pDir;
1724 CURSORICONDIRENTRY *pDirEntry;
1725 BOOL bIsIcon = (nType == IMAGE_ICON);
1727 /* Completing iDesiredCX CY for Monochrome Bitmaps if needed
1729 if(((nFlags & LR_MONOCHROME) && !(nFlags & LR_COPYFROMRESOURCE))
1730 || (iDesiredCX == 0 && iDesiredCY == 0))
1732 iDesiredCY = GetSystemMetrics(bIsIcon ?
1733 SM_CYICON : SM_CYCURSOR);
1734 iDesiredCX = GetSystemMetrics(bIsIcon ?
1735 SM_CXICON : SM_CXCURSOR);
1738 /* Retrieve the CURSORICONDIRENTRY
1740 if (!(hMem = LoadResource( pIconCache->hModule ,
1741 pIconCache->hGroupRsrc)))
1743 return 0;
1745 if (!(pDir = (CURSORICONDIR*)LockResource( hMem )))
1747 return 0;
1750 /* Find Best Fit
1752 if(bIsIcon)
1754 pDirEntry = CURSORICON_FindBestIconRes(
1755 pDir, iDesiredCX, iDesiredCY, 256 );
1757 else
1759 pDirEntry = CURSORICON_FindBestCursorRes(
1760 pDir, iDesiredCX, iDesiredCY, 1);
1763 wResId = pDirEntry->wResId;
1764 dwBytesInRes = pDirEntry->dwBytesInRes;
1765 FreeResource(hMem);
1767 TRACE_(icon)("ResID %u, BytesInRes %u, Width %d, Height %d DX %d, DY %d\n",
1768 wResId, dwBytesInRes, pDirEntry->ResInfo.icon.bWidth,
1769 pDirEntry->ResInfo.icon.bHeight, iDesiredCX, iDesiredCY);
1771 /* Get the Best Fit
1773 if (!(hRsrc = FindResourceW(pIconCache->hModule ,
1774 MAKEINTRESOURCEW(wResId), (LPWSTR)(bIsIcon ? RT_ICON : RT_CURSOR))))
1776 return 0;
1778 if (!(hMem = LoadResource( pIconCache->hModule , hRsrc )))
1780 return 0;
1783 pBits = (LPBYTE)LockResource( hMem );
1785 if(nFlags & LR_DEFAULTSIZE)
1787 iTargetCY = GetSystemMetrics(SM_CYICON);
1788 iTargetCX = GetSystemMetrics(SM_CXICON);
1791 /* Create a New Icon with the proper dimension
1793 hNew = CreateIconFromResourceEx( pBits, dwBytesInRes,
1794 bIsIcon, 0x00030000, iTargetCX, iTargetCY, nFlags);
1795 FreeResource(hMem);
1798 else hNew = CURSORICON_Copy(0, hIcon);
1799 return hNew;
1803 /***********************************************************************
1804 * CreateCursor (USER32.@)
1806 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
1807 INT xHotSpot, INT yHotSpot,
1808 INT nWidth, INT nHeight,
1809 LPCVOID lpANDbits, LPCVOID lpXORbits )
1811 CURSORICONINFO info;
1813 TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
1814 nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1816 info.ptHotSpot.x = xHotSpot;
1817 info.ptHotSpot.y = yHotSpot;
1818 info.nWidth = nWidth;
1819 info.nHeight = nHeight;
1820 info.nWidthBytes = 0;
1821 info.bPlanes = 1;
1822 info.bBitsPerPixel = 1;
1824 return HICON_32(CreateCursorIconIndirect16(0, &info, lpANDbits, lpXORbits));
1828 /***********************************************************************
1829 * CreateIcon (USER.407)
1831 HICON16 WINAPI CreateIcon16( HINSTANCE16 hInstance, INT16 nWidth,
1832 INT16 nHeight, BYTE bPlanes, BYTE bBitsPixel,
1833 LPCVOID lpANDbits, LPCVOID lpXORbits )
1835 CURSORICONINFO info;
1837 TRACE_(icon)("%dx%dx%d, xor=%p, and=%p\n",
1838 nWidth, nHeight, bPlanes * bBitsPixel, lpXORbits, lpANDbits);
1840 info.ptHotSpot.x = ICON_HOTSPOT;
1841 info.ptHotSpot.y = ICON_HOTSPOT;
1842 info.nWidth = nWidth;
1843 info.nHeight = nHeight;
1844 info.nWidthBytes = 0;
1845 info.bPlanes = bPlanes;
1846 info.bBitsPerPixel = bBitsPixel;
1848 return CreateCursorIconIndirect16( hInstance, &info, lpANDbits, lpXORbits );
1852 /***********************************************************************
1853 * CreateIcon (USER32.@)
1855 * Creates an icon based on the specified bitmaps. The bitmaps must be
1856 * provided in a device dependent format and will be resized to
1857 * (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1858 * depth. The provided bitmaps must be top-down bitmaps.
1859 * Although Windows does not support 15bpp(*) this API must support it
1860 * for Winelib applications.
1862 * (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1863 * format!
1865 * RETURNS
1866 * Success: handle to an icon
1867 * Failure: NULL
1869 * FIXME: Do we need to resize the bitmaps?
1871 HICON WINAPI CreateIcon(
1872 HINSTANCE hInstance, /* [in] the application's hInstance */
1873 INT nWidth, /* [in] the width of the provided bitmaps */
1874 INT nHeight, /* [in] the height of the provided bitmaps */
1875 BYTE bPlanes, /* [in] the number of planes in the provided bitmaps */
1876 BYTE bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1877 LPCVOID lpANDbits, /* [in] a monochrome bitmap representing the icon's mask */
1878 LPCVOID lpXORbits) /* [in] the icon's 'color' bitmap */
1880 ICONINFO iinfo;
1881 HICON hIcon;
1883 TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
1884 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1886 iinfo.fIcon = TRUE;
1887 iinfo.xHotspot = ICON_HOTSPOT;
1888 iinfo.yHotspot = ICON_HOTSPOT;
1889 iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1890 iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );
1892 hIcon = CreateIconIndirect( &iinfo );
1894 DeleteObject( iinfo.hbmMask );
1895 DeleteObject( iinfo.hbmColor );
1897 return hIcon;
1901 /***********************************************************************
1902 * CreateCursorIconIndirect (USER.408)
1904 HGLOBAL16 WINAPI CreateCursorIconIndirect16( HINSTANCE16 hInstance,
1905 CURSORICONINFO *info,
1906 LPCVOID lpANDbits,
1907 LPCVOID lpXORbits )
1909 HCURSOR cursor;
1910 cursor_frame_t frame;
1911 int sizeAnd, sizeXor;
1913 if (!lpXORbits || !lpANDbits || info->bPlanes != 1) return 0;
1914 info->nWidthBytes = get_bitmap_width_bytes(info->nWidth,info->bBitsPerPixel);
1915 sizeXor = info->nHeight * info->nWidthBytes;
1916 sizeAnd = info->nHeight * get_bitmap_width_bytes( info->nWidth, 1 );
1918 cursor = create_cursor( 1, 0 );
1919 frame.xhot = info->ptHotSpot.x;
1920 frame.yhot = info->ptHotSpot.y;
1921 frame.width = info->nWidth;
1922 frame.height = info->nHeight;
1923 frame.and_width_bytes = get_bitmap_width_bytes( info->nWidth, 1 );
1924 frame.xor_width_bytes = info->nWidthBytes;
1925 frame.planes = info->bPlanes;
1926 frame.bpp = info->bBitsPerPixel;
1927 frame.bits = HeapAlloc( GetProcessHeap(), 0, sizeAnd + sizeXor );
1928 CopyMemory( frame.bits, lpANDbits, sizeAnd );
1929 CopyMemory( frame.bits + sizeAnd, lpXORbits, sizeXor );
1930 set_cursor_frame( cursor, 0, &frame );
1931 HeapFree( GetProcessHeap(), 0, frame.bits );
1933 return HICON_16(cursor);
1937 /***********************************************************************
1938 * CopyIcon (USER.368)
1940 HICON16 WINAPI CopyIcon16( HINSTANCE16 hInstance, HICON16 hIcon )
1942 TRACE_(icon)("%04x %04x\n", hInstance, hIcon );
1943 return HICON_16(CURSORICON_Copy(hInstance, HICON_32(hIcon)));
1947 /***********************************************************************
1948 * CopyIcon (USER32.@)
1950 HICON WINAPI CopyIcon( HICON hIcon )
1952 TRACE_(icon)("%p\n", hIcon );
1953 return CURSORICON_Copy( 0, hIcon );
1957 /***********************************************************************
1958 * CopyCursor (USER.369)
1960 HCURSOR16 WINAPI CopyCursor16( HINSTANCE16 hInstance, HCURSOR16 hCursor )
1962 TRACE_(cursor)("%04x %04x\n", hInstance, hCursor );
1963 return HICON_16(CURSORICON_Copy(hInstance, HCURSOR_32(hCursor)));
1966 /**********************************************************************
1967 * DestroyIcon32 (USER.610)
1969 * This routine is actually exported from Win95 USER under the name
1970 * DestroyIcon32 ... The behaviour implemented here should mimic
1971 * the Win95 one exactly, especially the return values, which
1972 * depend on the setting of various flags.
1974 WORD WINAPI DestroyIcon32( HGLOBAL16 handle, UINT16 flags )
1976 WORD retv;
1978 TRACE_(icon)("(%04x, %04x)\n", handle, flags );
1980 /* Check whether destroying active cursor */
1982 if ( get_user_thread_info()->cursor == HICON_32(handle) )
1984 WARN_(cursor)("Destroying active cursor!\n" );
1985 return FALSE;
1988 /* Try shared cursor/icon first */
1990 if ( !(flags & CID_NONSHARED) )
1992 INT count = CURSORICON_DelSharedIcon(HICON_32(handle));
1994 if ( count != -1 )
1995 return (flags & CID_WIN32)? TRUE : (count == 0);
1997 /* FIXME: OEM cursors/icons should be recognized */
2000 /* Now assume non-shared cursor/icon */
2002 retv = destroy_cursor( HCURSOR_32(handle) );
2003 return (flags & CID_RESOURCE)? retv : TRUE;
2006 /***********************************************************************
2007 * DestroyIcon (USER32.@)
2009 BOOL WINAPI DestroyIcon( HICON hIcon )
2011 return DestroyIcon32(HICON_16(hIcon), CID_WIN32);
2015 /***********************************************************************
2016 * DestroyCursor (USER32.@)
2018 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
2020 return DestroyIcon32(HCURSOR_16(hCursor), CID_WIN32);
2024 /***********************************************************************
2025 * DrawIcon (USER32.@)
2027 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
2029 CURSORICONINFO *ptr;
2030 HDC hMemDC;
2031 HBITMAP hXorBits, hAndBits;
2032 COLORREF oldFg, oldBg;
2034 TRACE("%p, (%d,%d), %p\n", hdc, x, y, hIcon);
2036 if (!(ptr = (CURSORICONINFO *)GlobalLock16(HICON_16(hIcon)))) return FALSE;
2037 if (!(hMemDC = CreateCompatibleDC( hdc ))) return FALSE;
2038 hAndBits = CreateBitmap( ptr->nWidth, ptr->nHeight, 1, 1,
2039 (char *)(ptr+1) );
2040 hXorBits = CreateBitmap( ptr->nWidth, ptr->nHeight, ptr->bPlanes,
2041 ptr->bBitsPerPixel, (char *)(ptr + 1)
2042 + ptr->nHeight * get_bitmap_width_bytes(ptr->nWidth,1) );
2043 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2044 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2046 if (hXorBits && hAndBits)
2048 HBITMAP hBitTemp = SelectObject( hMemDC, hAndBits );
2049 BitBlt( hdc, x, y, ptr->nWidth, ptr->nHeight, hMemDC, 0, 0, SRCAND );
2050 SelectObject( hMemDC, hXorBits );
2051 BitBlt(hdc, x, y, ptr->nWidth, ptr->nHeight, hMemDC, 0, 0,SRCINVERT);
2052 SelectObject( hMemDC, hBitTemp );
2054 DeleteDC( hMemDC );
2055 if (hXorBits) DeleteObject( hXorBits );
2056 if (hAndBits) DeleteObject( hAndBits );
2057 GlobalUnlock16(HICON_16(hIcon));
2058 SetTextColor( hdc, oldFg );
2059 SetBkColor( hdc, oldBg );
2060 return TRUE;
2063 /***********************************************************************
2064 * DumpIcon (USER.459)
2066 DWORD WINAPI DumpIcon16( SEGPTR pInfo, WORD *lpLen,
2067 SEGPTR *lpXorBits, SEGPTR *lpAndBits )
2069 CURSORICONINFO *info = MapSL( pInfo );
2070 int sizeAnd, sizeXor;
2072 if (!info) return 0;
2073 sizeXor = info->nHeight * info->nWidthBytes;
2074 sizeAnd = info->nHeight * get_bitmap_width_bytes( info->nWidth, 1 );
2075 if (lpAndBits) *lpAndBits = pInfo + sizeof(CURSORICONINFO);
2076 if (lpXorBits) *lpXorBits = pInfo + sizeof(CURSORICONINFO) + sizeAnd;
2077 if (lpLen) *lpLen = sizeof(CURSORICONINFO) + sizeAnd + sizeXor;
2078 return MAKELONG( sizeXor, sizeXor );
2082 /***********************************************************************
2083 * SetCursor (USER32.@)
2085 * Set the cursor shape.
2087 * RETURNS
2088 * A handle to the previous cursor shape.
2090 HCURSOR WINAPI SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
2092 struct user_thread_info *thread_info = get_user_thread_info();
2093 HCURSOR hOldCursor;
2095 if (hCursor == thread_info->cursor) return hCursor; /* No change */
2096 TRACE("%p\n", hCursor);
2097 hOldCursor = thread_info->cursor;
2098 thread_info->cursor = hCursor;
2099 /* Change the cursor shape only if it is visible */
2100 if (thread_info->cursor_count >= 0)
2102 cursor_t *cursor;
2104 update_cursor_32from16( hCursor );
2105 cursor = get_cursor_object( hCursor );
2106 USER_Driver->pSetCursor( cursor );
2107 destroy_cursor_object( cursor );
2109 return hOldCursor;
2112 /***********************************************************************
2113 * ShowCursor (USER32.@)
2115 INT WINAPI ShowCursor( BOOL bShow )
2117 struct user_thread_info *thread_info = get_user_thread_info();
2119 TRACE("%d, count=%d\n", bShow, thread_info->cursor_count );
2121 if (bShow)
2123 if (++thread_info->cursor_count == 0) /* Show it */
2125 cursor_t *cursor;
2127 update_cursor_32from16( thread_info->cursor );
2128 cursor = get_cursor_object( thread_info->cursor );
2129 USER_Driver->pSetCursor( cursor );
2130 destroy_cursor_object( cursor );
2133 else
2135 if (--thread_info->cursor_count == -1) /* Hide it */
2136 USER_Driver->pSetCursor( NULL );
2138 return thread_info->cursor_count;
2141 /***********************************************************************
2142 * GetCursor (USER32.@)
2144 HCURSOR WINAPI GetCursor(void)
2146 return get_user_thread_info()->cursor;
2150 /***********************************************************************
2151 * ClipCursor (USER32.@)
2153 BOOL WINAPI ClipCursor( const RECT *rect )
2155 RECT virt;
2157 SetRect( &virt, 0, 0, GetSystemMetrics( SM_CXVIRTUALSCREEN ),
2158 GetSystemMetrics( SM_CYVIRTUALSCREEN ) );
2159 OffsetRect( &virt, GetSystemMetrics( SM_XVIRTUALSCREEN ),
2160 GetSystemMetrics( SM_YVIRTUALSCREEN ) );
2162 TRACE( "Clipping to: %s was: %s screen: %s\n", wine_dbgstr_rect(rect),
2163 wine_dbgstr_rect(&CURSOR_ClipRect), wine_dbgstr_rect(&virt) );
2165 if (!IntersectRect( &CURSOR_ClipRect, &virt, rect ))
2166 CURSOR_ClipRect = virt;
2168 USER_Driver->pClipCursor( rect );
2169 return TRUE;
2173 /***********************************************************************
2174 * GetClipCursor (USER32.@)
2176 BOOL WINAPI GetClipCursor( RECT *rect )
2178 /* If this is first time - initialize the rect */
2179 if (IsRectEmpty( &CURSOR_ClipRect )) ClipCursor( NULL );
2181 return CopyRect( rect, &CURSOR_ClipRect );
2185 /***********************************************************************
2186 * SetSystemCursor (USER32.@)
2188 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
2190 FIXME("(%p,%08x),stub!\n", hcur, id);
2191 return TRUE;
2195 /**********************************************************************
2196 * LookupIconIdFromDirectoryEx (USER.364)
2198 * FIXME: exact parameter sizes
2200 INT16 WINAPI LookupIconIdFromDirectoryEx16( LPBYTE dir, BOOL16 bIcon,
2201 INT16 width, INT16 height, UINT16 cFlag )
2203 return LookupIconIdFromDirectoryEx( dir, bIcon, width, height, cFlag );
2206 /**********************************************************************
2207 * LookupIconIdFromDirectoryEx (USER32.@)
2209 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
2210 INT width, INT height, UINT cFlag )
2212 CURSORICONDIR *dir = (CURSORICONDIR*)xdir;
2213 UINT retVal = 0;
2214 if( dir && !dir->idReserved && (dir->idType & 3) )
2216 CURSORICONDIRENTRY* entry;
2217 HDC hdc;
2218 UINT palEnts;
2219 int colors;
2220 hdc = GetDC(0);
2221 palEnts = GetSystemPaletteEntries(hdc, 0, 0, NULL);
2222 if (palEnts == 0)
2223 palEnts = 256;
2224 colors = (cFlag & LR_MONOCHROME) ? 2 : palEnts;
2226 ReleaseDC(0, hdc);
2228 if( bIcon )
2229 entry = CURSORICON_FindBestIconRes( dir, width, height, colors );
2230 else
2231 entry = CURSORICON_FindBestCursorRes( dir, width, height, 1);
2233 if( entry ) retVal = entry->wResId;
2235 else WARN_(cursor)("invalid resource directory\n");
2236 return retVal;
2239 /**********************************************************************
2240 * LookupIconIdFromDirectory (USER.?)
2242 INT16 WINAPI LookupIconIdFromDirectory16( LPBYTE dir, BOOL16 bIcon )
2244 return LookupIconIdFromDirectoryEx16( dir, bIcon,
2245 bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
2246 bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
2249 /**********************************************************************
2250 * LookupIconIdFromDirectory (USER32.@)
2252 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
2254 return LookupIconIdFromDirectoryEx( dir, bIcon,
2255 bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
2256 bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
2259 /**********************************************************************
2260 * GetIconID (USER.455)
2262 WORD WINAPI GetIconID16( HGLOBAL16 hResource, DWORD resType )
2264 LPBYTE lpDir = (LPBYTE)GlobalLock16(hResource);
2266 TRACE_(cursor)("hRes=%04x, entries=%i\n",
2267 hResource, lpDir ? ((CURSORICONDIR*)lpDir)->idCount : 0);
2269 switch(resType)
2271 case RT_CURSOR:
2272 return (WORD)LookupIconIdFromDirectoryEx16( lpDir, FALSE,
2273 GetSystemMetrics(SM_CXCURSOR), GetSystemMetrics(SM_CYCURSOR), LR_MONOCHROME );
2274 case RT_ICON:
2275 return (WORD)LookupIconIdFromDirectoryEx16( lpDir, TRUE,
2276 GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), 0 );
2277 default:
2278 WARN_(cursor)("invalid res type %d\n", resType );
2280 return 0;
2283 /**********************************************************************
2284 * LoadCursorIconHandler (USER.336)
2286 * Supposed to load resources of Windows 2.x applications.
2288 HGLOBAL16 WINAPI LoadCursorIconHandler16( HGLOBAL16 hResource, HMODULE16 hModule, HRSRC16 hRsrc )
2290 FIXME_(cursor)("(%04x,%04x,%04x): old 2.x resources are not supported!\n",
2291 hResource, hModule, hRsrc);
2292 return (HGLOBAL16)0;
2295 /**********************************************************************
2296 * LoadIconHandler (USER.456)
2298 HICON16 WINAPI LoadIconHandler16( HGLOBAL16 hResource, BOOL16 bNew )
2300 LPBYTE bits = (LPBYTE)LockResource16( hResource );
2302 TRACE_(cursor)("hRes=%04x\n",hResource);
2304 return HICON_16(CreateIconFromResourceEx( bits, 0, TRUE,
2305 bNew ? 0x00030000 : 0x00020000, 0, 0, LR_DEFAULTCOLOR));
2308 /***********************************************************************
2309 * LoadCursorW (USER32.@)
2311 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
2313 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2315 return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
2316 LR_SHARED | LR_DEFAULTSIZE );
2319 /***********************************************************************
2320 * LoadCursorA (USER32.@)
2322 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
2324 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2326 return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
2327 LR_SHARED | LR_DEFAULTSIZE );
2330 /***********************************************************************
2331 * LoadCursorFromFileW (USER32.@)
2333 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
2335 TRACE("%s\n", debugstr_w(name));
2337 return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
2338 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2341 /***********************************************************************
2342 * LoadCursorFromFileA (USER32.@)
2344 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
2346 TRACE("%s\n", debugstr_a(name));
2348 return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
2349 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2352 /***********************************************************************
2353 * LoadIconW (USER32.@)
2355 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
2357 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2359 return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
2360 LR_SHARED | LR_DEFAULTSIZE );
2363 /***********************************************************************
2364 * LoadIconA (USER32.@)
2366 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
2368 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2370 return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
2371 LR_SHARED | LR_DEFAULTSIZE );
2374 /**********************************************************************
2375 * GetIconInfo (USER32.@)
2377 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
2379 CURSORICONINFO *ciconinfo;
2380 INT height;
2382 ciconinfo = GlobalLock16(HICON_16(hIcon));
2383 if (!ciconinfo)
2384 return FALSE;
2386 TRACE("%p => %dx%d, %d bpp\n", hIcon,
2387 ciconinfo->nWidth, ciconinfo->nHeight, ciconinfo->bBitsPerPixel);
2389 if ( (ciconinfo->ptHotSpot.x == ICON_HOTSPOT) &&
2390 (ciconinfo->ptHotSpot.y == ICON_HOTSPOT) )
2392 iconinfo->fIcon = TRUE;
2393 iconinfo->xHotspot = ciconinfo->nWidth / 2;
2394 iconinfo->yHotspot = ciconinfo->nHeight / 2;
2396 else
2398 iconinfo->fIcon = FALSE;
2399 iconinfo->xHotspot = ciconinfo->ptHotSpot.x;
2400 iconinfo->yHotspot = ciconinfo->ptHotSpot.y;
2403 height = ciconinfo->nHeight;
2405 if (ciconinfo->bBitsPerPixel > 1)
2407 iconinfo->hbmColor = CreateBitmap( ciconinfo->nWidth, ciconinfo->nHeight,
2408 ciconinfo->bPlanes, ciconinfo->bBitsPerPixel,
2409 (char *)(ciconinfo + 1)
2410 + ciconinfo->nHeight *
2411 get_bitmap_width_bytes (ciconinfo->nWidth,1) );
2413 else
2415 iconinfo->hbmColor = 0;
2416 height *= 2;
2419 iconinfo->hbmMask = CreateBitmap ( ciconinfo->nWidth, height,
2420 1, 1, (char *)(ciconinfo + 1));
2422 GlobalUnlock16(HICON_16(hIcon));
2424 return TRUE;
2427 /**********************************************************************
2428 * CreateIconIndirect (USER32.@)
2430 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
2432 HCURSOR cursor;
2433 cursor_frame_t frame;
2434 BITMAP bmpXor,bmpAnd;
2435 int sizeXor,sizeAnd;
2437 TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
2438 iconinfo->hbmColor, iconinfo->hbmMask,
2439 iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
2441 if (!iconinfo->hbmMask) return 0;
2443 if (iconinfo->hbmColor)
2445 GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2446 TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2447 bmpXor.bmWidth, bmpXor.bmHeight, bmpXor.bmWidthBytes,
2448 bmpXor.bmPlanes, bmpXor.bmBitsPixel);
2450 GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
2451 TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2452 bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
2453 bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
2455 sizeXor = iconinfo->hbmColor ? (bmpXor.bmHeight * bmpXor.bmWidthBytes) : 0;
2456 sizeAnd = bmpAnd.bmHeight * get_bitmap_width_bytes(bmpAnd.bmWidth, 1);
2458 cursor = create_cursor( 1, 0 );
2460 /* If we are creating an icon, the hotspot is unused */
2461 if (iconinfo->fIcon)
2463 frame.xhot = ICON_HOTSPOT;
2464 frame.yhot = ICON_HOTSPOT;
2466 else
2468 frame.xhot = iconinfo->xHotspot;
2469 frame.yhot = iconinfo->yHotspot;
2472 if (iconinfo->hbmColor)
2474 frame.width = bmpXor.bmWidth;
2475 frame.height = bmpXor.bmHeight;
2476 frame.and_width_bytes = bmpAnd.bmWidthBytes;
2477 frame.xor_width_bytes = bmpXor.bmWidthBytes;
2478 frame.planes = bmpXor.bmPlanes;
2479 frame.bpp = bmpXor.bmBitsPixel;
2481 else
2483 frame.width = bmpAnd.bmWidth;
2484 frame.height = bmpAnd.bmHeight / 2;
2485 frame.and_width_bytes = get_bitmap_width_bytes(bmpAnd.bmWidth, 1);
2486 frame.xor_width_bytes = 0;
2487 frame.planes = 1;
2488 frame.bpp = 1;
2491 frame.bits = HeapAlloc( GetProcessHeap(), 0, sizeAnd + sizeXor );
2493 /* Some apps pass a color bitmap as a mask, convert it to b/w */
2494 if (bmpAnd.bmBitsPixel == 1)
2496 GetBitmapBits( iconinfo->hbmMask, sizeAnd, frame.bits );
2498 else
2500 HDC hdc, hdc_mem;
2501 HBITMAP hbmp_old, hbmp_mem_old, hbmp_mono;
2503 hdc = GetDC( 0 );
2504 hdc_mem = CreateCompatibleDC( hdc );
2506 hbmp_mono = CreateBitmap( bmpAnd.bmWidth, bmpAnd.bmHeight, 1, 1, NULL );
2508 hbmp_old = SelectObject( hdc, iconinfo->hbmMask );
2509 hbmp_mem_old = SelectObject( hdc_mem, hbmp_mono );
2511 BitBlt( hdc_mem, 0, 0, bmpAnd.bmWidth, bmpAnd.bmHeight, hdc, 0, 0, SRCCOPY );
2513 SelectObject( hdc, hbmp_old );
2514 SelectObject( hdc_mem, hbmp_mem_old );
2516 DeleteDC( hdc_mem );
2517 ReleaseDC( 0, hdc );
2519 GetBitmapBits( hbmp_mono, sizeAnd, frame.bits );
2520 DeleteObject( hbmp_mono );
2523 if (iconinfo->hbmColor) GetBitmapBits( iconinfo->hbmColor, sizeXor, frame.bits + sizeAnd );
2524 set_cursor_frame( cursor, 0, &frame );
2525 HeapFree( GetProcessHeap(), 0, frame.bits );
2527 return cursor;
2530 /******************************************************************************
2531 * DrawIconEx (USER32.@) Draws an icon or cursor on device context
2533 * NOTES
2534 * Why is this using SM_CXICON instead of SM_CXCURSOR?
2536 * PARAMS
2537 * hdc [I] Handle to device context
2538 * x0 [I] X coordinate of upper left corner
2539 * y0 [I] Y coordinate of upper left corner
2540 * hIcon [I] Handle to icon to draw
2541 * cxWidth [I] Width of icon
2542 * cyWidth [I] Height of icon
2543 * istep [I] Index of frame in animated cursor
2544 * hbr [I] Handle to background brush
2545 * flags [I] Icon-drawing flags
2547 * RETURNS
2548 * Success: TRUE
2549 * Failure: FALSE
2551 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2552 INT cxWidth, INT cyWidth, UINT istep,
2553 HBRUSH hbr, UINT flags )
2555 CURSORICONINFO *ptr = (CURSORICONINFO *)GlobalLock16(HICON_16(hIcon));
2556 HDC hDC_off = 0, hMemDC;
2557 BOOL result = FALSE, DoOffscreen;
2558 HBITMAP hB_off = 0, hOld = 0;
2560 if (!ptr) return FALSE;
2561 TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2562 hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2564 hMemDC = CreateCompatibleDC (hdc);
2565 if (istep)
2566 FIXME_(icon)("Ignoring istep=%d\n", istep);
2567 if (flags & DI_COMPAT)
2568 FIXME_(icon)("Ignoring flag DI_COMPAT\n");
2570 if (!flags) {
2571 FIXME_(icon)("no flags set? setting to DI_NORMAL\n");
2572 flags = DI_NORMAL;
2575 /* Calculate the size of the destination image. */
2576 if (cxWidth == 0)
2578 if (flags & DI_DEFAULTSIZE)
2579 cxWidth = GetSystemMetrics (SM_CXICON);
2580 else
2581 cxWidth = ptr->nWidth;
2583 if (cyWidth == 0)
2585 if (flags & DI_DEFAULTSIZE)
2586 cyWidth = GetSystemMetrics (SM_CYICON);
2587 else
2588 cyWidth = ptr->nHeight;
2591 DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2593 if (DoOffscreen) {
2594 RECT r;
2596 r.left = 0;
2597 r.top = 0;
2598 r.right = cxWidth;
2599 r.bottom = cxWidth;
2601 hDC_off = CreateCompatibleDC(hdc);
2602 hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth);
2603 if (hDC_off && hB_off) {
2604 hOld = SelectObject(hDC_off, hB_off);
2605 FillRect(hDC_off, &r, hbr);
2609 if (hMemDC && (!DoOffscreen || (hDC_off && hB_off)))
2611 HBITMAP hXorBits, hAndBits;
2612 COLORREF oldFg, oldBg;
2613 INT nStretchMode;
2615 nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2617 hXorBits = CreateBitmap ( ptr->nWidth, ptr->nHeight,
2618 ptr->bPlanes, ptr->bBitsPerPixel,
2619 (char *)(ptr + 1)
2620 + ptr->nHeight *
2621 get_bitmap_width_bytes(ptr->nWidth,1) );
2622 hAndBits = CreateBitmap ( ptr->nWidth, ptr->nHeight,
2623 1, 1, (char *)(ptr+1) );
2624 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2625 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2627 if (hXorBits && hAndBits)
2629 HBITMAP hBitTemp = SelectObject( hMemDC, hAndBits );
2630 if (flags & DI_MASK)
2632 if (DoOffscreen)
2633 StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
2634 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
2635 else
2636 StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
2637 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
2639 SelectObject( hMemDC, hXorBits );
2640 if (flags & DI_IMAGE)
2642 if (DoOffscreen)
2643 StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
2644 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
2645 else
2646 StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
2647 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
2649 SelectObject( hMemDC, hBitTemp );
2650 result = TRUE;
2653 SetTextColor( hdc, oldFg );
2654 SetBkColor( hdc, oldBg );
2655 if (hXorBits) DeleteObject( hXorBits );
2656 if (hAndBits) DeleteObject( hAndBits );
2657 SetStretchBltMode (hdc, nStretchMode);
2658 if (DoOffscreen) {
2659 BitBlt(hdc, x0, y0, cxWidth, cyWidth, hDC_off, 0, 0, SRCCOPY);
2660 SelectObject(hDC_off, hOld);
2663 if (hMemDC) DeleteDC( hMemDC );
2664 if (hDC_off) DeleteDC(hDC_off);
2665 if (hB_off) DeleteObject(hB_off);
2666 GlobalUnlock16(HICON_16(hIcon));
2667 return result;
2670 /***********************************************************************
2671 * DIB_FixColorsToLoadflags
2673 * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2674 * are in loadflags
2676 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2678 int colors;
2679 COLORREF c_W, c_S, c_F, c_L, c_C;
2680 int incr,i;
2681 RGBQUAD *ptr;
2682 int bitmap_type;
2683 LONG width;
2684 LONG height;
2685 WORD bpp;
2686 DWORD compr;
2688 if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2690 WARN_(resource)("Invalid bitmap\n");
2691 return;
2694 if (bpp > 8) return;
2696 if (bitmap_type == 0) /* BITMAPCOREHEADER */
2698 incr = 3;
2699 colors = 1 << bpp;
2701 else
2703 incr = 4;
2704 colors = bmi->bmiHeader.biClrUsed;
2705 if (colors > 256) colors = 256;
2706 if (!colors && (bpp <= 8)) colors = 1 << bpp;
2709 c_W = GetSysColor(COLOR_WINDOW);
2710 c_S = GetSysColor(COLOR_3DSHADOW);
2711 c_F = GetSysColor(COLOR_3DFACE);
2712 c_L = GetSysColor(COLOR_3DLIGHT);
2714 if (loadflags & LR_LOADTRANSPARENT) {
2715 switch (bpp) {
2716 case 1: pix = pix >> 7; break;
2717 case 4: pix = pix >> 4; break;
2718 case 8: break;
2719 default:
2720 WARN_(resource)("(%d): Unsupported depth\n", bpp);
2721 return;
2723 if (pix >= colors) {
2724 WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2725 return;
2727 if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2728 ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2729 ptr->rgbBlue = GetBValue(c_W);
2730 ptr->rgbGreen = GetGValue(c_W);
2731 ptr->rgbRed = GetRValue(c_W);
2733 if (loadflags & LR_LOADMAP3DCOLORS)
2734 for (i=0; i<colors; i++) {
2735 ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2736 c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2737 if (c_C == RGB(128, 128, 128)) {
2738 ptr->rgbRed = GetRValue(c_S);
2739 ptr->rgbGreen = GetGValue(c_S);
2740 ptr->rgbBlue = GetBValue(c_S);
2741 } else if (c_C == RGB(192, 192, 192)) {
2742 ptr->rgbRed = GetRValue(c_F);
2743 ptr->rgbGreen = GetGValue(c_F);
2744 ptr->rgbBlue = GetBValue(c_F);
2745 } else if (c_C == RGB(223, 223, 223)) {
2746 ptr->rgbRed = GetRValue(c_L);
2747 ptr->rgbGreen = GetGValue(c_L);
2748 ptr->rgbBlue = GetBValue(c_L);
2754 /**********************************************************************
2755 * BITMAP_Load
2757 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2758 INT desiredx, INT desiredy, UINT loadflags )
2760 HBITMAP hbitmap = 0, orig_bm;
2761 HRSRC hRsrc;
2762 HGLOBAL handle;
2763 char *ptr = NULL;
2764 BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2765 int size;
2766 BYTE pix;
2767 char *bits;
2768 LONG width, height, new_width, new_height;
2769 WORD bpp_dummy;
2770 DWORD compr_dummy;
2771 INT bm_type;
2772 HDC screen_mem_dc = NULL;
2774 if (!(loadflags & LR_LOADFROMFILE))
2776 if (!instance)
2778 /* OEM bitmap: try to load the resource from user32.dll */
2779 instance = user32_module;
2782 if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2783 if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2785 if ((info = (BITMAPINFO *)LockResource( handle )) == NULL) return 0;
2787 else
2789 if (!(ptr = map_fileW( name, NULL ))) return 0;
2790 info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2793 size = bitmap_info_size(info, DIB_RGB_COLORS);
2794 fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2795 scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2797 if (!fix_info || !scaled_info) goto end;
2798 memcpy(fix_info, info, size);
2800 pix = *((LPBYTE)info + size);
2801 DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2803 memcpy(scaled_info, fix_info, size);
2804 bm_type = DIB_GetBitmapInfo( &fix_info->bmiHeader, &width, &height,
2805 &bpp_dummy, &compr_dummy);
2806 if(desiredx != 0)
2807 new_width = desiredx;
2808 else
2809 new_width = width;
2811 if(desiredy != 0)
2812 new_height = height > 0 ? desiredy : -desiredy;
2813 else
2814 new_height = height;
2816 if(bm_type == 0)
2818 BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2819 core->bcWidth = new_width;
2820 core->bcHeight = new_height;
2822 else
2824 scaled_info->bmiHeader.biWidth = new_width;
2825 scaled_info->bmiHeader.biHeight = new_height;
2828 if (new_height < 0) new_height = -new_height;
2830 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2831 if (!(screen_mem_dc = CreateCompatibleDC( screen_dc ))) goto end;
2833 bits = (char *)info + size;
2835 if (loadflags & LR_CREATEDIBSECTION)
2837 scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2838 hbitmap = CreateDIBSection(screen_dc, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2840 else
2842 if (is_dib_monochrome(fix_info))
2843 hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2844 else
2845 hbitmap = CreateCompatibleBitmap(screen_dc, new_width, new_height);
2848 orig_bm = SelectObject(screen_mem_dc, hbitmap);
2849 StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2850 SelectObject(screen_mem_dc, orig_bm);
2852 end:
2853 if (screen_mem_dc) DeleteDC(screen_mem_dc);
2854 HeapFree(GetProcessHeap(), 0, scaled_info);
2855 HeapFree(GetProcessHeap(), 0, fix_info);
2856 if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2858 return hbitmap;
2861 /**********************************************************************
2862 * LoadImageA (USER32.@)
2864 * See LoadImageW.
2866 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2867 INT desiredx, INT desiredy, UINT loadflags)
2869 HANDLE res;
2870 LPWSTR u_name;
2872 if (!HIWORD(name))
2873 return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2875 __TRY {
2876 DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2877 u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2878 MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2880 __EXCEPT_PAGE_FAULT {
2881 SetLastError( ERROR_INVALID_PARAMETER );
2882 return 0;
2884 __ENDTRY
2885 res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2886 HeapFree(GetProcessHeap(), 0, u_name);
2887 return res;
2891 /******************************************************************************
2892 * LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2894 * PARAMS
2895 * hinst [I] Handle of instance that contains image
2896 * name [I] Name of image
2897 * type [I] Type of image
2898 * desiredx [I] Desired width
2899 * desiredy [I] Desired height
2900 * loadflags [I] Load flags
2902 * RETURNS
2903 * Success: Handle to newly loaded image
2904 * Failure: NULL
2906 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2908 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2909 INT desiredx, INT desiredy, UINT loadflags )
2911 TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
2912 hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
2914 if (loadflags & LR_DEFAULTSIZE) {
2915 if (type == IMAGE_ICON) {
2916 if (!desiredx) desiredx = GetSystemMetrics(SM_CXICON);
2917 if (!desiredy) desiredy = GetSystemMetrics(SM_CYICON);
2918 } else if (type == IMAGE_CURSOR) {
2919 if (!desiredx) desiredx = GetSystemMetrics(SM_CXCURSOR);
2920 if (!desiredy) desiredy = GetSystemMetrics(SM_CYCURSOR);
2923 if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
2924 switch (type) {
2925 case IMAGE_BITMAP:
2926 return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2928 case IMAGE_ICON:
2929 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2930 if (screen_dc)
2932 UINT palEnts = GetSystemPaletteEntries(screen_dc, 0, 0, NULL);
2933 if (palEnts == 0) palEnts = 256;
2934 return CURSORICON_Load(hinst, name, desiredx, desiredy,
2935 palEnts, FALSE, loadflags);
2937 break;
2939 case IMAGE_CURSOR:
2940 return CURSORICON_Load(hinst, name, desiredx, desiredy,
2941 1, TRUE, loadflags);
2943 return 0;
2946 /******************************************************************************
2947 * CopyImage (USER32.@) Creates new image and copies attributes to it
2949 * PARAMS
2950 * hnd [I] Handle to image to copy
2951 * type [I] Type of image to copy
2952 * desiredx [I] Desired width of new image
2953 * desiredy [I] Desired height of new image
2954 * flags [I] Copy flags
2956 * RETURNS
2957 * Success: Handle to newly created image
2958 * Failure: NULL
2960 * BUGS
2961 * Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
2962 * all other versions (95/2000/XP have been tested) ignore it.
2964 * NOTES
2965 * If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
2966 * a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
2967 * the copy will have the same depth as the screen.
2968 * The content of the image will only be copied if the bit depth of the
2969 * original image is compatible with the bit depth of the screen, or
2970 * if the source is a DIB section.
2971 * The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
2973 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2974 INT desiredy, UINT flags )
2976 TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
2977 hnd, type, desiredx, desiredy, flags);
2979 switch (type)
2981 case IMAGE_BITMAP:
2983 HBITMAP res = NULL;
2984 DIBSECTION ds;
2985 int objSize;
2986 BITMAPINFO * bi;
2988 objSize = GetObjectW( hnd, sizeof(ds), &ds );
2989 if (!objSize) return 0;
2990 if ((desiredx < 0) || (desiredy < 0)) return 0;
2992 if (flags & LR_COPYFROMRESOURCE)
2994 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
2997 if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
2998 if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
3000 /* Allocate memory for a BITMAPINFOHEADER structure and a
3001 color table. The maximum number of colors in a color table
3002 is 256 which corresponds to a bitmap with depth 8.
3003 Bitmaps with higher depths don't have color tables. */
3004 bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
3005 if (!bi) return 0;
3007 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
3008 bi->bmiHeader.biPlanes = ds.dsBm.bmPlanes;
3009 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
3010 bi->bmiHeader.biCompression = BI_RGB;
3012 if (flags & LR_CREATEDIBSECTION)
3014 /* Create a DIB section. LR_MONOCHROME is ignored */
3015 void * bits;
3016 HDC dc = CreateCompatibleDC(NULL);
3018 if (objSize == sizeof(DIBSECTION))
3020 /* The source bitmap is a DIB.
3021 Get its attributes to create an exact copy */
3022 memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
3025 /* Get the color table or the color masks */
3026 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3028 bi->bmiHeader.biWidth = desiredx;
3029 bi->bmiHeader.biHeight = desiredy;
3030 bi->bmiHeader.biSizeImage = 0;
3032 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
3033 DeleteDC(dc);
3035 else
3037 /* Create a device-dependent bitmap */
3039 BOOL monochrome = (flags & LR_MONOCHROME);
3041 if (objSize == sizeof(DIBSECTION))
3043 /* The source bitmap is a DIB section.
3044 Get its attributes */
3045 HDC dc = CreateCompatibleDC(NULL);
3046 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
3047 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
3048 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3049 DeleteDC(dc);
3051 if (!monochrome && ds.dsBm.bmBitsPixel == 1)
3053 /* Look if the colors of the DIB are black and white */
3055 monochrome =
3056 (bi->bmiColors[0].rgbRed == 0xff
3057 && bi->bmiColors[0].rgbGreen == 0xff
3058 && bi->bmiColors[0].rgbBlue == 0xff
3059 && bi->bmiColors[0].rgbReserved == 0
3060 && bi->bmiColors[1].rgbRed == 0
3061 && bi->bmiColors[1].rgbGreen == 0
3062 && bi->bmiColors[1].rgbBlue == 0
3063 && bi->bmiColors[1].rgbReserved == 0)
3065 (bi->bmiColors[0].rgbRed == 0
3066 && bi->bmiColors[0].rgbGreen == 0
3067 && bi->bmiColors[0].rgbBlue == 0
3068 && bi->bmiColors[0].rgbReserved == 0
3069 && bi->bmiColors[1].rgbRed == 0xff
3070 && bi->bmiColors[1].rgbGreen == 0xff
3071 && bi->bmiColors[1].rgbBlue == 0xff
3072 && bi->bmiColors[1].rgbReserved == 0);
3075 else if (!monochrome)
3077 monochrome = ds.dsBm.bmBitsPixel == 1;
3080 if (monochrome)
3082 res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
3084 else
3086 HDC screenDC = GetDC(NULL);
3087 res = CreateCompatibleBitmap(screenDC, desiredx, desiredy);
3088 ReleaseDC(NULL, screenDC);
3092 if (res)
3094 /* Only copy the bitmap if it's a DIB section or if it's
3095 compatible to the screen */
3096 BOOL copyContents;
3098 if (objSize == sizeof(DIBSECTION))
3100 copyContents = TRUE;
3102 else
3104 HDC screenDC = GetDC(NULL);
3105 int screen_depth = GetDeviceCaps(screenDC, BITSPIXEL);
3106 ReleaseDC(NULL, screenDC);
3108 copyContents = (ds.dsBm.bmBitsPixel == 1 || ds.dsBm.bmBitsPixel == screen_depth);
3111 if (copyContents)
3113 /* The source bitmap may already be selected in a device context,
3114 use GetDIBits/StretchDIBits and not StretchBlt */
3116 HDC dc;
3117 void * bits;
3119 dc = CreateCompatibleDC(NULL);
3121 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
3122 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
3123 bi->bmiHeader.biSizeImage = 0;
3124 bi->bmiHeader.biClrUsed = 0;
3125 bi->bmiHeader.biClrImportant = 0;
3127 /* Fill in biSizeImage */
3128 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3129 bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
3131 if (bits)
3133 HBITMAP oldBmp;
3135 /* Get the image bits of the source bitmap */
3136 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
3138 /* Copy it to the destination bitmap */
3139 oldBmp = SelectObject(dc, res);
3140 StretchDIBits(dc, 0, 0, desiredx, desiredy,
3141 0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
3142 bits, bi, DIB_RGB_COLORS, SRCCOPY);
3143 SelectObject(dc, oldBmp);
3145 HeapFree(GetProcessHeap(), 0, bits);
3148 DeleteDC(dc);
3151 if (flags & LR_COPYDELETEORG)
3153 DeleteObject(hnd);
3156 HeapFree(GetProcessHeap(), 0, bi);
3157 return res;
3159 case IMAGE_ICON:
3160 return CURSORICON_ExtCopy(hnd,type, desiredx, desiredy, flags);
3161 case IMAGE_CURSOR:
3162 /* Should call CURSORICON_ExtCopy but more testing
3163 * needs to be done before we change this
3165 if (flags) FIXME("Flags are ignored\n");
3166 return CopyCursor(hnd);
3168 return 0;
3172 /******************************************************************************
3173 * LoadBitmapW (USER32.@) Loads bitmap from the executable file
3175 * RETURNS
3176 * Success: Handle to specified bitmap
3177 * Failure: NULL
3179 HBITMAP WINAPI LoadBitmapW(
3180 HINSTANCE instance, /* [in] Handle to application instance */
3181 LPCWSTR name) /* [in] Address of bitmap resource name */
3183 return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
3186 /**********************************************************************
3187 * LoadBitmapA (USER32.@)
3189 * See LoadBitmapW.
3191 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
3193 return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );