[09/10] user: Add support for .ani cursors
[wine/hacks.git] / dlls / user32 / cursoricon.c
blob9ec28c2f5d4b5d4c4d565309988c8eb6280727fd
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 * 32-bit cursors and icons are stored in the server.
30 * 16-bit cursors and icons are stored in a global heap block, with the
31 * following layout:
33 * CURSORICONINFO info;
34 * BYTE[] ANDbits;
35 * BYTE[] XORbits;
37 * The bits structures are in the format of a device-dependent bitmap.
39 * This layout is very sub-optimal, as the bitmap bits are stored in
40 * the X client instead of in the server like other bitmaps; however,
41 * some programs (notably Paint Brush) expect to be able to manipulate
42 * the bits directly :-(
45 #include "config.h"
46 #include "wine/port.h"
48 #include <stdarg.h>
49 #include <string.h>
50 #include <stdlib.h>
52 #include "ntstatus.h"
53 #define WIN32_NO_STATUS
54 #include "windef.h"
55 #include "winbase.h"
56 #include "wingdi.h"
57 #include "winerror.h"
58 #include "wine/winbase16.h"
59 #include "wine/winuser16.h"
60 #include "wine/exception.h"
61 #include "wine/debug.h"
62 #include "wine/list.h"
63 #include "wine/server.h"
64 #include "user_private.h"
66 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
67 WINE_DECLARE_DEBUG_CHANNEL(icon);
68 WINE_DECLARE_DEBUG_CHANNEL(resource);
70 #include "pshpack1.h"
72 typedef struct {
73 BYTE bWidth;
74 BYTE bHeight;
75 BYTE bColorCount;
76 BYTE bReserved;
77 WORD xHotspot;
78 WORD yHotspot;
79 DWORD dwDIBSize;
80 DWORD dwDIBOffset;
81 } CURSORICONFILEDIRENTRY;
83 typedef struct
85 WORD idReserved;
86 WORD idType;
87 WORD idCount;
88 CURSORICONFILEDIRENTRY idEntries[1];
89 } CURSORICONFILEDIR;
91 #include "poppack.h"
93 #define CID_RESOURCE 0x0001
94 #define CID_WIN32 0x0004
95 #define CID_NONSHARED 0x0008
97 static RECT CURSOR_ClipRect; /* Cursor clipping rect */
99 static HDC screen_dc;
101 static const WCHAR DISPLAYW[] = {'D','I','S','P','L','A','Y',0};
103 /**********************************************************************
104 * ICONCACHE for cursors/icons loaded with LR_SHARED.
106 * FIXME: This should not be allocated on the system heap, but on a
107 * subsystem-global heap (i.e. one for all Win16 processes,
108 * and one for each Win32 process).
110 typedef struct tagICONCACHE
112 struct tagICONCACHE *next;
114 HMODULE hModule;
115 HRSRC hRsrc;
116 HRSRC hGroupRsrc;
117 HICON hIcon;
119 INT count;
121 } ICONCACHE;
123 static ICONCACHE *IconAnchor = NULL;
125 static CRITICAL_SECTION IconCrst;
126 static CRITICAL_SECTION_DEBUG critsect_debug =
128 0, 0, &IconCrst,
129 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
130 0, 0, { (DWORD_PTR)(__FILE__ ": IconCrst") }
132 static CRITICAL_SECTION IconCrst = { &critsect_debug, -1, 0, 0, 0, 0 };
134 static const WORD ICON_HOTSPOT = 0x4242;
136 /* What is a good table size? */
137 #define CURSOR_HASH_SIZE 97
139 typedef struct {
140 HCURSOR16 cursor16;
141 HCURSOR cursor32;
142 struct list entry16;
143 struct list entry32;
144 } cursor_map_entry_t;
146 static int get_bitmap_width_bytes( int width, int bpp );
148 static struct list cursor16to32[CURSOR_HASH_SIZE];
149 static struct list cursor32to16[CURSOR_HASH_SIZE];
151 static inline int hash_cursor_handle( DWORD handle )
153 return handle % CURSOR_HASH_SIZE;
156 static void add_cursor16to32_entry( cursor_map_entry_t *entry )
158 int idx = hash_cursor_handle( entry->cursor16 );
160 if (!cursor16to32[idx].next) list_init( &cursor16to32[idx] );
162 list_add_head( &cursor16to32[idx], &entry->entry16 );
165 static void add_cursor32to16_entry( cursor_map_entry_t *entry )
167 int idx = hash_cursor_handle( (DWORD)entry->cursor32 );
169 if (!cursor32to16[idx].next) list_init( &cursor32to16[idx] );
171 list_add_head( &cursor32to16[idx], &entry->entry32 );
174 static cursor_map_entry_t *remove_cursor16to32_entry( HCURSOR16 cursor16 )
176 cursor_map_entry_t *entry = NULL;
177 int idx = hash_cursor_handle( cursor16 );
179 if (cursor16to32[idx].next)
181 LIST_FOR_EACH_ENTRY( entry, &cursor16to32[idx], cursor_map_entry_t, entry16 )
182 if (entry->cursor16 == cursor16)
184 list_remove( &entry->entry16 );
185 return entry;
189 return entry;
192 static cursor_map_entry_t *remove_cursor32to16_entry( HCURSOR cursor32 )
194 cursor_map_entry_t *entry = NULL;
195 int idx = hash_cursor_handle( (DWORD)cursor32 );
197 if (cursor32to16[idx].next)
199 LIST_FOR_EACH_ENTRY( entry, &cursor32to16[idx], cursor_map_entry_t, entry32 )
200 if (entry->cursor32 == cursor32)
202 list_remove( &entry->entry32 );
203 return entry;
207 return entry;
210 /* Ask the server for a cursor */
211 static HCURSOR create_cursor( unsigned int num_frames, unsigned int delay )
213 HCURSOR cursor = 0;
215 SERVER_START_REQ(create_cursor)
217 req->num_frames = num_frames;
218 req->delay = delay;
219 if (!wine_server_call_err( req )) cursor = reply->handle;
221 SERVER_END_REQ;
223 return cursor;
226 /* Tell the server to kill a cursor */
227 static HCURSOR16 destroy_cursor( HCURSOR cursor )
229 cursor_map_entry_t *entry;
230 HCURSOR16 cursor16 = 0;
232 if (!cursor) return 0;
234 SERVER_START_REQ(destroy_cursor)
236 req->handle = cursor;
237 wine_server_call( req );
239 SERVER_END_REQ;
241 entry = remove_cursor32to16_entry( cursor );
242 if (entry)
244 cursor16 = entry->cursor16;
245 remove_cursor16to32_entry( cursor16 );
246 HeapFree( GetProcessHeap(), 0, entry );
249 return GlobalFree16( cursor16 );
252 /* Upload a cursor frame to the server */
253 static void set_cursor_frame( HCURSOR cursor, unsigned int frame_idx, cursor_frame_t *frame )
255 SERVER_START_REQ(set_cursor_frame)
257 req->handle = cursor;
258 req->frame_idx = frame_idx;
259 req->xhot = frame->xhot;
260 req->yhot = frame->yhot;
261 req->width = frame->width;
262 req->height = frame->height;
263 req->and_width_bytes = frame->and_width_bytes;
264 req->xor_width_bytes = frame->xor_width_bytes;
265 req->planes = frame->planes;
266 req->bpp = frame->bpp;
267 wine_server_add_data( req, frame->bits, (frame->and_width_bytes + frame->xor_width_bytes) * frame->height );
268 wine_server_call( req );
270 SERVER_END_REQ;
273 /* Download a cursor frame from the server */
274 static BOOL get_cursor_frame( HCURSOR cursor, unsigned int frame_idx, cursor_frame_t *frame )
276 NTSTATUS res;
277 /* Enough for a 32-bits 32x32 cursor / icon. */
278 unsigned int buffer_size = 4224;
279 unsigned int count = 0;
283 frame->bits = HeapAlloc(GetProcessHeap(), 0, buffer_size);
284 SERVER_START_REQ(get_cursor_frame)
286 req->handle = cursor;
287 req->frame_idx = frame_idx;
288 wine_server_set_reply( req, frame->bits, buffer_size);
289 if (!(res = wine_server_call_err( req )))
291 frame->xhot = reply->xhot;
292 frame->yhot = reply->yhot;
293 frame->width = reply->width;
294 frame->height = reply->height;
295 frame->and_width_bytes = reply->and_width_bytes;
296 frame->xor_width_bytes = reply->xor_width_bytes;
297 frame->planes = reply->planes;
298 frame->bpp = reply->bpp;
299 } else {
300 HeapFree( GetProcessHeap(), 0, frame->bits );
301 buffer_size = (reply->and_width_bytes + reply->xor_width_bytes) * reply->height;
304 SERVER_END_REQ;
305 } while (res == STATUS_BUFFER_OVERFLOW && !count++);
307 if (!frame->height)
309 HeapFree( GetProcessHeap(), 0, frame->bits );
311 return FALSE;
314 return TRUE;
317 /* Retrieve a cursor and all its frames from the server */
318 static cursor_t *get_cursor_object( HCURSOR handle )
320 unsigned int i;
321 cursor_t *cursor = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(cursor_t) );
323 SERVER_START_REQ(get_cursor_info)
325 req->handle = handle;
326 if (!wine_server_call_err( req ))
328 cursor->num_frames = reply->num_frames;
329 cursor->delay = reply->delay;
332 SERVER_END_REQ;
334 if (!cursor->num_frames)
336 HeapFree( GetProcessHeap(), 0, cursor );
337 return NULL;
340 cursor->frames = HeapAlloc( GetProcessHeap(), 0, cursor->num_frames * sizeof(cursor_frame_t) );
341 for (i = 0; i < cursor->num_frames; ++i)
343 if (!get_cursor_frame( handle, i, &cursor->frames[i] ))
345 unsigned int j;
347 for (j = 0; j < i; ++j)
349 HeapFree( GetProcessHeap(), 0, cursor->frames[j].bits );
351 HeapFree( GetProcessHeap(), 0, cursor->frames );
352 HeapFree( GetProcessHeap(), 0, cursor );
354 return NULL;
358 return cursor;
361 static void destroy_cursor_object( cursor_t *cursor )
363 unsigned int i;
365 if (!cursor) return;
367 for (i = 0; i < cursor->num_frames; ++i)
369 HeapFree( GetProcessHeap(), 0, cursor->frames[i].bits );
371 HeapFree( GetProcessHeap(), 0, cursor->frames );
372 HeapFree( GetProcessHeap(), 0, cursor );
375 /* Lookup the cursor's 16-bit handle. Create one if it doesn't already exist. */
376 HCURSOR16 get_cursor_handle16( HCURSOR cursor32, BOOL create )
378 cursor_map_entry_t *entry;
379 int idx = hash_cursor_handle( (DWORD)cursor32 );
381 if (!cursor32) return 0;
383 if (cursor32to16[idx].next)
385 LIST_FOR_EACH_ENTRY( entry, &cursor32to16[idx], cursor_map_entry_t, entry32 )
386 if (entry->cursor32 == cursor32) return entry->cursor16;
389 /* 16-bit cursor handle not found, create one */
390 if (create)
392 size_t bits_size;
393 HCURSOR16 cursor16;
394 cursor_frame_t frame;
396 if (!get_cursor_frame( cursor32, 0, &frame )) return 0;
398 entry = HeapAlloc( GetProcessHeap(), 0, sizeof(cursor_map_entry_t) );
399 bits_size = (frame.and_width_bytes + frame.xor_width_bytes) * frame.height;
400 cursor16 = GlobalAlloc16( GMEM_MOVEABLE, sizeof(CURSORICONINFO) + bits_size );
401 if (cursor16)
403 CURSORICONINFO *info;
405 info = (CURSORICONINFO *)GlobalLock16( cursor16 );
406 info->ptHotSpot.x = frame.xhot;
407 info->ptHotSpot.y = frame.yhot;
408 info->nWidth = frame.width;
409 info->nHeight = frame.height;
410 info->nWidthBytes = frame.xor_width_bytes;
411 info->bPlanes = frame.planes;
412 info->bBitsPerPixel = frame.bpp;
413 CopyMemory( info + 1, frame.bits, bits_size );
414 GlobalUnlock16( cursor16 );
416 HeapFree( GetProcessHeap(), 0, frame.bits );
418 entry->cursor16 = cursor16;
419 entry->cursor32 = cursor32;
420 add_cursor16to32_entry( entry );
421 add_cursor32to16_entry( entry );
423 return cursor16;
426 return 0;
429 HCURSOR get_cursor_handle32( HCURSOR16 cursor16 )
431 cursor_map_entry_t *entry;
432 int idx = hash_cursor_handle( cursor16 );
434 if (!cursor16) return 0;
436 if (cursor16to32[idx].next)
438 LIST_FOR_EACH_ENTRY( entry, &cursor16to32[idx], cursor_map_entry_t, entry16 )
439 if (entry->cursor16 == cursor16) return entry->cursor32;
442 return 0;
445 static void update_cursor_32from16( HCURSOR cursor32 )
447 size_t bits_size;
448 HCURSOR16 cursor16;
449 cursor_frame_t frame;
450 CURSORICONINFO *info;
452 if (!cursor32) return;
454 cursor16 = get_cursor_handle16( cursor32, FALSE );
455 if (!cursor16) return;
457 info = (CURSORICONINFO *)GlobalLock16( cursor16 );
458 frame.xhot = info->ptHotSpot.x;
459 frame.yhot = info->ptHotSpot.y;
460 frame.width = info->nWidth;
461 frame.height = info->nHeight;
462 frame.and_width_bytes = get_bitmap_width_bytes( info->nWidth, 1 );
463 frame.xor_width_bytes = info->nWidthBytes;
464 frame.planes = info->bPlanes;
465 frame.bpp = info->bBitsPerPixel;
466 bits_size = (frame.and_width_bytes + frame.xor_width_bytes) * frame.height;
467 frame.bits = HeapAlloc( GetProcessHeap(), 0, bits_size );
468 CopyMemory( frame.bits, info + 1, bits_size );
469 GlobalUnlock16( cursor16 );
471 set_cursor_frame( cursor32, 0, &frame );
472 HeapFree( GetProcessHeap(), 0, frame.bits );
475 /***********************************************************************
476 * map_fileW
478 * Helper function to map a file to memory:
479 * name - file name
480 * [RETURN] ptr - pointer to mapped file
481 * [RETURN] filesize - pointer size of file to be stored if not NULL
483 static void *map_fileW( LPCWSTR name, LPDWORD filesize )
485 HANDLE hFile, hMapping;
486 LPVOID ptr = NULL;
488 hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
489 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
490 if (hFile != INVALID_HANDLE_VALUE)
492 hMapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
493 if (hMapping)
495 ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
496 CloseHandle( hMapping );
497 if (filesize)
498 *filesize = GetFileSize( hFile, NULL );
500 CloseHandle( hFile );
502 return ptr;
506 /***********************************************************************
507 * get_bitmap_width_bytes
509 * Return number of bytes taken by a scanline of 16-bit aligned Windows DDB
510 * data.
512 static int get_bitmap_width_bytes( int width, int bpp )
514 switch(bpp)
516 case 1:
517 return 2 * ((width+15) / 16);
518 case 4:
519 return 2 * ((width+3) / 4);
520 case 24:
521 width *= 3;
522 /* fall through */
523 case 8:
524 return width + (width & 1);
525 case 16:
526 case 15:
527 return width * 2;
528 case 32:
529 return width * 4;
530 default:
531 WARN("Unknown depth %d, please report.\n", bpp );
533 return -1;
537 /***********************************************************************
538 * get_dib_width_bytes
540 * Return the width of a DIB bitmap in bytes. DIB bitmap data is 32-bit aligned.
542 static int get_dib_width_bytes( int width, int depth )
544 int words;
546 switch(depth)
548 case 1: words = (width + 31) / 32; break;
549 case 4: words = (width + 7) / 8; break;
550 case 8: words = (width + 3) / 4; break;
551 case 15:
552 case 16: words = (width + 1) / 2; break;
553 case 24: words = (width * 3 + 3)/4; break;
554 default:
555 WARN("(%d): Unsupported depth\n", depth );
556 /* fall through */
557 case 32:
558 words = width;
560 return 4 * words;
564 /***********************************************************************
565 * bitmap_info_size
567 * Return the size of the bitmap info structure including color table.
569 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
571 int colors, masks = 0;
573 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
575 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
576 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
577 return sizeof(BITMAPCOREHEADER) + colors *
578 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
580 else /* assume BITMAPINFOHEADER */
582 colors = info->bmiHeader.biClrUsed;
583 if (colors > 256) /* buffer overflow otherwise */
584 colors = 256;
585 if (!colors && (info->bmiHeader.biBitCount <= 8))
586 colors = 1 << info->bmiHeader.biBitCount;
587 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
588 return sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) + colors *
589 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
594 /***********************************************************************
595 * is_dib_monochrome
597 * Returns whether a DIB can be converted to a monochrome DDB.
599 * A DIB can be converted if its color table contains only black and
600 * white. Black must be the first color in the color table.
602 * Note : If the first color in the color table is white followed by
603 * black, we can't convert it to a monochrome DDB with
604 * SetDIBits, because black and white would be inverted.
606 static BOOL is_dib_monochrome( const BITMAPINFO* info )
608 if (info->bmiHeader.biBitCount != 1) return FALSE;
610 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
612 const RGBTRIPLE *rgb = ((const BITMAPCOREINFO*)info)->bmciColors;
614 /* Check if the first color is black */
615 if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
617 rgb++;
619 /* Check if the second color is white */
620 return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
621 && (rgb->rgbtBlue == 0xff));
623 else return FALSE;
625 else /* assume BITMAPINFOHEADER */
627 const RGBQUAD *rgb = info->bmiColors;
629 /* Check if the first color is black */
630 if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
631 (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
633 rgb++;
635 /* Check if the second color is white */
636 return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
637 && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
639 else return FALSE;
643 /***********************************************************************
644 * DIB_GetBitmapInfo
646 * Get the info from a bitmap header.
647 * Return 1 for INFOHEADER, 0 for COREHEADER,
648 * 4 for V4HEADER, 5 for V5HEADER, -1 for error.
650 static int DIB_GetBitmapInfo( const BITMAPINFOHEADER *header, LONG *width,
651 LONG *height, WORD *bpp, DWORD *compr )
653 if (header->biSize == sizeof(BITMAPINFOHEADER))
655 *width = header->biWidth;
656 *height = header->biHeight;
657 *bpp = header->biBitCount;
658 *compr = header->biCompression;
659 return 1;
661 if (header->biSize == sizeof(BITMAPCOREHEADER))
663 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)header;
664 *width = core->bcWidth;
665 *height = core->bcHeight;
666 *bpp = core->bcBitCount;
667 *compr = 0;
668 return 0;
670 if (header->biSize == sizeof(BITMAPV4HEADER))
672 const BITMAPV4HEADER *v4hdr = (const BITMAPV4HEADER *)header;
673 *width = v4hdr->bV4Width;
674 *height = v4hdr->bV4Height;
675 *bpp = v4hdr->bV4BitCount;
676 *compr = v4hdr->bV4V4Compression;
677 return 4;
679 if (header->biSize == sizeof(BITMAPV5HEADER))
681 const BITMAPV5HEADER *v5hdr = (const BITMAPV5HEADER *)header;
682 *width = v5hdr->bV5Width;
683 *height = v5hdr->bV5Height;
684 *bpp = v5hdr->bV5BitCount;
685 *compr = v5hdr->bV5Compression;
686 return 5;
688 ERR("(%d): unknown/wrong size for header\n", header->biSize );
689 return -1;
692 /**********************************************************************
693 * CURSORICON_FindSharedIcon
695 static HICON CURSORICON_FindSharedIcon( HMODULE hModule, HRSRC hRsrc )
697 HICON hIcon = 0;
698 ICONCACHE *ptr;
700 EnterCriticalSection( &IconCrst );
702 for ( ptr = IconAnchor; ptr; ptr = ptr->next )
703 if ( ptr->hModule == hModule && ptr->hRsrc == hRsrc )
705 ptr->count++;
706 hIcon = ptr->hIcon;
707 break;
710 LeaveCriticalSection( &IconCrst );
712 return hIcon;
715 /*************************************************************************
716 * CURSORICON_FindCache
718 * Given a handle, find the corresponding cache element
720 * PARAMS
721 * Handle [I] handle to an Image
723 * RETURNS
724 * Success: The cache entry
725 * Failure: NULL
728 static ICONCACHE* CURSORICON_FindCache(HICON hIcon)
730 ICONCACHE *ptr;
731 ICONCACHE *pRet=NULL;
732 BOOL IsFound = FALSE;
734 EnterCriticalSection( &IconCrst );
736 for (ptr = IconAnchor; ptr != NULL && !IsFound; ptr = ptr->next)
738 if ( hIcon == ptr->hIcon )
740 IsFound = TRUE;
741 pRet = ptr;
745 LeaveCriticalSection( &IconCrst );
747 return pRet;
750 /**********************************************************************
751 * CURSORICON_AddSharedIcon
753 static void CURSORICON_AddSharedIcon( HMODULE hModule, HRSRC hRsrc, HRSRC hGroupRsrc, HICON hIcon )
755 ICONCACHE *ptr = HeapAlloc( GetProcessHeap(), 0, sizeof(ICONCACHE) );
756 if ( !ptr ) return;
758 ptr->hModule = hModule;
759 ptr->hRsrc = hRsrc;
760 ptr->hIcon = hIcon;
761 ptr->hGroupRsrc = hGroupRsrc;
762 ptr->count = 1;
764 EnterCriticalSection( &IconCrst );
765 ptr->next = IconAnchor;
766 IconAnchor = ptr;
767 LeaveCriticalSection( &IconCrst );
770 /**********************************************************************
771 * CURSORICON_DelSharedIcon
773 static INT CURSORICON_DelSharedIcon( HICON hIcon )
775 INT count = -1;
776 ICONCACHE *ptr;
778 EnterCriticalSection( &IconCrst );
780 for ( ptr = IconAnchor; ptr; ptr = ptr->next )
781 if ( ptr->hIcon == hIcon )
783 if ( ptr->count > 0 ) ptr->count--;
784 count = ptr->count;
785 break;
788 LeaveCriticalSection( &IconCrst );
790 return count;
793 /**********************************************************************
794 * CURSORICON_FreeModuleIcons
796 void CURSORICON_FreeModuleIcons( HMODULE16 hMod16 )
798 ICONCACHE **ptr = &IconAnchor;
799 HMODULE hModule = HMODULE_32(GetExePtr( hMod16 ));
801 EnterCriticalSection( &IconCrst );
803 while ( *ptr )
805 if ( (*ptr)->hModule == hModule )
807 ICONCACHE *freePtr = *ptr;
808 *ptr = freePtr->next;
810 destroy_cursor( freePtr->hIcon );
811 HeapFree( GetProcessHeap(), 0, freePtr );
812 continue;
814 ptr = &(*ptr)->next;
817 LeaveCriticalSection( &IconCrst );
821 * The following macro functions account for the irregularities of
822 * accessing cursor and icon resources in files and resource entries.
824 typedef BOOL (*fnGetCIEntry)( LPVOID dir, int n,
825 int *width, int *height, int *bits );
827 /**********************************************************************
828 * CURSORICON_FindBestIcon
830 * Find the icon closest to the requested size and number of colors.
832 static int CURSORICON_FindBestIcon( LPVOID dir, fnGetCIEntry get_entry,
833 int width, int height, int colors )
835 int i, cx, cy, bits, bestEntry = -1;
836 UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
837 UINT iTempXDiff, iTempYDiff, iTempColorDiff;
839 /* Find Best Fit */
840 iTotalDiff = 0xFFFFFFFF;
841 iColorDiff = 0xFFFFFFFF;
842 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
844 iTempXDiff = abs(width - cx);
845 iTempYDiff = abs(height - cy);
847 if(iTotalDiff > (iTempXDiff + iTempYDiff))
849 iXDiff = iTempXDiff;
850 iYDiff = iTempYDiff;
851 iTotalDiff = iXDiff + iYDiff;
855 /* Find Best Colors for Best Fit */
856 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
858 if(abs(width - cx) == iXDiff && abs(height - cy) == iYDiff)
860 iTempColorDiff = abs(colors - (1<<bits));
861 if(iColorDiff > iTempColorDiff)
863 bestEntry = i;
864 iColorDiff = iTempColorDiff;
869 return bestEntry;
872 static BOOL CURSORICON_GetResIconEntry( LPVOID dir, int n,
873 int *width, int *height, int *bits )
875 CURSORICONDIR *resdir = dir;
876 ICONRESDIR *icon;
878 if ( resdir->idCount <= n )
879 return FALSE;
880 icon = &resdir->idEntries[n].ResInfo.icon;
881 *width = icon->bWidth;
882 *height = icon->bHeight;
883 *bits = resdir->idEntries[n].wBitCount;
884 return TRUE;
887 /**********************************************************************
888 * CURSORICON_FindBestCursor
890 * Find the cursor closest to the requested size.
891 * FIXME: parameter 'color' ignored and entries with more than 1 bpp
892 * ignored too
894 static int CURSORICON_FindBestCursor( LPVOID dir, fnGetCIEntry get_entry,
895 int width, int height, int color )
897 int i, maxwidth, maxheight, cx, cy, bits, bestEntry = -1;
899 /* Double height to account for AND and XOR masks */
901 height *= 2;
903 /* First find the largest one smaller than or equal to the requested size*/
905 maxwidth = maxheight = 0;
906 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
908 if ((cx <= width) && (cy <= height) &&
909 (cx > maxwidth) && (cy > maxheight) &&
910 (bits == 1))
912 bestEntry = i;
913 maxwidth = cx;
914 maxheight = cy;
917 if (bestEntry != -1) return bestEntry;
919 /* Now find the smallest one larger than the requested size */
921 maxwidth = maxheight = 255;
922 for ( i = 0; get_entry( dir, i, &cx, &cy, &bits ); i++ )
924 if (((cx < maxwidth) && (cy < maxheight) && (bits == 1)) ||
925 (bestEntry==-1))
927 bestEntry = i;
928 maxwidth = cx;
929 maxheight = cy;
933 return bestEntry;
936 static BOOL CURSORICON_GetResCursorEntry( LPVOID dir, int n,
937 int *width, int *height, int *bits )
939 CURSORICONDIR *resdir = dir;
940 CURSORDIR *cursor;
942 if ( resdir->idCount <= n )
943 return FALSE;
944 cursor = &resdir->idEntries[n].ResInfo.cursor;
945 *width = cursor->wWidth;
946 *height = cursor->wHeight;
947 *bits = resdir->idEntries[n].wBitCount;
948 return TRUE;
951 static CURSORICONDIRENTRY *CURSORICON_FindBestIconRes( CURSORICONDIR * dir,
952 int width, int height, int colors )
954 int n;
956 n = CURSORICON_FindBestIcon( dir, CURSORICON_GetResIconEntry,
957 width, height, colors );
958 if ( n < 0 )
959 return NULL;
960 return &dir->idEntries[n];
963 static CURSORICONDIRENTRY *CURSORICON_FindBestCursorRes( CURSORICONDIR *dir,
964 int width, int height, int color )
966 int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetResCursorEntry,
967 width, height, color );
968 if ( n < 0 )
969 return NULL;
970 return &dir->idEntries[n];
973 static BOOL CURSORICON_GetFileEntry( LPVOID dir, int n,
974 int *width, int *height, int *bits )
976 CURSORICONFILEDIR *filedir = dir;
977 CURSORICONFILEDIRENTRY *entry;
979 if ( filedir->idCount <= n )
980 return FALSE;
981 entry = &filedir->idEntries[n];
982 *width = entry->bWidth;
983 *height = entry->bHeight;
984 *bits = entry->bColorCount;
985 return TRUE;
988 static CURSORICONFILEDIRENTRY *CURSORICON_FindBestCursorFile( CURSORICONFILEDIR *dir,
989 int width, int height, int color )
991 int n = CURSORICON_FindBestCursor( dir, CURSORICON_GetFileEntry,
992 width, height, color );
993 if ( n < 0 )
994 return NULL;
995 return &dir->idEntries[n];
998 static CURSORICONFILEDIRENTRY *CURSORICON_FindBestIconFile( CURSORICONFILEDIR *dir,
999 int width, int height, int color )
1001 int n = CURSORICON_FindBestIcon( dir, CURSORICON_GetFileEntry,
1002 width, height, color );
1003 if ( n < 0 )
1004 return NULL;
1005 return &dir->idEntries[n];
1008 static BOOL load_cursor_frame( LPBYTE bits, UINT cbSize, POINT16 hotspot, DWORD dwVersion,
1009 INT width, INT height, UINT cFlag, cursor_frame_t *frame )
1011 static HDC hdcMem;
1012 int sizeAnd, sizeXor;
1013 HBITMAP hAndBits = 0, hXorBits = 0; /* error condition for later */
1014 BITMAP bmpXor, bmpAnd;
1015 BITMAPINFO *bmi;
1016 BOOL DoStretch;
1017 INT size;
1019 TRACE_(cursor)("%p (%u bytes), ver %08x, %ix%i %s\n",
1020 bits, cbSize, dwVersion, width, height,
1021 (cFlag & LR_MONOCHROME) ? "mono" : "" );
1022 if (dwVersion == 0x00020000)
1024 FIXME_(cursor)("\t2.xx resources are not supported\n");
1025 return FALSE;
1028 bmi = (BITMAPINFO *)bits;
1030 /* Check bitmap header */
1032 if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
1033 (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER) ||
1034 bmi->bmiHeader.biCompression != BI_RGB) )
1036 WARN_(cursor)("\tinvalid resource bitmap header.\n");
1037 return FALSE;
1040 size = bitmap_info_size( bmi, DIB_RGB_COLORS );
1042 if (!width) width = bmi->bmiHeader.biWidth;
1043 if (!height) height = bmi->bmiHeader.biHeight/2;
1044 DoStretch = (bmi->bmiHeader.biHeight/2 != height) ||
1045 (bmi->bmiHeader.biWidth != width);
1047 /* Scale the hotspot */
1048 if (DoStretch && hotspot.x != ICON_HOTSPOT && hotspot.y != ICON_HOTSPOT)
1050 hotspot.x = (hotspot.x * width) / bmi->bmiHeader.biWidth;
1051 hotspot.y = (hotspot.y * height) / (bmi->bmiHeader.biWidth / 2);
1054 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
1055 if (screen_dc)
1057 BITMAPINFO* pInfo;
1059 /* Make sure we have room for the monochrome bitmap later on.
1060 * Note that BITMAPINFOINFO and BITMAPCOREHEADER are the same
1061 * up to and including the biBitCount. In-memory icon resource
1062 * format is as follows:
1064 * BITMAPINFOHEADER icHeader // DIB header
1065 * RGBQUAD icColors[] // Color table
1066 * BYTE icXOR[] // DIB bits for XOR mask
1067 * BYTE icAND[] // DIB bits for AND mask
1070 if ((pInfo = HeapAlloc( GetProcessHeap(), 0,
1071 max(size, sizeof(BITMAPINFOHEADER) + 2*sizeof(RGBQUAD)))))
1073 memcpy( pInfo, bmi, size );
1074 pInfo->bmiHeader.biHeight /= 2;
1076 /* Create the XOR bitmap */
1078 if (DoStretch) {
1079 hXorBits = CreateCompatibleBitmap(screen_dc, width, height);
1080 if(hXorBits)
1082 HBITMAP hOld;
1083 BOOL res = FALSE;
1085 if (!hdcMem) hdcMem = CreateCompatibleDC(screen_dc);
1086 if (hdcMem) {
1087 hOld = SelectObject(hdcMem, hXorBits);
1088 res = StretchDIBits(hdcMem, 0, 0, width, height, 0, 0,
1089 bmi->bmiHeader.biWidth, bmi->bmiHeader.biHeight/2,
1090 (char*)bmi + size, pInfo, DIB_RGB_COLORS, SRCCOPY);
1091 SelectObject(hdcMem, hOld);
1093 if (!res) { DeleteObject(hXorBits); hXorBits = 0; }
1095 } else {
1096 if (is_dib_monochrome(bmi)) {
1097 hXorBits = CreateBitmap(width, height, 1, 1, NULL);
1098 SetDIBits(screen_dc, hXorBits, 0, height,
1099 (char*)bmi + size, pInfo, DIB_RGB_COLORS);
1101 else
1102 hXorBits = CreateDIBitmap(screen_dc, &pInfo->bmiHeader,
1103 CBM_INIT, (char*)bmi + size, pInfo, DIB_RGB_COLORS);
1106 if( hXorBits )
1108 char* xbits = (char *)bmi + size +
1109 get_dib_width_bytes( bmi->bmiHeader.biWidth,
1110 bmi->bmiHeader.biBitCount ) * abs( bmi->bmiHeader.biHeight ) / 2;
1112 pInfo->bmiHeader.biBitCount = 1;
1113 if (pInfo->bmiHeader.biSize != sizeof(BITMAPCOREHEADER))
1115 RGBQUAD *rgb = pInfo->bmiColors;
1117 pInfo->bmiHeader.biClrUsed = pInfo->bmiHeader.biClrImportant = 2;
1118 rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
1119 rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
1120 rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
1122 else
1124 RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)pInfo) + 1);
1126 rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
1127 rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
1130 /* Create the AND bitmap */
1132 if (DoStretch) {
1133 if ((hAndBits = CreateBitmap(width, height, 1, 1, NULL))) {
1134 HBITMAP hOld;
1135 BOOL res = FALSE;
1137 if (!hdcMem) hdcMem = CreateCompatibleDC(screen_dc);
1138 if (hdcMem) {
1139 hOld = SelectObject(hdcMem, hAndBits);
1140 res = StretchDIBits(hdcMem, 0, 0, width, height, 0, 0,
1141 pInfo->bmiHeader.biWidth, pInfo->bmiHeader.biHeight,
1142 xbits, pInfo, DIB_RGB_COLORS, SRCCOPY);
1143 SelectObject(hdcMem, hOld);
1145 if (!res) { DeleteObject(hAndBits); hAndBits = 0; }
1147 } else {
1148 hAndBits = CreateBitmap(width, height, 1, 1, NULL);
1150 if (hAndBits) SetDIBits(screen_dc, hAndBits, 0, height,
1151 xbits, pInfo, DIB_RGB_COLORS);
1154 if( !hAndBits ) DeleteObject( hXorBits );
1156 HeapFree( GetProcessHeap(), 0, pInfo );
1160 if( !hXorBits || !hAndBits )
1162 WARN_(cursor)("\tunable to create an icon bitmap.\n");
1163 return FALSE;
1166 /* Setup a cursor frame, send it to the server */
1167 GetObjectA( hXorBits, sizeof(bmpXor), &bmpXor );
1168 GetObjectA( hAndBits, sizeof(bmpAnd), &bmpAnd );
1169 sizeXor = bmpXor.bmHeight * bmpXor.bmWidthBytes;
1170 sizeAnd = bmpAnd.bmHeight * bmpAnd.bmWidthBytes;
1172 frame->xhot = hotspot.x;
1173 frame->yhot = hotspot.y;
1174 frame->width = bmpXor.bmWidth;
1175 frame->height = bmpXor.bmHeight;
1176 frame->and_width_bytes = bmpAnd.bmWidthBytes;
1177 frame->xor_width_bytes = bmpXor.bmWidthBytes;
1178 frame->planes = bmpXor.bmPlanes;
1179 frame->bpp = bmpXor.bmBitsPixel;
1180 frame->bits = HeapAlloc( GetProcessHeap(), 0, sizeAnd + sizeXor );
1181 GetBitmapBits( hAndBits, sizeAnd, frame->bits );
1182 GetBitmapBits( hXorBits, sizeXor, frame->bits + sizeAnd );
1184 DeleteObject( hAndBits );
1185 DeleteObject( hXorBits );
1187 return TRUE;
1190 /**********************************************************************
1191 * .ANI cursor support
1193 #define RIFF_FOURCC( c0, c1, c2, c3 ) \
1194 ( (DWORD)(BYTE)(c0) | ( (DWORD)(BYTE)(c1) << 8 ) | \
1195 ( (DWORD)(BYTE)(c2) << 16 ) | ( (DWORD)(BYTE)(c3) << 24 ) )
1197 #define ANI_RIFF_ID RIFF_FOURCC('R', 'I', 'F', 'F')
1198 #define ANI_LIST_ID RIFF_FOURCC('L', 'I', 'S', 'T')
1199 #define ANI_ACON_ID RIFF_FOURCC('A', 'C', 'O', 'N')
1200 #define ANI_anih_ID RIFF_FOURCC('a', 'n', 'i', 'h')
1201 #define ANI_seq__ID RIFF_FOURCC('s', 'e', 'q', ' ')
1202 #define ANI_fram_ID RIFF_FOURCC('f', 'r', 'a', 'm')
1204 #define ANI_FLAG_ICON 0x1
1205 #define ANI_FLAG_SEQUENCE 0x2
1207 typedef struct {
1208 DWORD header_size;
1209 DWORD num_frames;
1210 DWORD num_steps;
1211 DWORD width;
1212 DWORD height;
1213 DWORD bpp;
1214 DWORD num_planes;
1215 DWORD display_rate;
1216 DWORD flags;
1217 } ani_header;
1219 typedef struct {
1220 DWORD data_size;
1221 const unsigned char *data;
1222 } riff_chunk_t;
1224 static void dump_ani_header( const ani_header *header )
1226 TRACE(" header size: %d\n", header->header_size);
1227 TRACE(" frames: %d\n", header->num_frames);
1228 TRACE(" steps: %d\n", header->num_steps);
1229 TRACE(" width: %d\n", header->width);
1230 TRACE(" height: %d\n", header->height);
1231 TRACE(" bpp: %d\n", header->bpp);
1232 TRACE(" planes: %d\n", header->num_planes);
1233 TRACE(" display rate: %d\n", header->display_rate);
1234 TRACE(" flags: 0x%08x\n", header->flags);
1239 * RIFF:
1240 * DWORD "RIFF"
1241 * DWORD size
1242 * DWORD riff_id
1243 * BYTE[] data
1245 * LIST:
1246 * DWORD "LIST"
1247 * DWORD size
1248 * DWORD list_id
1249 * BYTE[] data
1251 * CHUNK:
1252 * DWORD chunk_id
1253 * DWORD size
1254 * BYTE[] data
1256 static void riff_find_chunk( DWORD chunk_id, DWORD chunk_type, const riff_chunk_t *parent_chunk, riff_chunk_t *chunk )
1258 const unsigned char *ptr = parent_chunk->data;
1259 const unsigned char *end = parent_chunk->data + (parent_chunk->data_size - (2 * sizeof(DWORD)));
1261 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) end -= sizeof(DWORD);
1263 while (ptr < end)
1265 if ((!chunk_type && *(DWORD *)ptr == chunk_id )
1266 || (chunk_type && *(DWORD *)ptr == chunk_type && *((DWORD *)ptr + 2) == chunk_id ))
1268 ptr += sizeof(DWORD);
1269 chunk->data_size = *(DWORD *)ptr;
1270 ptr += sizeof(DWORD);
1271 if (chunk_type == ANI_LIST_ID || chunk_type == ANI_RIFF_ID) ptr += sizeof(DWORD);
1272 chunk->data = ptr;
1274 return;
1277 ptr += sizeof(DWORD);
1278 ptr += *(DWORD *)ptr;
1279 ptr += sizeof(DWORD);
1285 * .ANI layout:
1287 * RIFF:'ACON' RIFF chunk
1288 * |- CHUNK:'anih' Header
1289 * |- CHUNK:'seq ' Sequence information (optional)
1290 * \- LIST:'fram' Frame list
1291 * |- CHUNK:icon Cursor frames
1292 * |- CHUNK:icon
1293 * |- ...
1294 * \- CHUNK:icon
1296 static HCURSOR load_ani( const LPBYTE bits, DWORD bits_size, INT width, INT height )
1298 int i;
1299 WORD max_count = 0;
1300 HCURSOR cursor;
1301 CURSORICONFILEDIR *dir = 0;
1302 ani_header header = {0};
1303 DWORD *frame_seq = 0;
1304 cursor_frame_t *frames;
1305 unsigned int frame_bits_size = 0;
1306 LPBYTE frame_bits = 0;
1307 POINT16 hotspot;
1309 riff_chunk_t root_chunk = { bits_size, bits };
1310 riff_chunk_t ACON_chunk = {0};
1311 riff_chunk_t anih_chunk = {0};
1312 riff_chunk_t fram_chunk = {0};
1313 const unsigned char *icon_chunk;
1314 const unsigned char *icon_data;
1316 TRACE("bits %p, bits_size %d\n", bits, bits_size);
1318 if (!bits) return 0;
1320 riff_find_chunk( ANI_ACON_ID, ANI_RIFF_ID, &root_chunk, &ACON_chunk );
1321 if (!ACON_chunk.data)
1323 ERR("Failed to get root chunk.\n");
1324 return 0;
1327 riff_find_chunk( ANI_anih_ID, 0, &ACON_chunk, &anih_chunk );
1328 if (!anih_chunk.data)
1330 ERR("Failed to get 'anih' chunk.\n");
1331 return 0;
1333 memcpy( &header, anih_chunk.data, sizeof(header) );
1334 dump_ani_header( &header );
1336 if (header.flags & ANI_FLAG_SEQUENCE)
1338 riff_chunk_t seq_chunk = {0};
1340 TRACE("Loading sequence data.\n");
1341 riff_find_chunk( ANI_seq__ID, 0, &ACON_chunk, &seq_chunk );
1342 if (!seq_chunk.data)
1344 ERR("Failed to get 'seq ' chunk\n");
1345 return 0;
1347 frame_seq = HeapAlloc( GetProcessHeap(), 0, sizeof(DWORD) * header.num_steps );
1348 memcpy( frame_seq, seq_chunk.data, sizeof(DWORD) * header.num_steps );
1351 riff_find_chunk( ANI_fram_ID, ANI_LIST_ID, &ACON_chunk, &fram_chunk );
1352 if (!fram_chunk.data)
1354 ERR("Failed to get icon list\n");
1355 return 0;
1358 icon_chunk = fram_chunk.data;
1359 icon_data = icon_chunk + (2 * sizeof(DWORD));
1360 /* The .ANI stores the display rate in 1/60s, we store the delay between frames in ms */
1361 cursor = create_cursor( header.num_steps, (100 * header.display_rate) / 6 );
1362 frames = HeapAlloc( GetProcessHeap(), 0, header.num_frames * sizeof(cursor_frame_t) );
1364 for (i = 0; i < header.num_frames; ++i)
1366 WORD count;
1367 CURSORICONFILEDIRENTRY *entry;
1368 DWORD chunk_size = *(DWORD *)(icon_chunk + sizeof(DWORD));
1370 /* Read icon count, skip magic */
1371 memcpy( &count, icon_data + sizeof(DWORD), sizeof(WORD) );
1373 /* There's a decent chance the amount of entries will be the same for each icon */
1374 if (count > max_count)
1376 HeapFree( GetProcessHeap(), 0, dir );
1377 /* sizeof(CURSORICONFILEDIRENTRY) for each entry, +6 for magic & count */
1378 dir = HeapAlloc( GetProcessHeap(), 0, (count * sizeof(CURSORICONFILEDIRENTRY)) + 6 );
1379 max_count = count;
1382 /* sizeof(CURSORICONFILEDIRENTRY) for each entry, +6 for magic & count */
1383 memcpy( dir, icon_data, (count * sizeof(CURSORICONFILEDIRENTRY)) + 6 );
1384 entry = CURSORICON_FindBestCursorFile( dir, width, height, 1 );
1386 if (frame_bits_size < entry->dwDIBSize)
1388 frame_bits_size = entry->dwDIBSize;
1389 HeapFree( GetProcessHeap(), 0, frame_bits );
1390 frame_bits = HeapAlloc( GetProcessHeap(), 0, frame_bits_size );
1393 if (!header.width || !header.height)
1395 header.width = entry->bWidth;
1396 header.height = entry->bHeight;
1399 hotspot.x = entry->xHotspot;
1400 hotspot.y = entry->yHotspot;
1402 memcpy( frame_bits, icon_data + entry->dwDIBOffset, entry->dwDIBSize );
1404 load_cursor_frame( frame_bits, entry->dwDIBSize, hotspot, 0x00030000, header.width, header.height, 0, &frames[i] );
1406 /* Advance to the next chunk */
1407 icon_chunk += chunk_size + (2 * sizeof(DWORD));
1408 icon_data = icon_chunk + (2 * sizeof(DWORD));
1410 HeapFree( GetProcessHeap(), 0, dir );
1412 /* Set the frames in the correct sequence */
1413 for (i = 0; i < header.num_steps; ++i)
1415 int frame_idx = (frame_seq ? frame_seq[i] : i);
1416 set_cursor_frame( cursor, i, &frames[frame_idx] );
1419 /* Cleanup */
1420 for (i = 0; i < header.num_frames; ++i)
1422 HeapFree( GetProcessHeap(), 0, frames[i].bits );
1424 HeapFree( GetProcessHeap(), 0, frame_seq );
1425 HeapFree( GetProcessHeap(), 0, frames );
1427 return cursor;
1431 /**********************************************************************
1432 * CreateIconFromResourceEx (USER32.@)
1434 * FIXME: Convert to mono when cFlag is LR_MONOCHROME. Do something
1435 * with cbSize parameter as well.
1437 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
1438 BOOL bIcon, DWORD dwVersion,
1439 INT width, INT height,
1440 UINT cFlag )
1442 POINT16 hotspot;
1443 HCURSOR cursor = create_cursor( 1, 0 );
1444 cursor_frame_t frame = {0};
1446 if (bIcon)
1448 hotspot.x = ICON_HOTSPOT;
1449 hotspot.y = ICON_HOTSPOT;
1451 else
1453 hotspot = *(POINT16 *)bits;
1454 bits = (LPBYTE)(((POINT16 *)bits) + 1);
1457 if (load_cursor_frame( bits, cbSize, hotspot, dwVersion, width, height, cFlag, &frame ))
1459 set_cursor_frame( cursor, 0, &frame );
1461 else
1463 destroy_cursor( cursor );
1464 cursor = 0;
1467 HeapFree( GetProcessHeap(), 0, frame.bits );
1469 return cursor;
1473 /**********************************************************************
1474 * CreateIconFromResource (USER32.@)
1476 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
1477 BOOL bIcon, DWORD dwVersion)
1479 return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
1483 static HICON CURSORICON_LoadFromFile( LPCWSTR filename,
1484 INT width, INT height, INT colors,
1485 BOOL fCursor, UINT loadflags)
1487 CURSORICONFILEDIRENTRY *entry;
1488 cursor_frame_t frame = {0};
1489 CURSORICONFILEDIR *dir;
1490 DWORD filesize = 0;
1491 HICON hIcon = 0;
1492 POINT16 hotspot;
1493 LPBYTE bits;
1495 TRACE("loading %s\n", debugstr_w( filename ));
1497 bits = map_fileW( filename, &filesize );
1498 if (!bits)
1499 return hIcon;
1501 /* If the data contains the magic for an .ICO it's an .ICO,
1502 * regardless of what fCursor says. */
1503 if (!memcmp( bits, "\x00\x00\x01\x00", 4 )) fCursor = FALSE;
1504 /* Same thing for .CUR */
1505 else if (!memcmp( bits, "\x00\x00\x02\x00", 4 )) fCursor = TRUE;
1506 /* Check for .ani. */
1507 else if (!memcmp( bits, "RIFF", 4 ))
1509 hIcon = load_ani( bits, filesize, width, height );
1510 goto end;
1513 dir = (CURSORICONFILEDIR*) bits;
1514 if ( filesize < sizeof(*dir) )
1515 goto end;
1517 if ( filesize < (sizeof(*dir) + sizeof(dir->idEntries[0])*(dir->idCount-1)) )
1518 goto end;
1520 if ( fCursor )
1521 entry = CURSORICON_FindBestCursorFile( dir, width, height, colors );
1522 else
1523 entry = CURSORICON_FindBestIconFile( dir, width, height, colors );
1525 if ( !entry )
1526 goto end;
1528 /* check that we don't run off the end of the file */
1529 if ( entry->dwDIBOffset > filesize )
1530 goto end;
1531 if ( entry->dwDIBOffset + entry->dwDIBSize > filesize )
1532 goto end;
1534 if ( fCursor )
1536 hotspot.x = entry->xHotspot;
1537 hotspot.y = entry->yHotspot;
1539 else
1541 hotspot.x = ICON_HOTSPOT;
1542 hotspot.y = ICON_HOTSPOT;
1545 hIcon = create_cursor( 1, 0 );
1546 load_cursor_frame( &bits[entry->dwDIBOffset], entry->dwDIBSize, hotspot,
1547 0x00030000, width, height, loadflags, &frame );
1548 set_cursor_frame( hIcon, 0, &frame );
1549 HeapFree( GetProcessHeap(), 0, frame.bits );
1551 end:
1552 TRACE("loaded %s -> %p\n", debugstr_w( filename ), hIcon );
1553 UnmapViewOfFile( bits );
1554 return hIcon;
1557 /**********************************************************************
1558 * CURSORICON_Load
1560 * Load a cursor or icon from resource or file.
1562 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
1563 INT width, INT height, INT colors,
1564 BOOL fCursor, UINT loadflags)
1566 HANDLE handle = 0;
1567 HICON hIcon = 0;
1568 HRSRC hRsrc, hGroupRsrc;
1569 CURSORICONDIR *dir;
1570 CURSORICONDIRENTRY *dirEntry;
1571 LPBYTE bits;
1572 WORD wResId;
1573 DWORD dwBytesInRes;
1575 TRACE("%p, %s, %dx%d, colors %d, fCursor %d, flags 0x%04x\n",
1576 hInstance, debugstr_w(name), width, height, colors, fCursor, loadflags);
1578 if ( loadflags & LR_LOADFROMFILE ) /* Load from file */
1579 return CURSORICON_LoadFromFile( name, width, height, colors, fCursor, loadflags );
1581 if (!hInstance) hInstance = user32_module; /* Load OEM cursor/icon */
1583 /* Normalize hInstance (must be uniquely represented for icon cache) */
1585 if (!HIWORD( hInstance ))
1586 hInstance = HINSTANCE_32(GetExePtr( HINSTANCE_16(hInstance) ));
1588 /* Get directory resource ID */
1590 if (!(hRsrc = FindResourceW( hInstance, name,
1591 (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
1592 return 0;
1593 hGroupRsrc = hRsrc;
1595 /* Find the best entry in the directory */
1597 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1598 if (!(dir = (CURSORICONDIR*)LockResource( handle ))) return 0;
1599 if (fCursor)
1600 dirEntry = CURSORICON_FindBestCursorRes( dir, width, height, 1);
1601 else
1602 dirEntry = CURSORICON_FindBestIconRes( dir, width, height, colors );
1603 if (!dirEntry) return 0;
1604 wResId = dirEntry->wResId;
1605 dwBytesInRes = dirEntry->dwBytesInRes;
1606 FreeResource( handle );
1608 /* Load the resource */
1610 if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
1611 (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
1613 /* If shared icon, check whether it was already loaded */
1614 if ( (loadflags & LR_SHARED)
1615 && (hIcon = CURSORICON_FindSharedIcon( hInstance, hRsrc ) ) != 0 )
1616 return hIcon;
1618 if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
1619 bits = (LPBYTE)LockResource( handle );
1620 hIcon = CreateIconFromResourceEx( bits, dwBytesInRes,
1621 !fCursor, 0x00030000, width, height, loadflags);
1622 FreeResource( handle );
1624 /* If shared icon, add to icon cache */
1626 if ( hIcon && (loadflags & LR_SHARED) )
1627 CURSORICON_AddSharedIcon( hInstance, hRsrc, hGroupRsrc, hIcon );
1629 return hIcon;
1632 /***********************************************************************
1633 * CURSORICON_Copy
1635 * Make a copy of a cursor or icon.
1637 static HICON CURSORICON_Copy( HINSTANCE16 hInst16, HICON hIcon )
1639 /* Should animated cursors be copyable like this as well? */
1640 HCURSOR new_cursor;
1641 cursor_frame_t frame;
1643 if (!hIcon || !get_cursor_frame( hIcon, 0, &frame ))
1645 return 0;
1648 new_cursor = create_cursor( 1, 0 );
1649 set_cursor_frame( new_cursor, 0, &frame );
1650 HeapFree( GetProcessHeap(), 0, frame.bits );
1652 return new_cursor;
1655 /*************************************************************************
1656 * CURSORICON_ExtCopy
1658 * Copies an Image from the Cache if LR_COPYFROMRESOURCE is specified
1660 * PARAMS
1661 * Handle [I] handle to an Image
1662 * nType [I] Type of Handle (IMAGE_CURSOR | IMAGE_ICON)
1663 * iDesiredCX [I] The Desired width of the Image
1664 * iDesiredCY [I] The desired height of the Image
1665 * nFlags [I] The flags from CopyImage
1667 * RETURNS
1668 * Success: The new handle of the Image
1670 * NOTES
1671 * LR_COPYDELETEORG and LR_MONOCHROME are currently not implemented.
1672 * LR_MONOCHROME should be implemented by CreateIconFromResourceEx.
1673 * LR_COPYFROMRESOURCE will only work if the Image is in the Cache.
1678 static HICON CURSORICON_ExtCopy(HICON hIcon, UINT nType,
1679 INT iDesiredCX, INT iDesiredCY,
1680 UINT nFlags)
1682 HICON hNew=0;
1684 TRACE_(icon)("hIcon %p, nType %u, iDesiredCX %i, iDesiredCY %i, nFlags %u\n",
1685 hIcon, nType, iDesiredCX, iDesiredCY, nFlags);
1687 if(hIcon == 0)
1689 return 0;
1692 /* Best Fit or Monochrome */
1693 if( (nFlags & LR_COPYFROMRESOURCE
1694 && (iDesiredCX > 0 || iDesiredCY > 0))
1695 || nFlags & LR_MONOCHROME)
1697 ICONCACHE* pIconCache = CURSORICON_FindCache(hIcon);
1699 /* Not Found in Cache, then do a straight copy
1701 if(pIconCache == NULL)
1703 hNew = CURSORICON_Copy(0, hIcon);
1704 if(nFlags & LR_COPYFROMRESOURCE)
1706 TRACE_(icon)("LR_COPYFROMRESOURCE: Failed to load from cache\n");
1709 else
1711 int iTargetCY = iDesiredCY, iTargetCX = iDesiredCX;
1712 LPBYTE pBits;
1713 HANDLE hMem;
1714 HRSRC hRsrc;
1715 DWORD dwBytesInRes;
1716 WORD wResId;
1717 CURSORICONDIR *pDir;
1718 CURSORICONDIRENTRY *pDirEntry;
1719 BOOL bIsIcon = (nType == IMAGE_ICON);
1721 /* Completing iDesiredCX CY for Monochrome Bitmaps if needed
1723 if(((nFlags & LR_MONOCHROME) && !(nFlags & LR_COPYFROMRESOURCE))
1724 || (iDesiredCX == 0 && iDesiredCY == 0))
1726 iDesiredCY = GetSystemMetrics(bIsIcon ?
1727 SM_CYICON : SM_CYCURSOR);
1728 iDesiredCX = GetSystemMetrics(bIsIcon ?
1729 SM_CXICON : SM_CXCURSOR);
1732 /* Retrieve the CURSORICONDIRENTRY
1734 if (!(hMem = LoadResource( pIconCache->hModule ,
1735 pIconCache->hGroupRsrc)))
1737 return 0;
1739 if (!(pDir = (CURSORICONDIR*)LockResource( hMem )))
1741 return 0;
1744 /* Find Best Fit
1746 if(bIsIcon)
1748 pDirEntry = CURSORICON_FindBestIconRes(
1749 pDir, iDesiredCX, iDesiredCY, 256 );
1751 else
1753 pDirEntry = CURSORICON_FindBestCursorRes(
1754 pDir, iDesiredCX, iDesiredCY, 1);
1757 wResId = pDirEntry->wResId;
1758 dwBytesInRes = pDirEntry->dwBytesInRes;
1759 FreeResource(hMem);
1761 TRACE_(icon)("ResID %u, BytesInRes %u, Width %d, Height %d DX %d, DY %d\n",
1762 wResId, dwBytesInRes, pDirEntry->ResInfo.icon.bWidth,
1763 pDirEntry->ResInfo.icon.bHeight, iDesiredCX, iDesiredCY);
1765 /* Get the Best Fit
1767 if (!(hRsrc = FindResourceW(pIconCache->hModule ,
1768 MAKEINTRESOURCEW(wResId), (LPWSTR)(bIsIcon ? RT_ICON : RT_CURSOR))))
1770 return 0;
1772 if (!(hMem = LoadResource( pIconCache->hModule , hRsrc )))
1774 return 0;
1777 pBits = (LPBYTE)LockResource( hMem );
1779 if(nFlags & LR_DEFAULTSIZE)
1781 iTargetCY = GetSystemMetrics(SM_CYICON);
1782 iTargetCX = GetSystemMetrics(SM_CXICON);
1785 /* Create a New Icon with the proper dimension
1787 hNew = CreateIconFromResourceEx( pBits, dwBytesInRes,
1788 bIsIcon, 0x00030000, iTargetCX, iTargetCY, nFlags);
1789 FreeResource(hMem);
1792 else hNew = CURSORICON_Copy(0, hIcon);
1793 return hNew;
1797 /***********************************************************************
1798 * CreateCursor (USER32.@)
1800 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
1801 INT xHotSpot, INT yHotSpot,
1802 INT nWidth, INT nHeight,
1803 LPCVOID lpANDbits, LPCVOID lpXORbits )
1805 CURSORICONINFO info;
1807 TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
1808 nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
1810 info.ptHotSpot.x = xHotSpot;
1811 info.ptHotSpot.y = yHotSpot;
1812 info.nWidth = nWidth;
1813 info.nHeight = nHeight;
1814 info.nWidthBytes = 0;
1815 info.bPlanes = 1;
1816 info.bBitsPerPixel = 1;
1818 return HICON_32(CreateCursorIconIndirect16(0, &info, lpANDbits, lpXORbits));
1822 /***********************************************************************
1823 * CreateIcon (USER.407)
1825 HICON16 WINAPI CreateIcon16( HINSTANCE16 hInstance, INT16 nWidth,
1826 INT16 nHeight, BYTE bPlanes, BYTE bBitsPixel,
1827 LPCVOID lpANDbits, LPCVOID lpXORbits )
1829 CURSORICONINFO info;
1831 TRACE_(icon)("%dx%dx%d, xor=%p, and=%p\n",
1832 nWidth, nHeight, bPlanes * bBitsPixel, lpXORbits, lpANDbits);
1834 info.ptHotSpot.x = ICON_HOTSPOT;
1835 info.ptHotSpot.y = ICON_HOTSPOT;
1836 info.nWidth = nWidth;
1837 info.nHeight = nHeight;
1838 info.nWidthBytes = 0;
1839 info.bPlanes = bPlanes;
1840 info.bBitsPerPixel = bBitsPixel;
1842 return CreateCursorIconIndirect16( hInstance, &info, lpANDbits, lpXORbits );
1846 /***********************************************************************
1847 * CreateIcon (USER32.@)
1849 * Creates an icon based on the specified bitmaps. The bitmaps must be
1850 * provided in a device dependent format and will be resized to
1851 * (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1852 * depth. The provided bitmaps must be top-down bitmaps.
1853 * Although Windows does not support 15bpp(*) this API must support it
1854 * for Winelib applications.
1856 * (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1857 * format!
1859 * RETURNS
1860 * Success: handle to an icon
1861 * Failure: NULL
1863 * FIXME: Do we need to resize the bitmaps?
1865 HICON WINAPI CreateIcon(
1866 HINSTANCE hInstance, /* [in] the application's hInstance */
1867 INT nWidth, /* [in] the width of the provided bitmaps */
1868 INT nHeight, /* [in] the height of the provided bitmaps */
1869 BYTE bPlanes, /* [in] the number of planes in the provided bitmaps */
1870 BYTE bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1871 LPCVOID lpANDbits, /* [in] a monochrome bitmap representing the icon's mask */
1872 LPCVOID lpXORbits) /* [in] the icon's 'color' bitmap */
1874 ICONINFO iinfo;
1875 HICON hIcon;
1877 TRACE_(icon)("%dx%d, planes %d, bpp %d, xor %p, and %p\n",
1878 nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits, lpANDbits);
1880 iinfo.fIcon = TRUE;
1881 iinfo.xHotspot = ICON_HOTSPOT;
1882 iinfo.yHotspot = ICON_HOTSPOT;
1883 iinfo.hbmMask = CreateBitmap( nWidth, nHeight, 1, 1, lpANDbits );
1884 iinfo.hbmColor = CreateBitmap( nWidth, nHeight, bPlanes, bBitsPixel, lpXORbits );
1886 hIcon = CreateIconIndirect( &iinfo );
1888 DeleteObject( iinfo.hbmMask );
1889 DeleteObject( iinfo.hbmColor );
1891 return hIcon;
1895 /***********************************************************************
1896 * CreateCursorIconIndirect (USER.408)
1898 HGLOBAL16 WINAPI CreateCursorIconIndirect16( HINSTANCE16 hInstance,
1899 CURSORICONINFO *info,
1900 LPCVOID lpANDbits,
1901 LPCVOID lpXORbits )
1903 HCURSOR cursor;
1904 cursor_frame_t frame;
1905 int sizeAnd, sizeXor;
1907 if (!lpXORbits || !lpANDbits || info->bPlanes != 1) return 0;
1908 info->nWidthBytes = get_bitmap_width_bytes(info->nWidth,info->bBitsPerPixel);
1909 sizeXor = info->nHeight * info->nWidthBytes;
1910 sizeAnd = info->nHeight * get_bitmap_width_bytes( info->nWidth, 1 );
1912 cursor = create_cursor( 1, 0 );
1913 frame.xhot = info->ptHotSpot.x;
1914 frame.yhot = info->ptHotSpot.y;
1915 frame.width = info->nWidth;
1916 frame.height = info->nHeight;
1917 frame.and_width_bytes = get_bitmap_width_bytes( info->nWidth, 1 );
1918 frame.xor_width_bytes = info->nWidthBytes;
1919 frame.planes = info->bPlanes;
1920 frame.bpp = info->bBitsPerPixel;
1921 frame.bits = HeapAlloc( GetProcessHeap(), 0, sizeAnd + sizeXor );
1922 CopyMemory( frame.bits, lpANDbits, sizeAnd );
1923 CopyMemory( frame.bits + sizeAnd, lpXORbits, sizeXor );
1924 set_cursor_frame( cursor, 0, &frame );
1925 HeapFree( GetProcessHeap(), 0, frame.bits );
1927 return HICON_16(cursor);
1931 /***********************************************************************
1932 * CopyIcon (USER.368)
1934 HICON16 WINAPI CopyIcon16( HINSTANCE16 hInstance, HICON16 hIcon )
1936 TRACE_(icon)("%04x %04x\n", hInstance, hIcon );
1937 return HICON_16(CURSORICON_Copy(hInstance, HICON_32(hIcon)));
1941 /***********************************************************************
1942 * CopyIcon (USER32.@)
1944 HICON WINAPI CopyIcon( HICON hIcon )
1946 TRACE_(icon)("%p\n", hIcon );
1947 return CURSORICON_Copy( 0, hIcon );
1951 /***********************************************************************
1952 * CopyCursor (USER.369)
1954 HCURSOR16 WINAPI CopyCursor16( HINSTANCE16 hInstance, HCURSOR16 hCursor )
1956 TRACE_(cursor)("%04x %04x\n", hInstance, hCursor );
1957 return HICON_16(CURSORICON_Copy(hInstance, HCURSOR_32(hCursor)));
1960 /**********************************************************************
1961 * DestroyIcon32 (USER.610)
1963 * This routine is actually exported from Win95 USER under the name
1964 * DestroyIcon32 ... The behaviour implemented here should mimic
1965 * the Win95 one exactly, especially the return values, which
1966 * depend on the setting of various flags.
1968 WORD WINAPI DestroyIcon32( HGLOBAL16 handle, UINT16 flags )
1970 WORD retv;
1972 TRACE_(icon)("(%04x, %04x)\n", handle, flags );
1974 /* Check whether destroying active cursor */
1976 if ( get_user_thread_info()->cursor == HICON_32(handle) )
1978 WARN_(cursor)("Destroying active cursor!\n" );
1979 return FALSE;
1982 /* Try shared cursor/icon first */
1984 if ( !(flags & CID_NONSHARED) )
1986 INT count = CURSORICON_DelSharedIcon(HICON_32(handle));
1988 if ( count != -1 )
1989 return (flags & CID_WIN32)? TRUE : (count == 0);
1991 /* FIXME: OEM cursors/icons should be recognized */
1994 /* Now assume non-shared cursor/icon */
1996 retv = destroy_cursor( HCURSOR_32(handle) );
1997 return (flags & CID_RESOURCE)? retv : TRUE;
2000 /***********************************************************************
2001 * DestroyIcon (USER32.@)
2003 BOOL WINAPI DestroyIcon( HICON hIcon )
2005 return DestroyIcon32(HICON_16(hIcon), CID_WIN32);
2009 /***********************************************************************
2010 * DestroyCursor (USER32.@)
2012 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
2014 return DestroyIcon32(HCURSOR_16(hCursor), CID_WIN32);
2018 /***********************************************************************
2019 * DrawIcon (USER32.@)
2021 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
2023 CURSORICONINFO *ptr;
2024 HDC hMemDC;
2025 HBITMAP hXorBits, hAndBits;
2026 COLORREF oldFg, oldBg;
2028 TRACE("%p, (%d,%d), %p\n", hdc, x, y, hIcon);
2030 if (!(ptr = (CURSORICONINFO *)GlobalLock16(HICON_16(hIcon)))) return FALSE;
2031 if (!(hMemDC = CreateCompatibleDC( hdc ))) return FALSE;
2032 hAndBits = CreateBitmap( ptr->nWidth, ptr->nHeight, 1, 1,
2033 (char *)(ptr+1) );
2034 hXorBits = CreateBitmap( ptr->nWidth, ptr->nHeight, ptr->bPlanes,
2035 ptr->bBitsPerPixel, (char *)(ptr + 1)
2036 + ptr->nHeight * get_bitmap_width_bytes(ptr->nWidth,1) );
2037 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2038 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2040 if (hXorBits && hAndBits)
2042 HBITMAP hBitTemp = SelectObject( hMemDC, hAndBits );
2043 BitBlt( hdc, x, y, ptr->nWidth, ptr->nHeight, hMemDC, 0, 0, SRCAND );
2044 SelectObject( hMemDC, hXorBits );
2045 BitBlt(hdc, x, y, ptr->nWidth, ptr->nHeight, hMemDC, 0, 0,SRCINVERT);
2046 SelectObject( hMemDC, hBitTemp );
2048 DeleteDC( hMemDC );
2049 if (hXorBits) DeleteObject( hXorBits );
2050 if (hAndBits) DeleteObject( hAndBits );
2051 GlobalUnlock16(HICON_16(hIcon));
2052 SetTextColor( hdc, oldFg );
2053 SetBkColor( hdc, oldBg );
2054 return TRUE;
2057 /***********************************************************************
2058 * DumpIcon (USER.459)
2060 DWORD WINAPI DumpIcon16( SEGPTR pInfo, WORD *lpLen,
2061 SEGPTR *lpXorBits, SEGPTR *lpAndBits )
2063 CURSORICONINFO *info = MapSL( pInfo );
2064 int sizeAnd, sizeXor;
2066 if (!info) return 0;
2067 sizeXor = info->nHeight * info->nWidthBytes;
2068 sizeAnd = info->nHeight * get_bitmap_width_bytes( info->nWidth, 1 );
2069 if (lpAndBits) *lpAndBits = pInfo + sizeof(CURSORICONINFO);
2070 if (lpXorBits) *lpXorBits = pInfo + sizeof(CURSORICONINFO) + sizeAnd;
2071 if (lpLen) *lpLen = sizeof(CURSORICONINFO) + sizeAnd + sizeXor;
2072 return MAKELONG( sizeXor, sizeXor );
2076 /***********************************************************************
2077 * SetCursor (USER32.@)
2079 * Set the cursor shape.
2081 * RETURNS
2082 * A handle to the previous cursor shape.
2084 HCURSOR WINAPI SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
2086 struct user_thread_info *thread_info = get_user_thread_info();
2087 HCURSOR hOldCursor;
2089 if (hCursor == thread_info->cursor) return hCursor; /* No change */
2090 TRACE("%p\n", hCursor);
2091 hOldCursor = thread_info->cursor;
2092 thread_info->cursor = hCursor;
2093 /* Change the cursor shape only if it is visible */
2094 if (thread_info->cursor_count >= 0)
2096 cursor_t *cursor;
2098 update_cursor_32from16( hCursor );
2099 cursor = get_cursor_object( hCursor );
2100 USER_Driver->pSetCursor( cursor );
2101 destroy_cursor_object( cursor );
2103 return hOldCursor;
2106 /***********************************************************************
2107 * ShowCursor (USER32.@)
2109 INT WINAPI ShowCursor( BOOL bShow )
2111 struct user_thread_info *thread_info = get_user_thread_info();
2113 TRACE("%d, count=%d\n", bShow, thread_info->cursor_count );
2115 if (bShow)
2117 if (++thread_info->cursor_count == 0) /* Show it */
2119 cursor_t *cursor;
2121 update_cursor_32from16( thread_info->cursor );
2122 cursor = get_cursor_object( thread_info->cursor );
2123 USER_Driver->pSetCursor( cursor );
2124 destroy_cursor_object( cursor );
2127 else
2129 if (--thread_info->cursor_count == -1) /* Hide it */
2130 USER_Driver->pSetCursor( NULL );
2132 return thread_info->cursor_count;
2135 /***********************************************************************
2136 * GetCursor (USER32.@)
2138 HCURSOR WINAPI GetCursor(void)
2140 return get_user_thread_info()->cursor;
2144 /***********************************************************************
2145 * ClipCursor (USER32.@)
2147 BOOL WINAPI ClipCursor( const RECT *rect )
2149 RECT virt;
2151 SetRect( &virt, 0, 0, GetSystemMetrics( SM_CXVIRTUALSCREEN ),
2152 GetSystemMetrics( SM_CYVIRTUALSCREEN ) );
2153 OffsetRect( &virt, GetSystemMetrics( SM_XVIRTUALSCREEN ),
2154 GetSystemMetrics( SM_YVIRTUALSCREEN ) );
2156 TRACE( "Clipping to: %s was: %s screen: %s\n", wine_dbgstr_rect(rect),
2157 wine_dbgstr_rect(&CURSOR_ClipRect), wine_dbgstr_rect(&virt) );
2159 if (!IntersectRect( &CURSOR_ClipRect, &virt, rect ))
2160 CURSOR_ClipRect = virt;
2162 USER_Driver->pClipCursor( rect );
2163 return TRUE;
2167 /***********************************************************************
2168 * GetClipCursor (USER32.@)
2170 BOOL WINAPI GetClipCursor( RECT *rect )
2172 /* If this is first time - initialize the rect */
2173 if (IsRectEmpty( &CURSOR_ClipRect )) ClipCursor( NULL );
2175 return CopyRect( rect, &CURSOR_ClipRect );
2179 /***********************************************************************
2180 * SetSystemCursor (USER32.@)
2182 BOOL WINAPI SetSystemCursor(HCURSOR hcur, DWORD id)
2184 FIXME("(%p,%08x),stub!\n", hcur, id);
2185 return TRUE;
2189 /**********************************************************************
2190 * LookupIconIdFromDirectoryEx (USER.364)
2192 * FIXME: exact parameter sizes
2194 INT16 WINAPI LookupIconIdFromDirectoryEx16( LPBYTE dir, BOOL16 bIcon,
2195 INT16 width, INT16 height, UINT16 cFlag )
2197 return LookupIconIdFromDirectoryEx( dir, bIcon, width, height, cFlag );
2200 /**********************************************************************
2201 * LookupIconIdFromDirectoryEx (USER32.@)
2203 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
2204 INT width, INT height, UINT cFlag )
2206 CURSORICONDIR *dir = (CURSORICONDIR*)xdir;
2207 UINT retVal = 0;
2208 if( dir && !dir->idReserved && (dir->idType & 3) )
2210 CURSORICONDIRENTRY* entry;
2211 HDC hdc;
2212 UINT palEnts;
2213 int colors;
2214 hdc = GetDC(0);
2215 palEnts = GetSystemPaletteEntries(hdc, 0, 0, NULL);
2216 if (palEnts == 0)
2217 palEnts = 256;
2218 colors = (cFlag & LR_MONOCHROME) ? 2 : palEnts;
2220 ReleaseDC(0, hdc);
2222 if( bIcon )
2223 entry = CURSORICON_FindBestIconRes( dir, width, height, colors );
2224 else
2225 entry = CURSORICON_FindBestCursorRes( dir, width, height, 1);
2227 if( entry ) retVal = entry->wResId;
2229 else WARN_(cursor)("invalid resource directory\n");
2230 return retVal;
2233 /**********************************************************************
2234 * LookupIconIdFromDirectory (USER.?)
2236 INT16 WINAPI LookupIconIdFromDirectory16( LPBYTE dir, BOOL16 bIcon )
2238 return LookupIconIdFromDirectoryEx16( dir, bIcon,
2239 bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
2240 bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
2243 /**********************************************************************
2244 * LookupIconIdFromDirectory (USER32.@)
2246 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
2248 return LookupIconIdFromDirectoryEx( dir, bIcon,
2249 bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
2250 bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
2253 /**********************************************************************
2254 * GetIconID (USER.455)
2256 WORD WINAPI GetIconID16( HGLOBAL16 hResource, DWORD resType )
2258 LPBYTE lpDir = (LPBYTE)GlobalLock16(hResource);
2260 TRACE_(cursor)("hRes=%04x, entries=%i\n",
2261 hResource, lpDir ? ((CURSORICONDIR*)lpDir)->idCount : 0);
2263 switch(resType)
2265 case RT_CURSOR:
2266 return (WORD)LookupIconIdFromDirectoryEx16( lpDir, FALSE,
2267 GetSystemMetrics(SM_CXCURSOR), GetSystemMetrics(SM_CYCURSOR), LR_MONOCHROME );
2268 case RT_ICON:
2269 return (WORD)LookupIconIdFromDirectoryEx16( lpDir, TRUE,
2270 GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), 0 );
2271 default:
2272 WARN_(cursor)("invalid res type %d\n", resType );
2274 return 0;
2277 /**********************************************************************
2278 * LoadCursorIconHandler (USER.336)
2280 * Supposed to load resources of Windows 2.x applications.
2282 HGLOBAL16 WINAPI LoadCursorIconHandler16( HGLOBAL16 hResource, HMODULE16 hModule, HRSRC16 hRsrc )
2284 FIXME_(cursor)("(%04x,%04x,%04x): old 2.x resources are not supported!\n",
2285 hResource, hModule, hRsrc);
2286 return (HGLOBAL16)0;
2289 /**********************************************************************
2290 * LoadIconHandler (USER.456)
2292 HICON16 WINAPI LoadIconHandler16( HGLOBAL16 hResource, BOOL16 bNew )
2294 LPBYTE bits = (LPBYTE)LockResource16( hResource );
2296 TRACE_(cursor)("hRes=%04x\n",hResource);
2298 return HICON_16(CreateIconFromResourceEx( bits, 0, TRUE,
2299 bNew ? 0x00030000 : 0x00020000, 0, 0, LR_DEFAULTCOLOR));
2302 /***********************************************************************
2303 * LoadCursorW (USER32.@)
2305 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
2307 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2309 return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
2310 LR_SHARED | LR_DEFAULTSIZE );
2313 /***********************************************************************
2314 * LoadCursorA (USER32.@)
2316 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
2318 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2320 return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
2321 LR_SHARED | LR_DEFAULTSIZE );
2324 /***********************************************************************
2325 * LoadCursorFromFileW (USER32.@)
2327 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
2329 TRACE("%s\n", debugstr_w(name));
2331 return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
2332 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2335 /***********************************************************************
2336 * LoadCursorFromFileA (USER32.@)
2338 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
2340 TRACE("%s\n", debugstr_a(name));
2342 return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
2343 LR_LOADFROMFILE | LR_DEFAULTSIZE );
2346 /***********************************************************************
2347 * LoadIconW (USER32.@)
2349 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
2351 TRACE("%p, %s\n", hInstance, debugstr_w(name));
2353 return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
2354 LR_SHARED | LR_DEFAULTSIZE );
2357 /***********************************************************************
2358 * LoadIconA (USER32.@)
2360 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
2362 TRACE("%p, %s\n", hInstance, debugstr_a(name));
2364 return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
2365 LR_SHARED | LR_DEFAULTSIZE );
2368 /**********************************************************************
2369 * GetIconInfo (USER32.@)
2371 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
2373 CURSORICONINFO *ciconinfo;
2374 INT height;
2376 ciconinfo = GlobalLock16(HICON_16(hIcon));
2377 if (!ciconinfo)
2378 return FALSE;
2380 TRACE("%p => %dx%d, %d bpp\n", hIcon,
2381 ciconinfo->nWidth, ciconinfo->nHeight, ciconinfo->bBitsPerPixel);
2383 if ( (ciconinfo->ptHotSpot.x == ICON_HOTSPOT) &&
2384 (ciconinfo->ptHotSpot.y == ICON_HOTSPOT) )
2386 iconinfo->fIcon = TRUE;
2387 iconinfo->xHotspot = ciconinfo->nWidth / 2;
2388 iconinfo->yHotspot = ciconinfo->nHeight / 2;
2390 else
2392 iconinfo->fIcon = FALSE;
2393 iconinfo->xHotspot = ciconinfo->ptHotSpot.x;
2394 iconinfo->yHotspot = ciconinfo->ptHotSpot.y;
2397 height = ciconinfo->nHeight;
2399 if (ciconinfo->bBitsPerPixel > 1)
2401 iconinfo->hbmColor = CreateBitmap( ciconinfo->nWidth, ciconinfo->nHeight,
2402 ciconinfo->bPlanes, ciconinfo->bBitsPerPixel,
2403 (char *)(ciconinfo + 1)
2404 + ciconinfo->nHeight *
2405 get_bitmap_width_bytes (ciconinfo->nWidth,1) );
2407 else
2409 iconinfo->hbmColor = 0;
2410 height *= 2;
2413 iconinfo->hbmMask = CreateBitmap ( ciconinfo->nWidth, height,
2414 1, 1, (char *)(ciconinfo + 1));
2416 GlobalUnlock16(HICON_16(hIcon));
2418 return TRUE;
2421 /**********************************************************************
2422 * CreateIconIndirect (USER32.@)
2424 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
2426 HCURSOR cursor;
2427 cursor_frame_t frame;
2428 DIBSECTION bmpXor;
2429 BITMAP bmpAnd;
2430 int xor_objsize = 0, sizeXor = 0, sizeAnd, planes, bpp;
2432 TRACE("color %p, mask %p, hotspot %ux%u, fIcon %d\n",
2433 iconinfo->hbmColor, iconinfo->hbmMask,
2434 iconinfo->xHotspot, iconinfo->yHotspot, iconinfo->fIcon);
2436 if (!iconinfo->hbmMask) return 0;
2438 planes = GetDeviceCaps( screen_dc, PLANES );
2439 bpp = GetDeviceCaps( screen_dc, BITSPIXEL );
2441 if (iconinfo->hbmColor)
2443 xor_objsize = GetObjectW( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
2444 TRACE("color: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2445 bmpXor.dsBm.bmWidth, bmpXor.dsBm.bmHeight, bmpXor.dsBm.bmWidthBytes,
2446 bmpXor.dsBm.bmPlanes, bmpXor.dsBm.bmBitsPixel);
2447 /* we can use either depth 1 or screen depth for xor bitmap */
2448 if (bmpXor.dsBm.bmPlanes == 1 && bmpXor.dsBm.bmBitsPixel == 1) planes = bpp = 1;
2449 sizeXor = bmpXor.dsBm.bmHeight * planes * get_bitmap_width_bytes( bmpXor.dsBm.bmWidth, bpp );
2451 GetObjectW( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
2452 TRACE("mask: width %d, height %d, width bytes %d, planes %u, bpp %u\n",
2453 bmpAnd.bmWidth, bmpAnd.bmHeight, bmpAnd.bmWidthBytes,
2454 bmpAnd.bmPlanes, bmpAnd.bmBitsPixel);
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.dsBm.bmWidth;
2475 frame.height = bmpXor.dsBm.bmHeight;
2476 frame.and_width_bytes = bmpAnd.bmWidthBytes;
2477 frame.xor_width_bytes = bmpXor.dsBm.bmWidthBytes;
2478 frame.planes = planes;
2479 frame.bpp = bpp;
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)
2525 char *dst_bits = frame.bits + sizeAnd;
2527 if (bmpXor.dsBm.bmPlanes == planes && bmpXor.dsBm.bmBitsPixel == bpp)
2528 GetBitmapBits( iconinfo->hbmColor, sizeXor, dst_bits );
2529 else
2531 BITMAPINFO bminfo;
2532 int dib_width = get_dib_width_bytes( frame.width, frame.bpp );
2533 int bitmap_width = get_bitmap_width_bytes( frame.width, frame.bpp );
2535 bminfo.bmiHeader.biSize = sizeof(bminfo);
2536 bminfo.bmiHeader.biWidth = frame.width;
2537 bminfo.bmiHeader.biHeight = frame.height;
2538 bminfo.bmiHeader.biPlanes = frame.planes;
2539 bminfo.bmiHeader.biBitCount = frame.bpp;
2540 bminfo.bmiHeader.biCompression = BI_RGB;
2541 bminfo.bmiHeader.biSizeImage = frame.height * dib_width;
2542 bminfo.bmiHeader.biXPelsPerMeter = 0;
2543 bminfo.bmiHeader.biYPelsPerMeter = 0;
2544 bminfo.bmiHeader.biClrUsed = 0;
2545 bminfo.bmiHeader.biClrImportant = 0;
2547 /* swap lines for dib sections */
2548 if (xor_objsize == sizeof(DIBSECTION))
2549 bminfo.bmiHeader.biHeight = -bminfo.bmiHeader.biHeight;
2551 if (dib_width != bitmap_width) /* need to fixup alignment */
2553 char *src_bits = HeapAlloc( GetProcessHeap(), 0, bminfo.bmiHeader.biSizeImage );
2555 if (src_bits && GetDIBits( screen_dc, iconinfo->hbmColor, 0, frame.height,
2556 src_bits, &bminfo, DIB_RGB_COLORS ))
2558 int y;
2559 for (y = 0; y < frame.height; y++)
2560 memcpy( dst_bits + y * bitmap_width, src_bits + y * dib_width, bitmap_width );
2562 HeapFree( GetProcessHeap(), 0, src_bits );
2564 else
2565 GetDIBits( screen_dc, iconinfo->hbmColor, 0, frame.height,
2566 dst_bits, &bminfo, DIB_RGB_COLORS );
2569 set_cursor_frame( cursor, 0, &frame );
2570 HeapFree( GetProcessHeap(), 0, frame.bits );
2572 return cursor;
2575 /******************************************************************************
2576 * DrawIconEx (USER32.@) Draws an icon or cursor on device context
2578 * NOTES
2579 * Why is this using SM_CXICON instead of SM_CXCURSOR?
2581 * PARAMS
2582 * hdc [I] Handle to device context
2583 * x0 [I] X coordinate of upper left corner
2584 * y0 [I] Y coordinate of upper left corner
2585 * hIcon [I] Handle to icon to draw
2586 * cxWidth [I] Width of icon
2587 * cyWidth [I] Height of icon
2588 * istep [I] Index of frame in animated cursor
2589 * hbr [I] Handle to background brush
2590 * flags [I] Icon-drawing flags
2592 * RETURNS
2593 * Success: TRUE
2594 * Failure: FALSE
2596 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
2597 INT cxWidth, INT cyWidth, UINT istep,
2598 HBRUSH hbr, UINT flags )
2600 CURSORICONINFO *ptr = (CURSORICONINFO *)GlobalLock16(HICON_16(hIcon));
2601 HDC hDC_off = 0, hMemDC;
2602 BOOL result = FALSE, DoOffscreen;
2603 HBITMAP hB_off = 0, hOld = 0;
2605 if (!ptr) return FALSE;
2606 TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
2607 hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
2609 hMemDC = CreateCompatibleDC (hdc);
2610 if (istep)
2611 FIXME_(icon)("Ignoring istep=%d\n", istep);
2612 if (flags & DI_COMPAT)
2613 FIXME_(icon)("Ignoring flag DI_COMPAT\n");
2615 if (!flags) {
2616 FIXME_(icon)("no flags set? setting to DI_NORMAL\n");
2617 flags = DI_NORMAL;
2620 /* Calculate the size of the destination image. */
2621 if (cxWidth == 0)
2623 if (flags & DI_DEFAULTSIZE)
2624 cxWidth = GetSystemMetrics (SM_CXICON);
2625 else
2626 cxWidth = ptr->nWidth;
2628 if (cyWidth == 0)
2630 if (flags & DI_DEFAULTSIZE)
2631 cyWidth = GetSystemMetrics (SM_CYICON);
2632 else
2633 cyWidth = ptr->nHeight;
2636 DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
2638 if (DoOffscreen) {
2639 RECT r;
2641 r.left = 0;
2642 r.top = 0;
2643 r.right = cxWidth;
2644 r.bottom = cxWidth;
2646 hDC_off = CreateCompatibleDC(hdc);
2647 hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth);
2648 if (hDC_off && hB_off) {
2649 hOld = SelectObject(hDC_off, hB_off);
2650 FillRect(hDC_off, &r, hbr);
2654 if (hMemDC && (!DoOffscreen || (hDC_off && hB_off)))
2656 HBITMAP hXorBits, hAndBits;
2657 COLORREF oldFg, oldBg;
2658 INT nStretchMode;
2660 nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
2662 hXorBits = CreateBitmap ( ptr->nWidth, ptr->nHeight,
2663 ptr->bPlanes, ptr->bBitsPerPixel,
2664 (char *)(ptr + 1)
2665 + ptr->nHeight *
2666 get_bitmap_width_bytes(ptr->nWidth,1) );
2667 hAndBits = CreateBitmap ( ptr->nWidth, ptr->nHeight,
2668 1, 1, (char *)(ptr+1) );
2669 oldFg = SetTextColor( hdc, RGB(0,0,0) );
2670 oldBg = SetBkColor( hdc, RGB(255,255,255) );
2672 if (hXorBits && hAndBits)
2674 HBITMAP hBitTemp = SelectObject( hMemDC, hAndBits );
2675 if (flags & DI_MASK)
2677 if (DoOffscreen)
2678 StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
2679 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
2680 else
2681 StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
2682 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
2684 SelectObject( hMemDC, hXorBits );
2685 if (flags & DI_IMAGE)
2687 if (DoOffscreen)
2688 StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
2689 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
2690 else
2691 StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
2692 hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
2694 SelectObject( hMemDC, hBitTemp );
2695 result = TRUE;
2698 SetTextColor( hdc, oldFg );
2699 SetBkColor( hdc, oldBg );
2700 if (hXorBits) DeleteObject( hXorBits );
2701 if (hAndBits) DeleteObject( hAndBits );
2702 SetStretchBltMode (hdc, nStretchMode);
2703 if (DoOffscreen) {
2704 BitBlt(hdc, x0, y0, cxWidth, cyWidth, hDC_off, 0, 0, SRCCOPY);
2705 SelectObject(hDC_off, hOld);
2708 if (hMemDC) DeleteDC( hMemDC );
2709 if (hDC_off) DeleteDC(hDC_off);
2710 if (hB_off) DeleteObject(hB_off);
2711 GlobalUnlock16(HICON_16(hIcon));
2712 return result;
2715 /***********************************************************************
2716 * DIB_FixColorsToLoadflags
2718 * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
2719 * are in loadflags
2721 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
2723 int colors;
2724 COLORREF c_W, c_S, c_F, c_L, c_C;
2725 int incr,i;
2726 RGBQUAD *ptr;
2727 int bitmap_type;
2728 LONG width;
2729 LONG height;
2730 WORD bpp;
2731 DWORD compr;
2733 if (((bitmap_type = DIB_GetBitmapInfo((BITMAPINFOHEADER*) bmi, &width, &height, &bpp, &compr)) == -1))
2735 WARN_(resource)("Invalid bitmap\n");
2736 return;
2739 if (bpp > 8) return;
2741 if (bitmap_type == 0) /* BITMAPCOREHEADER */
2743 incr = 3;
2744 colors = 1 << bpp;
2746 else
2748 incr = 4;
2749 colors = bmi->bmiHeader.biClrUsed;
2750 if (colors > 256) colors = 256;
2751 if (!colors && (bpp <= 8)) colors = 1 << bpp;
2754 c_W = GetSysColor(COLOR_WINDOW);
2755 c_S = GetSysColor(COLOR_3DSHADOW);
2756 c_F = GetSysColor(COLOR_3DFACE);
2757 c_L = GetSysColor(COLOR_3DLIGHT);
2759 if (loadflags & LR_LOADTRANSPARENT) {
2760 switch (bpp) {
2761 case 1: pix = pix >> 7; break;
2762 case 4: pix = pix >> 4; break;
2763 case 8: break;
2764 default:
2765 WARN_(resource)("(%d): Unsupported depth\n", bpp);
2766 return;
2768 if (pix >= colors) {
2769 WARN_(resource)("pixel has color index greater than biClrUsed!\n");
2770 return;
2772 if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
2773 ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
2774 ptr->rgbBlue = GetBValue(c_W);
2775 ptr->rgbGreen = GetGValue(c_W);
2776 ptr->rgbRed = GetRValue(c_W);
2778 if (loadflags & LR_LOADMAP3DCOLORS)
2779 for (i=0; i<colors; i++) {
2780 ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
2781 c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
2782 if (c_C == RGB(128, 128, 128)) {
2783 ptr->rgbRed = GetRValue(c_S);
2784 ptr->rgbGreen = GetGValue(c_S);
2785 ptr->rgbBlue = GetBValue(c_S);
2786 } else if (c_C == RGB(192, 192, 192)) {
2787 ptr->rgbRed = GetRValue(c_F);
2788 ptr->rgbGreen = GetGValue(c_F);
2789 ptr->rgbBlue = GetBValue(c_F);
2790 } else if (c_C == RGB(223, 223, 223)) {
2791 ptr->rgbRed = GetRValue(c_L);
2792 ptr->rgbGreen = GetGValue(c_L);
2793 ptr->rgbBlue = GetBValue(c_L);
2799 /**********************************************************************
2800 * BITMAP_Load
2802 static HBITMAP BITMAP_Load( HINSTANCE instance, LPCWSTR name,
2803 INT desiredx, INT desiredy, UINT loadflags )
2805 HBITMAP hbitmap = 0, orig_bm;
2806 HRSRC hRsrc;
2807 HGLOBAL handle;
2808 char *ptr = NULL;
2809 BITMAPINFO *info, *fix_info = NULL, *scaled_info = NULL;
2810 int size;
2811 BYTE pix;
2812 char *bits;
2813 LONG width, height, new_width, new_height;
2814 WORD bpp_dummy;
2815 DWORD compr_dummy;
2816 INT bm_type;
2817 HDC screen_mem_dc = NULL;
2819 if (!(loadflags & LR_LOADFROMFILE))
2821 if (!instance)
2823 /* OEM bitmap: try to load the resource from user32.dll */
2824 instance = user32_module;
2827 if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
2828 if (!(handle = LoadResource( instance, hRsrc ))) return 0;
2830 if ((info = (BITMAPINFO *)LockResource( handle )) == NULL) return 0;
2832 else
2834 BITMAPFILEHEADER * bmfh;
2836 if (!(ptr = map_fileW( name, NULL ))) return 0;
2837 info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
2838 bmfh = (BITMAPFILEHEADER *)ptr;
2839 if (!( bmfh->bfType == 0x4d42 /* 'BM' */ &&
2840 bmfh->bfReserved1 == 0 &&
2841 bmfh->bfReserved2 == 0))
2843 WARN("Invalid/unsupported bitmap format!\n");
2844 UnmapViewOfFile( ptr );
2845 return 0;
2849 size = bitmap_info_size(info, DIB_RGB_COLORS);
2850 fix_info = HeapAlloc(GetProcessHeap(), 0, size);
2851 scaled_info = HeapAlloc(GetProcessHeap(), 0, size);
2853 if (!fix_info || !scaled_info) goto end;
2854 memcpy(fix_info, info, size);
2856 pix = *((LPBYTE)info + size);
2857 DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
2859 memcpy(scaled_info, fix_info, size);
2860 bm_type = DIB_GetBitmapInfo( &fix_info->bmiHeader, &width, &height,
2861 &bpp_dummy, &compr_dummy);
2862 if(desiredx != 0)
2863 new_width = desiredx;
2864 else
2865 new_width = width;
2867 if(desiredy != 0)
2868 new_height = height > 0 ? desiredy : -desiredy;
2869 else
2870 new_height = height;
2872 if(bm_type == 0)
2874 BITMAPCOREHEADER *core = (BITMAPCOREHEADER *)&scaled_info->bmiHeader;
2875 core->bcWidth = new_width;
2876 core->bcHeight = new_height;
2878 else
2880 scaled_info->bmiHeader.biWidth = new_width;
2881 scaled_info->bmiHeader.biHeight = new_height;
2884 if (new_height < 0) new_height = -new_height;
2886 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2887 if (!(screen_mem_dc = CreateCompatibleDC( screen_dc ))) goto end;
2889 bits = (char *)info + size;
2891 if (loadflags & LR_CREATEDIBSECTION)
2893 scaled_info->bmiHeader.biCompression = 0; /* DIBSection can't be compressed */
2894 hbitmap = CreateDIBSection(screen_dc, scaled_info, DIB_RGB_COLORS, NULL, 0, 0);
2896 else
2898 if (is_dib_monochrome(fix_info))
2899 hbitmap = CreateBitmap(new_width, new_height, 1, 1, NULL);
2900 else
2901 hbitmap = CreateCompatibleBitmap(screen_dc, new_width, new_height);
2904 orig_bm = SelectObject(screen_mem_dc, hbitmap);
2905 StretchDIBits(screen_mem_dc, 0, 0, new_width, new_height, 0, 0, width, height, bits, fix_info, DIB_RGB_COLORS, SRCCOPY);
2906 SelectObject(screen_mem_dc, orig_bm);
2908 end:
2909 if (screen_mem_dc) DeleteDC(screen_mem_dc);
2910 HeapFree(GetProcessHeap(), 0, scaled_info);
2911 HeapFree(GetProcessHeap(), 0, fix_info);
2912 if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
2914 return hbitmap;
2917 /**********************************************************************
2918 * LoadImageA (USER32.@)
2920 * See LoadImageW.
2922 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2923 INT desiredx, INT desiredy, UINT loadflags)
2925 HANDLE res;
2926 LPWSTR u_name;
2928 if (!HIWORD(name))
2929 return LoadImageW(hinst, (LPCWSTR)name, type, desiredx, desiredy, loadflags);
2931 __TRY {
2932 DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2933 u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2934 MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2936 __EXCEPT_PAGE_FAULT {
2937 SetLastError( ERROR_INVALID_PARAMETER );
2938 return 0;
2940 __ENDTRY
2941 res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2942 HeapFree(GetProcessHeap(), 0, u_name);
2943 return res;
2947 /******************************************************************************
2948 * LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2950 * PARAMS
2951 * hinst [I] Handle of instance that contains image
2952 * name [I] Name of image
2953 * type [I] Type of image
2954 * desiredx [I] Desired width
2955 * desiredy [I] Desired height
2956 * loadflags [I] Load flags
2958 * RETURNS
2959 * Success: Handle to newly loaded image
2960 * Failure: NULL
2962 * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2964 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2965 INT desiredx, INT desiredy, UINT loadflags )
2967 TRACE_(resource)("(%p,%s,%d,%d,%d,0x%08x)\n",
2968 hinst,debugstr_w(name),type,desiredx,desiredy,loadflags);
2970 if (loadflags & LR_DEFAULTSIZE) {
2971 if (type == IMAGE_ICON) {
2972 if (!desiredx) desiredx = GetSystemMetrics(SM_CXICON);
2973 if (!desiredy) desiredy = GetSystemMetrics(SM_CYICON);
2974 } else if (type == IMAGE_CURSOR) {
2975 if (!desiredx) desiredx = GetSystemMetrics(SM_CXCURSOR);
2976 if (!desiredy) desiredy = GetSystemMetrics(SM_CYCURSOR);
2979 if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
2980 switch (type) {
2981 case IMAGE_BITMAP:
2982 return BITMAP_Load( hinst, name, desiredx, desiredy, loadflags );
2984 case IMAGE_ICON:
2985 if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2986 if (screen_dc)
2988 UINT palEnts = GetSystemPaletteEntries(screen_dc, 0, 0, NULL);
2989 if (palEnts == 0) palEnts = 256;
2990 return CURSORICON_Load(hinst, name, desiredx, desiredy,
2991 palEnts, FALSE, loadflags);
2993 break;
2995 case IMAGE_CURSOR:
2996 return CURSORICON_Load(hinst, name, desiredx, desiredy,
2997 1, TRUE, loadflags);
2999 return 0;
3002 /******************************************************************************
3003 * CopyImage (USER32.@) Creates new image and copies attributes to it
3005 * PARAMS
3006 * hnd [I] Handle to image to copy
3007 * type [I] Type of image to copy
3008 * desiredx [I] Desired width of new image
3009 * desiredy [I] Desired height of new image
3010 * flags [I] Copy flags
3012 * RETURNS
3013 * Success: Handle to newly created image
3014 * Failure: NULL
3016 * BUGS
3017 * Only Windows NT 4.0 supports the LR_COPYRETURNORG flag for bitmaps,
3018 * all other versions (95/2000/XP have been tested) ignore it.
3020 * NOTES
3021 * If LR_CREATEDIBSECTION is absent, the copy will be monochrome for
3022 * a monochrome source bitmap or if LR_MONOCHROME is present, otherwise
3023 * the copy will have the same depth as the screen.
3024 * The content of the image will only be copied if the bit depth of the
3025 * original image is compatible with the bit depth of the screen, or
3026 * if the source is a DIB section.
3027 * The LR_MONOCHROME flag is ignored if LR_CREATEDIBSECTION is present.
3029 HANDLE WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
3030 INT desiredy, UINT flags )
3032 TRACE("hnd=%p, type=%u, desiredx=%d, desiredy=%d, flags=%x\n",
3033 hnd, type, desiredx, desiredy, flags);
3035 switch (type)
3037 case IMAGE_BITMAP:
3039 HBITMAP res = NULL;
3040 DIBSECTION ds;
3041 int objSize;
3042 BITMAPINFO * bi;
3044 objSize = GetObjectW( hnd, sizeof(ds), &ds );
3045 if (!objSize) return 0;
3046 if ((desiredx < 0) || (desiredy < 0)) return 0;
3048 if (flags & LR_COPYFROMRESOURCE)
3050 FIXME("The flag LR_COPYFROMRESOURCE is not implemented for bitmaps\n");
3053 if (desiredx == 0) desiredx = ds.dsBm.bmWidth;
3054 if (desiredy == 0) desiredy = ds.dsBm.bmHeight;
3056 /* Allocate memory for a BITMAPINFOHEADER structure and a
3057 color table. The maximum number of colors in a color table
3058 is 256 which corresponds to a bitmap with depth 8.
3059 Bitmaps with higher depths don't have color tables. */
3060 bi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
3061 if (!bi) return 0;
3063 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
3064 bi->bmiHeader.biPlanes = ds.dsBm.bmPlanes;
3065 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
3066 bi->bmiHeader.biCompression = BI_RGB;
3068 if (flags & LR_CREATEDIBSECTION)
3070 /* Create a DIB section. LR_MONOCHROME is ignored */
3071 void * bits;
3072 HDC dc = CreateCompatibleDC(NULL);
3074 if (objSize == sizeof(DIBSECTION))
3076 /* The source bitmap is a DIB.
3077 Get its attributes to create an exact copy */
3078 memcpy(bi, &ds.dsBmih, sizeof(BITMAPINFOHEADER));
3081 /* Get the color table or the color masks */
3082 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3084 bi->bmiHeader.biWidth = desiredx;
3085 bi->bmiHeader.biHeight = desiredy;
3086 bi->bmiHeader.biSizeImage = 0;
3088 res = CreateDIBSection(dc, bi, DIB_RGB_COLORS, &bits, NULL, 0);
3089 DeleteDC(dc);
3091 else
3093 /* Create a device-dependent bitmap */
3095 BOOL monochrome = (flags & LR_MONOCHROME);
3097 if (objSize == sizeof(DIBSECTION))
3099 /* The source bitmap is a DIB section.
3100 Get its attributes */
3101 HDC dc = CreateCompatibleDC(NULL);
3102 bi->bmiHeader.biSize = sizeof(bi->bmiHeader);
3103 bi->bmiHeader.biBitCount = ds.dsBm.bmBitsPixel;
3104 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3105 DeleteDC(dc);
3107 if (!monochrome && ds.dsBm.bmBitsPixel == 1)
3109 /* Look if the colors of the DIB are black and white */
3111 monochrome =
3112 (bi->bmiColors[0].rgbRed == 0xff
3113 && bi->bmiColors[0].rgbGreen == 0xff
3114 && bi->bmiColors[0].rgbBlue == 0xff
3115 && bi->bmiColors[0].rgbReserved == 0
3116 && bi->bmiColors[1].rgbRed == 0
3117 && bi->bmiColors[1].rgbGreen == 0
3118 && bi->bmiColors[1].rgbBlue == 0
3119 && bi->bmiColors[1].rgbReserved == 0)
3121 (bi->bmiColors[0].rgbRed == 0
3122 && bi->bmiColors[0].rgbGreen == 0
3123 && bi->bmiColors[0].rgbBlue == 0
3124 && bi->bmiColors[0].rgbReserved == 0
3125 && bi->bmiColors[1].rgbRed == 0xff
3126 && bi->bmiColors[1].rgbGreen == 0xff
3127 && bi->bmiColors[1].rgbBlue == 0xff
3128 && bi->bmiColors[1].rgbReserved == 0);
3131 else if (!monochrome)
3133 monochrome = ds.dsBm.bmBitsPixel == 1;
3136 if (monochrome)
3138 res = CreateBitmap(desiredx, desiredy, 1, 1, NULL);
3140 else
3142 HDC screenDC = GetDC(NULL);
3143 res = CreateCompatibleBitmap(screenDC, desiredx, desiredy);
3144 ReleaseDC(NULL, screenDC);
3148 if (res)
3150 /* Only copy the bitmap if it's a DIB section or if it's
3151 compatible to the screen */
3152 BOOL copyContents;
3154 if (objSize == sizeof(DIBSECTION))
3156 copyContents = TRUE;
3158 else
3160 HDC screenDC = GetDC(NULL);
3161 int screen_depth = GetDeviceCaps(screenDC, BITSPIXEL);
3162 ReleaseDC(NULL, screenDC);
3164 copyContents = (ds.dsBm.bmBitsPixel == 1 || ds.dsBm.bmBitsPixel == screen_depth);
3167 if (copyContents)
3169 /* The source bitmap may already be selected in a device context,
3170 use GetDIBits/StretchDIBits and not StretchBlt */
3172 HDC dc;
3173 void * bits;
3175 dc = CreateCompatibleDC(NULL);
3177 bi->bmiHeader.biWidth = ds.dsBm.bmWidth;
3178 bi->bmiHeader.biHeight = ds.dsBm.bmHeight;
3179 bi->bmiHeader.biSizeImage = 0;
3180 bi->bmiHeader.biClrUsed = 0;
3181 bi->bmiHeader.biClrImportant = 0;
3183 /* Fill in biSizeImage */
3184 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, NULL, bi, DIB_RGB_COLORS);
3185 bits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bi->bmiHeader.biSizeImage);
3187 if (bits)
3189 HBITMAP oldBmp;
3191 /* Get the image bits of the source bitmap */
3192 GetDIBits(dc, hnd, 0, ds.dsBm.bmHeight, bits, bi, DIB_RGB_COLORS);
3194 /* Copy it to the destination bitmap */
3195 oldBmp = SelectObject(dc, res);
3196 StretchDIBits(dc, 0, 0, desiredx, desiredy,
3197 0, 0, ds.dsBm.bmWidth, ds.dsBm.bmHeight,
3198 bits, bi, DIB_RGB_COLORS, SRCCOPY);
3199 SelectObject(dc, oldBmp);
3201 HeapFree(GetProcessHeap(), 0, bits);
3204 DeleteDC(dc);
3207 if (flags & LR_COPYDELETEORG)
3209 DeleteObject(hnd);
3212 HeapFree(GetProcessHeap(), 0, bi);
3213 return res;
3215 case IMAGE_ICON:
3216 return CURSORICON_ExtCopy(hnd,type, desiredx, desiredy, flags);
3217 case IMAGE_CURSOR:
3218 /* Should call CURSORICON_ExtCopy but more testing
3219 * needs to be done before we change this
3221 if (flags) FIXME("Flags are ignored\n");
3222 return CopyCursor(hnd);
3224 return 0;
3228 /******************************************************************************
3229 * LoadBitmapW (USER32.@) Loads bitmap from the executable file
3231 * RETURNS
3232 * Success: Handle to specified bitmap
3233 * Failure: NULL
3235 HBITMAP WINAPI LoadBitmapW(
3236 HINSTANCE instance, /* [in] Handle to application instance */
3237 LPCWSTR name) /* [in] Address of bitmap resource name */
3239 return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
3242 /**********************************************************************
3243 * LoadBitmapA (USER32.@)
3245 * See LoadBitmapW.
3247 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
3249 return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );