Remove obsolete status files for direct3D, directsound, and
[wine] / windows / cursoricon.c
1 /*
2  * Cursor and icon support
3  *
4  * Copyright 1995 Alexandre Julliard
5  *           1996 Martin Von Loewis
6  *           1997 Alex Korobka
7  *           1998 Turchanov Sergey
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 /*
25  * Theory:
26  *
27  * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwui/html/msdn_icons.asp
28  *
29  * Cursors and icons are stored in a global heap block, with the
30  * following layout:
31  *
32  * CURSORICONINFO info;
33  * BYTE[]         ANDbits;
34  * BYTE[]         XORbits;
35  *
36  * The bits structures are in the format of a device-dependent bitmap.
37  *
38  * This layout is very sub-optimal, as the bitmap bits are stored in
39  * the X client instead of in the server like other bitmaps; however,
40  * some programs (notably Paint Brush) expect to be able to manipulate
41  * the bits directly :-(
42  *
43  * FIXME: what are we going to do with animation and color (bpp > 1) cursors ?!
44  */
45
46 #include <stdarg.h>
47 #include <string.h>
48 #include <stdlib.h>
49
50 #include "windef.h"
51 #include "winbase.h"
52 #include "wingdi.h"
53 #include "wownt32.h"
54 #include "winerror.h"
55 #include "ntstatus.h"
56 #include "excpt.h"
57 #include "wine/winbase16.h"
58 #include "wine/winuser16.h"
59 #include "wine/exception.h"
60 #include "bitmap.h"
61 #include "cursoricon.h"
62 #include "module.h"
63 #include "wine/debug.h"
64 #include "user.h"
65 #include "message.h"
66
67 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
68 WINE_DECLARE_DEBUG_CHANNEL(icon);
69 WINE_DECLARE_DEBUG_CHANNEL(resource);
70
71
72 static RECT CURSOR_ClipRect;       /* Cursor clipping rect */
73
74 static HDC screen_dc;
75
76 static const WCHAR DISPLAYW[] = {'D','I','S','P','L','A','Y',0};
77
78 /**********************************************************************
79  * ICONCACHE for cursors/icons loaded with LR_SHARED.
80  *
81  * FIXME: This should not be allocated on the system heap, but on a
82  *        subsystem-global heap (i.e. one for all Win16 processes,
83  *        and one for each Win32 process).
84  */
85 typedef struct tagICONCACHE
86 {
87     struct tagICONCACHE *next;
88
89     HMODULE              hModule;
90     HRSRC                hRsrc;
91     HRSRC                hGroupRsrc;
92     HICON                hIcon;
93
94     INT                  count;
95
96 } ICONCACHE;
97
98 static ICONCACHE *IconAnchor = NULL;
99
100 static CRITICAL_SECTION IconCrst;
101 static CRITICAL_SECTION_DEBUG critsect_debug =
102 {
103     0, 0, &IconCrst,
104     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
105       0, 0, { 0, (DWORD)(__FILE__ ": IconCrst") }
106 };
107 static CRITICAL_SECTION IconCrst = { &critsect_debug, -1, 0, 0, 0, 0 };
108
109 static WORD ICON_HOTSPOT = 0x4242;
110
111
112 /***********************************************************************
113  *             map_fileW
114  *
115  * Helper function to map a file to memory:
116  *  name                        -       file name
117  *  [RETURN] ptr                -       pointer to mapped file
118  */
119 static void *map_fileW( LPCWSTR name )
120 {
121     HANDLE hFile, hMapping;
122     LPVOID ptr = NULL;
123
124     hFile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL,
125                          OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0 );
126     if (hFile != INVALID_HANDLE_VALUE)
127     {
128         hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
129         CloseHandle( hFile );
130         if (hMapping)
131         {
132             ptr = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
133             CloseHandle( hMapping );
134         }
135     }
136     return ptr;
137 }
138
139
140 /***********************************************************************
141  *           get_bitmap_width_bytes
142  *
143  * Return number of bytes taken by a scanline of 16-bit aligned Windows DDB
144  * data.
145  */
146 static int get_bitmap_width_bytes( int width, int bpp )
147 {
148     switch(bpp)
149     {
150     case 1:
151         return 2 * ((width+15) / 16);
152     case 4:
153         return 2 * ((width+3) / 4);
154     case 24:
155         width *= 3;
156         /* fall through */
157     case 8:
158         return width + (width & 1);
159     case 16:
160     case 15:
161         return width * 2;
162     case 32:
163         return width * 4;
164     default:
165         WARN("Unknown depth %d, please report.\n", bpp );
166     }
167     return -1;
168 }
169
170
171 /**********************************************************************
172  *          CURSORICON_FindSharedIcon
173  */
174 static HICON CURSORICON_FindSharedIcon( HMODULE hModule, HRSRC hRsrc )
175 {
176     HICON hIcon = 0;
177     ICONCACHE *ptr;
178
179     EnterCriticalSection( &IconCrst );
180
181     for ( ptr = IconAnchor; ptr; ptr = ptr->next )
182         if ( ptr->hModule == hModule && ptr->hRsrc == hRsrc )
183         {
184             ptr->count++;
185             hIcon = ptr->hIcon;
186             break;
187         }
188
189     LeaveCriticalSection( &IconCrst );
190
191     return hIcon;
192 }
193
194 /*************************************************************************
195  * CURSORICON_FindCache
196  *
197  * Given a handle, find the corresponding cache element
198  *
199  * PARAMS
200  *      Handle     [I] handle to an Image
201  *
202  * RETURNS
203  *     Success: The cache entry
204  *     Failure: NULL
205  *
206  */
207 static ICONCACHE* CURSORICON_FindCache(HICON hIcon)
208 {
209     ICONCACHE *ptr;
210     ICONCACHE *pRet=NULL;
211     BOOL IsFound = FALSE;
212     int count;
213
214     EnterCriticalSection( &IconCrst );
215
216     for (count = 0, ptr = IconAnchor; ptr != NULL && !IsFound; ptr = ptr->next, count++ )
217     {
218         if ( hIcon == ptr->hIcon )
219         {
220             IsFound = TRUE;
221             pRet = ptr;
222         }
223     }
224
225     LeaveCriticalSection( &IconCrst );
226
227     return pRet;
228 }
229
230 /**********************************************************************
231  *          CURSORICON_AddSharedIcon
232  */
233 static void CURSORICON_AddSharedIcon( HMODULE hModule, HRSRC hRsrc, HRSRC hGroupRsrc, HICON hIcon )
234 {
235     ICONCACHE *ptr = HeapAlloc( GetProcessHeap(), 0, sizeof(ICONCACHE) );
236     if ( !ptr ) return;
237
238     ptr->hModule = hModule;
239     ptr->hRsrc   = hRsrc;
240     ptr->hIcon  = hIcon;
241     ptr->hGroupRsrc = hGroupRsrc;
242     ptr->count   = 1;
243
244     EnterCriticalSection( &IconCrst );
245     ptr->next    = IconAnchor;
246     IconAnchor   = ptr;
247     LeaveCriticalSection( &IconCrst );
248 }
249
250 /**********************************************************************
251  *          CURSORICON_DelSharedIcon
252  */
253 static INT CURSORICON_DelSharedIcon( HICON hIcon )
254 {
255     INT count = -1;
256     ICONCACHE *ptr;
257
258     EnterCriticalSection( &IconCrst );
259
260     for ( ptr = IconAnchor; ptr; ptr = ptr->next )
261         if ( ptr->hIcon == hIcon )
262         {
263             if ( ptr->count > 0 ) ptr->count--;
264             count = ptr->count;
265             break;
266         }
267
268     LeaveCriticalSection( &IconCrst );
269
270     return count;
271 }
272
273 /**********************************************************************
274  *          CURSORICON_FreeModuleIcons
275  */
276 void CURSORICON_FreeModuleIcons( HMODULE16 hMod16 )
277 {
278     ICONCACHE **ptr = &IconAnchor;
279     HMODULE hModule = HMODULE_32(GetExePtr( hMod16 ));
280
281     EnterCriticalSection( &IconCrst );
282
283     while ( *ptr )
284     {
285         if ( (*ptr)->hModule == hModule )
286         {
287             ICONCACHE *freePtr = *ptr;
288             *ptr = freePtr->next;
289
290             GlobalFree16(HICON_16(freePtr->hIcon));
291             HeapFree( GetProcessHeap(), 0, freePtr );
292             continue;
293         }
294         ptr = &(*ptr)->next;
295     }
296
297     LeaveCriticalSection( &IconCrst );
298 }
299
300 /**********************************************************************
301  *          CURSORICON_FindBestIcon
302  *
303  * Find the icon closest to the requested size and number of colors.
304  */
305 static CURSORICONDIRENTRY *CURSORICON_FindBestIcon( CURSORICONDIR *dir, int width,
306                                               int height, int colors )
307 {
308     int i;
309     CURSORICONDIRENTRY *entry, *bestEntry = NULL;
310     UINT iTotalDiff, iXDiff=0, iYDiff=0, iColorDiff;
311     UINT iTempXDiff, iTempYDiff, iTempColorDiff;
312
313     if (dir->idCount < 1)
314     {
315         WARN_(icon)("Empty directory!\n" );
316         return NULL;
317     }
318     if (dir->idCount == 1) return &dir->idEntries[0];  /* No choice... */
319
320     /* Find Best Fit */
321     iTotalDiff = 0xFFFFFFFF;
322     iColorDiff = 0xFFFFFFFF;
323     for (i = 0, entry = &dir->idEntries[0]; i < dir->idCount; i++,entry++)
324     {
325         iTempXDiff = abs(width - entry->ResInfo.icon.bWidth);
326         iTempYDiff = abs(height - entry->ResInfo.icon.bHeight);
327
328         if(iTotalDiff > (iTempXDiff + iTempYDiff))
329         {
330             iXDiff = iTempXDiff;
331             iYDiff = iTempYDiff;
332             iTotalDiff = iXDiff + iYDiff;
333         }
334     }
335
336     /* Find Best Colors for Best Fit */
337     for (i = 0, entry = &dir->idEntries[0]; i < dir->idCount; i++,entry++)
338     {
339         if(abs(width - entry->ResInfo.icon.bWidth) == iXDiff &&
340            abs(height - entry->ResInfo.icon.bHeight) == iYDiff)
341         {
342             iTempColorDiff = abs(colors - (1<<entry->wBitCount));
343             if(iColorDiff > iTempColorDiff)
344             {
345                 bestEntry = entry;
346                 iColorDiff = iTempColorDiff;
347             }
348         }
349     }
350
351     return bestEntry;
352 }
353
354
355 /**********************************************************************
356  *          CURSORICON_FindBestCursor
357  *
358  * Find the cursor closest to the requested size.
359  * FIXME: parameter 'color' ignored and entries with more than 1 bpp
360  *        ignored too
361  */
362 static CURSORICONDIRENTRY *CURSORICON_FindBestCursor( CURSORICONDIR *dir,
363                                                   int width, int height, int color)
364 {
365     int i, maxwidth, maxheight;
366     CURSORICONDIRENTRY *entry, *bestEntry = NULL;
367
368     if (dir->idCount < 1)
369     {
370         WARN_(cursor)("Empty directory!\n" );
371         return NULL;
372     }
373     if (dir->idCount == 1) return &dir->idEntries[0]; /* No choice... */
374
375     /* Double height to account for AND and XOR masks */
376
377     height *= 2;
378
379     /* First find the largest one smaller than or equal to the requested size*/
380
381     maxwidth = maxheight = 0;
382     for(i = 0,entry = &dir->idEntries[0]; i < dir->idCount; i++,entry++)
383         if ((entry->ResInfo.cursor.wWidth <= width) && (entry->ResInfo.cursor.wHeight <= height) &&
384             (entry->ResInfo.cursor.wWidth > maxwidth) && (entry->ResInfo.cursor.wHeight > maxheight) &&
385             (entry->wBitCount == 1))
386         {
387             bestEntry = entry;
388             maxwidth  = entry->ResInfo.cursor.wWidth;
389             maxheight = entry->ResInfo.cursor.wHeight;
390         }
391     if (bestEntry) return bestEntry;
392
393     /* Now find the smallest one larger than the requested size */
394
395     maxwidth = maxheight = 255;
396     for(i = 0,entry = &dir->idEntries[0]; i < dir->idCount; i++,entry++)
397         if ((entry->ResInfo.cursor.wWidth < maxwidth) && (entry->ResInfo.cursor.wHeight < maxheight) &&
398             (entry->wBitCount == 1))
399         {
400             bestEntry = entry;
401             maxwidth  = entry->ResInfo.cursor.wWidth;
402             maxheight = entry->ResInfo.cursor.wHeight;
403         }
404
405     return bestEntry;
406 }
407
408 /*********************************************************************
409  * The main purpose of this function is to create fake resource directory
410  * and fake resource entries. There are several reasons for this:
411  *      -       CURSORICONDIR and CURSORICONFILEDIR differ in sizes and their
412  *              fields
413  *      There are some "bad" cursor files which do not have
414  *              bColorCount initialized but instead one must read this info
415  *              directly from corresponding DIB sections
416  * Note: wResId is index to array of pointer returned in ptrs (origin is 1)
417  */
418 static BOOL CURSORICON_SimulateLoadingFromResourceW( LPWSTR filename, BOOL fCursor,
419                                                 CURSORICONDIR **res, LPBYTE **ptr)
420 {
421     LPBYTE   _free;
422     CURSORICONFILEDIR *bits;
423     int      entries, size, i;
424
425     *res = NULL;
426     *ptr = NULL;
427     if (!(bits = map_fileW( filename ))) return FALSE;
428
429     /* FIXME: test for inimated icons
430      * hack to load the first icon from the *.ani file
431      */
432     if ( *(LPDWORD)bits==0x46464952 ) /* "RIFF" */
433     { LPBYTE pos = (LPBYTE) bits;
434       FIXME_(cursor)("Animated icons not correctly implemented! %p \n", bits);
435
436       for (;;)
437       { if (*(LPDWORD)pos==0x6e6f6369)          /* "icon" */
438         { FIXME_(cursor)("icon entry found! %p\n", bits);
439           pos+=4;
440           if ( !*(LPWORD) pos==0x2fe)           /* iconsize */
441           { goto fail;
442           }
443           bits=(CURSORICONFILEDIR*)(pos+4);
444           FIXME_(cursor)("icon size ok. offset=%p \n", bits);
445           break;
446         }
447         pos+=2;
448         if (pos>=(LPBYTE)bits+766) goto fail;
449       }
450     }
451     if (!(entries = bits->idCount)) goto fail;
452     size = sizeof(CURSORICONDIR) + sizeof(CURSORICONDIRENTRY) * (entries - 1);
453     _free = (LPBYTE) size;
454
455     for (i=0; i < entries; i++)
456       size += bits->idEntries[i].dwDIBSize + (fCursor ? sizeof(POINT16): 0);
457
458     if (!(*ptr = HeapAlloc( GetProcessHeap(), 0,
459                             entries * sizeof (CURSORICONDIRENTRY*)))) goto fail;
460     if (!(*res = HeapAlloc( GetProcessHeap(), 0, size))) goto fail;
461
462     _free = (LPBYTE)(*res) + (int)_free;
463     memcpy((*res), bits, 6);
464     for (i=0; i<entries; i++)
465     {
466       ((LPBYTE*)(*ptr))[i] = _free;
467       if (fCursor) {
468         (*res)->idEntries[i].ResInfo.cursor.wWidth=bits->idEntries[i].bWidth;
469         (*res)->idEntries[i].ResInfo.cursor.wHeight=bits->idEntries[i].bHeight;
470         ((LPPOINT16)_free)->x=bits->idEntries[i].xHotspot;
471         ((LPPOINT16)_free)->y=bits->idEntries[i].yHotspot;
472         _free+=sizeof(POINT16);
473       } else {
474         (*res)->idEntries[i].ResInfo.icon.bWidth=bits->idEntries[i].bWidth;
475         (*res)->idEntries[i].ResInfo.icon.bHeight=bits->idEntries[i].bHeight;
476         (*res)->idEntries[i].ResInfo.icon.bColorCount = bits->idEntries[i].bColorCount;
477       }
478       (*res)->idEntries[i].wPlanes=1;
479       (*res)->idEntries[i].wBitCount = ((LPBITMAPINFOHEADER)((LPBYTE)bits +
480                                                    bits->idEntries[i].dwDIBOffset))->biBitCount;
481       (*res)->idEntries[i].dwBytesInRes = bits->idEntries[i].dwDIBSize;
482       (*res)->idEntries[i].wResId=i+1;
483
484       memcpy(_free,(LPBYTE)bits +bits->idEntries[i].dwDIBOffset,
485              (*res)->idEntries[i].dwBytesInRes);
486       _free += (*res)->idEntries[i].dwBytesInRes;
487     }
488     UnmapViewOfFile( bits );
489     return TRUE;
490 fail:
491     if (*res) HeapFree( GetProcessHeap(), 0, *res );
492     if (*ptr) HeapFree( GetProcessHeap(), 0, *ptr );
493     UnmapViewOfFile( bits );
494     return FALSE;
495 }
496
497
498 /**********************************************************************
499  *          CURSORICON_CreateFromResource
500  *
501  * Create a cursor or icon from in-memory resource template.
502  *
503  * FIXME: Convert to mono when cFlag is LR_MONOCHROME. Do something
504  *        with cbSize parameter as well.
505  */
506 static HICON CURSORICON_CreateFromResource( HMODULE16 hModule, HGLOBAL16 hObj, LPBYTE bits,
507                                                 UINT cbSize, BOOL bIcon, DWORD dwVersion,
508                                                 INT width, INT height, UINT loadflags )
509 {
510     static HDC hdcMem;
511     int sizeAnd, sizeXor;
512     HBITMAP hAndBits = 0, hXorBits = 0; /* error condition for later */
513     BITMAP bmpXor, bmpAnd;
514     POINT16 hotspot;
515     BITMAPINFO *bmi;
516     BOOL DoStretch;
517     INT size;
518
519     hotspot.x = ICON_HOTSPOT;
520     hotspot.y = ICON_HOTSPOT;
521
522     TRACE_(cursor)("%08x (%u bytes), ver %08x, %ix%i %s %s\n",
523                         (unsigned)bits, cbSize, (unsigned)dwVersion, width, height,
524                                   bIcon ? "icon" : "cursor", (loadflags & LR_MONOCHROME) ? "mono" : "" );
525     if (dwVersion == 0x00020000)
526     {
527         FIXME_(cursor)("\t2.xx resources are not supported\n");
528         return 0;
529     }
530
531     if (bIcon)
532         bmi = (BITMAPINFO *)bits;
533     else /* get the hotspot */
534     {
535         POINT16 *pt = (POINT16 *)bits;
536         hotspot = *pt;
537         bmi = (BITMAPINFO *)(pt + 1);
538     }
539     size = DIB_BitmapInfoSize( bmi, DIB_RGB_COLORS );
540
541     if (!width) width = bmi->bmiHeader.biWidth;
542     if (!height) height = bmi->bmiHeader.biHeight/2;
543     DoStretch = (bmi->bmiHeader.biHeight/2 != height) ||
544       (bmi->bmiHeader.biWidth != width);
545
546     /* Check bitmap header */
547
548     if ( (bmi->bmiHeader.biSize != sizeof(BITMAPCOREHEADER)) &&
549          (bmi->bmiHeader.biSize != sizeof(BITMAPINFOHEADER)  ||
550           bmi->bmiHeader.biCompression != BI_RGB) )
551     {
552           WARN_(cursor)("\tinvalid resource bitmap header.\n");
553           return 0;
554     }
555
556     if (!screen_dc) screen_dc = CreateDCA( "DISPLAY", NULL, NULL, NULL );
557     if (screen_dc)
558     {
559         BITMAPINFO* pInfo;
560
561         /* Make sure we have room for the monochrome bitmap later on.
562          * Note that BITMAPINFOINFO and BITMAPCOREHEADER are the same
563          * up to and including the biBitCount. In-memory icon resource
564          * format is as follows:
565          *
566          *   BITMAPINFOHEADER   icHeader  // DIB header
567          *   RGBQUAD         icColors[]   // Color table
568          *   BYTE            icXOR[]      // DIB bits for XOR mask
569          *   BYTE            icAND[]      // DIB bits for AND mask
570          */
571
572         if ((pInfo = (BITMAPINFO *)HeapAlloc( GetProcessHeap(), 0,
573           max(size, sizeof(BITMAPINFOHEADER) + 2*sizeof(RGBQUAD)))))
574         {
575             memcpy( pInfo, bmi, size );
576             pInfo->bmiHeader.biHeight /= 2;
577
578             /* Create the XOR bitmap */
579
580             if (DoStretch) {
581                 if(bIcon)
582                 {
583                     hXorBits = CreateCompatibleBitmap(screen_dc, width, height);
584                 }
585                 else
586                 {
587                     hXorBits = CreateBitmap(width, height, 1, 1, NULL);
588                 }
589                 if(hXorBits)
590                 {
591                 HBITMAP hOld;
592                 BOOL res = FALSE;
593
594                 if (!hdcMem) hdcMem = CreateCompatibleDC(screen_dc);
595                 if (hdcMem) {
596                     hOld = SelectObject(hdcMem, hXorBits);
597                     res = StretchDIBits(hdcMem, 0, 0, width, height, 0, 0,
598                                         bmi->bmiHeader.biWidth, bmi->bmiHeader.biHeight/2,
599                                         (char*)bmi + size, pInfo, DIB_RGB_COLORS, SRCCOPY);
600                     SelectObject(hdcMem, hOld);
601                 }
602                 if (!res) { DeleteObject(hXorBits); hXorBits = 0; }
603               }
604             } else hXorBits = CreateDIBitmap( screen_dc, &pInfo->bmiHeader,
605                 CBM_INIT, (char*)bmi + size, pInfo, DIB_RGB_COLORS );
606             if( hXorBits )
607             {
608                 char* xbits = (char *)bmi + size +
609                         DIB_GetDIBImageBytes(bmi->bmiHeader.biWidth,
610                                              bmi->bmiHeader.biHeight,
611                                              bmi->bmiHeader.biBitCount) / 2;
612
613                 pInfo->bmiHeader.biBitCount = 1;
614                 if (pInfo->bmiHeader.biSize == sizeof(BITMAPINFOHEADER))
615                 {
616                     RGBQUAD *rgb = pInfo->bmiColors;
617
618                     pInfo->bmiHeader.biClrUsed = pInfo->bmiHeader.biClrImportant = 2;
619                     rgb[0].rgbBlue = rgb[0].rgbGreen = rgb[0].rgbRed = 0x00;
620                     rgb[1].rgbBlue = rgb[1].rgbGreen = rgb[1].rgbRed = 0xff;
621                     rgb[0].rgbReserved = rgb[1].rgbReserved = 0;
622                 }
623                 else
624                 {
625                     RGBTRIPLE *rgb = (RGBTRIPLE *)(((BITMAPCOREHEADER *)pInfo) + 1);
626
627                     rgb[0].rgbtBlue = rgb[0].rgbtGreen = rgb[0].rgbtRed = 0x00;
628                     rgb[1].rgbtBlue = rgb[1].rgbtGreen = rgb[1].rgbtRed = 0xff;
629                 }
630
631                 /* Create the AND bitmap */
632
633             if (DoStretch) {
634               if ((hAndBits = CreateBitmap(width, height, 1, 1, NULL))) {
635                 HBITMAP hOld;
636                 BOOL res = FALSE;
637
638                 if (!hdcMem) hdcMem = CreateCompatibleDC(screen_dc);
639                 if (hdcMem) {
640                     hOld = SelectObject(hdcMem, hAndBits);
641                     res = StretchDIBits(hdcMem, 0, 0, width, height, 0, 0,
642                                         pInfo->bmiHeader.biWidth, pInfo->bmiHeader.biHeight,
643                                         xbits, pInfo, DIB_RGB_COLORS, SRCCOPY);
644                     SelectObject(hdcMem, hOld);
645                 }
646                 if (!res) { DeleteObject(hAndBits); hAndBits = 0; }
647               }
648             } else hAndBits = CreateDIBitmap( screen_dc, &pInfo->bmiHeader,
649               CBM_INIT, xbits, pInfo, DIB_RGB_COLORS );
650
651                 if( !hAndBits ) DeleteObject( hXorBits );
652             }
653             HeapFree( GetProcessHeap(), 0, pInfo );
654         }
655     }
656
657     if( !hXorBits || !hAndBits )
658     {
659         WARN_(cursor)("\tunable to create an icon bitmap.\n");
660         return 0;
661     }
662
663     /* Now create the CURSORICONINFO structure */
664     GetObjectA( hXorBits, sizeof(bmpXor), &bmpXor );
665     GetObjectA( hAndBits, sizeof(bmpAnd), &bmpAnd );
666     sizeXor = bmpXor.bmHeight * bmpXor.bmWidthBytes;
667     sizeAnd = bmpAnd.bmHeight * bmpAnd.bmWidthBytes;
668
669     if (hObj) hObj = GlobalReAlloc16( hObj,
670                      sizeof(CURSORICONINFO) + sizeXor + sizeAnd, GMEM_MOVEABLE );
671     if (!hObj) hObj = GlobalAlloc16( GMEM_MOVEABLE,
672                      sizeof(CURSORICONINFO) + sizeXor + sizeAnd );
673     if (hObj)
674     {
675         CURSORICONINFO *info;
676
677         /* Make it owned by the module */
678         if (hModule) hModule = GetExePtr(hModule);
679         FarSetOwner16( hObj, hModule );
680
681         info = (CURSORICONINFO *)GlobalLock16( hObj );
682         info->ptHotSpot.x   = hotspot.x;
683         info->ptHotSpot.y   = hotspot.y;
684         info->nWidth        = bmpXor.bmWidth;
685         info->nHeight       = bmpXor.bmHeight;
686         info->nWidthBytes   = bmpXor.bmWidthBytes;
687         info->bPlanes       = bmpXor.bmPlanes;
688         info->bBitsPerPixel = bmpXor.bmBitsPixel;
689
690         /* Transfer the bitmap bits to the CURSORICONINFO structure */
691
692         GetBitmapBits( hAndBits, sizeAnd, (char *)(info + 1) );
693         GetBitmapBits( hXorBits, sizeXor, (char *)(info + 1) + sizeAnd );
694         GlobalUnlock16( hObj );
695     }
696
697     DeleteObject( hAndBits );
698     DeleteObject( hXorBits );
699     return HICON_32((HICON16)hObj);
700 }
701
702
703 /**********************************************************************
704  *              CreateIconFromResource (USER32.@)
705  */
706 HICON WINAPI CreateIconFromResource( LPBYTE bits, UINT cbSize,
707                                            BOOL bIcon, DWORD dwVersion)
708 {
709     return CreateIconFromResourceEx( bits, cbSize, bIcon, dwVersion, 0,0,0);
710 }
711
712
713 /**********************************************************************
714  *              CreateIconFromResourceEx (USER32.@)
715  */
716 HICON WINAPI CreateIconFromResourceEx( LPBYTE bits, UINT cbSize,
717                                            BOOL bIcon, DWORD dwVersion,
718                                            INT width, INT height,
719                                            UINT cFlag )
720 {
721     return CURSORICON_CreateFromResource( 0, 0, bits, cbSize, bIcon, dwVersion,
722                                           width, height, cFlag );
723 }
724
725 /**********************************************************************
726  *          CURSORICON_Load
727  *
728  * Load a cursor or icon from resource or file.
729  */
730 static HICON CURSORICON_Load(HINSTANCE hInstance, LPCWSTR name,
731                              INT width, INT height, INT colors,
732                              BOOL fCursor, UINT loadflags)
733 {
734     HANDLE handle = 0;
735     HICON hIcon = 0;
736     HRSRC hRsrc;
737     CURSORICONDIR *dir;
738     CURSORICONDIRENTRY *dirEntry;
739     LPBYTE bits;
740
741     if ( loadflags & LR_LOADFROMFILE )    /* Load from file */
742     {
743         LPBYTE *ptr;
744         if (!CURSORICON_SimulateLoadingFromResourceW((LPWSTR)name, fCursor, &dir, &ptr))
745             return 0;
746         if (fCursor)
747             dirEntry = (CURSORICONDIRENTRY *)CURSORICON_FindBestCursor(dir, width, height, 1);
748         else
749             dirEntry = (CURSORICONDIRENTRY *)CURSORICON_FindBestIcon(dir, width, height, colors);
750         bits = ptr[dirEntry->wResId-1];
751         hIcon = CURSORICON_CreateFromResource( 0, 0, bits, dirEntry->dwBytesInRes,
752                                            !fCursor, 0x00030000, width, height, loadflags);
753         HeapFree( GetProcessHeap(), 0, dir );
754         HeapFree( GetProcessHeap(), 0, ptr );
755     }
756     else  /* Load from resource */
757     {
758         HRSRC hGroupRsrc;
759         WORD wResId;
760         DWORD dwBytesInRes;
761
762         if (!hInstance)  /* Load OEM cursor/icon */
763         {
764             if (!(hInstance = GetModuleHandleA( "user32.dll" ))) return 0;
765         }
766
767         /* Normalize hInstance (must be uniquely represented for icon cache) */
768
769         if (!HIWORD( hInstance ))
770             hInstance = HINSTANCE_32(GetExePtr( HINSTANCE_16(hInstance) ));
771
772         /* Get directory resource ID */
773
774         if (!(hRsrc = FindResourceW( hInstance, name,
775                                      (LPWSTR)(fCursor ? RT_GROUP_CURSOR : RT_GROUP_ICON) )))
776             return 0;
777         hGroupRsrc = hRsrc;
778
779         /* Find the best entry in the directory */
780
781         if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
782         if (!(dir = (CURSORICONDIR*)LockResource( handle ))) return 0;
783         if (fCursor)
784             dirEntry = (CURSORICONDIRENTRY *)CURSORICON_FindBestCursor( dir,
785                                                               width, height, 1);
786         else
787             dirEntry = (CURSORICONDIRENTRY *)CURSORICON_FindBestIcon( dir,
788                                                        width, height, colors );
789         if (!dirEntry) return 0;
790         wResId = dirEntry->wResId;
791         dwBytesInRes = dirEntry->dwBytesInRes;
792         FreeResource( handle );
793
794         /* Load the resource */
795
796         if (!(hRsrc = FindResourceW(hInstance,MAKEINTRESOURCEW(wResId),
797                                     (LPWSTR)(fCursor ? RT_CURSOR : RT_ICON) ))) return 0;
798
799         /* If shared icon, check whether it was already loaded */
800         if (    (loadflags & LR_SHARED)
801              && (hIcon = CURSORICON_FindSharedIcon( hInstance, hRsrc ) ) != 0 )
802             return hIcon;
803
804         if (!(handle = LoadResource( hInstance, hRsrc ))) return 0;
805         bits = (LPBYTE)LockResource( handle );
806         hIcon = CURSORICON_CreateFromResource( 0, 0, bits, dwBytesInRes,
807                                            !fCursor, 0x00030000, width, height, loadflags);
808         FreeResource( handle );
809
810         /* If shared icon, add to icon cache */
811
812         if ( hIcon && (loadflags & LR_SHARED) )
813             CURSORICON_AddSharedIcon( hInstance, hRsrc, hGroupRsrc, hIcon );
814     }
815
816     return hIcon;
817 }
818
819 /***********************************************************************
820  *           CURSORICON_Copy
821  *
822  * Make a copy of a cursor or icon.
823  */
824 static HICON CURSORICON_Copy( HINSTANCE16 hInst16, HICON hIcon )
825 {
826     char *ptrOld, *ptrNew;
827     int size;
828     HICON16 hOld = HICON_16(hIcon);
829     HICON16 hNew;
830
831     if (!(ptrOld = (char *)GlobalLock16( hOld ))) return 0;
832     if (hInst16 && !(hInst16 = GetExePtr( hInst16 ))) return 0;
833     size = GlobalSize16( hOld );
834     hNew = GlobalAlloc16( GMEM_MOVEABLE, size );
835     FarSetOwner16( hNew, hInst16 );
836     ptrNew = (char *)GlobalLock16( hNew );
837     memcpy( ptrNew, ptrOld, size );
838     GlobalUnlock16( hOld );
839     GlobalUnlock16( hNew );
840     return HICON_32(hNew);
841 }
842
843 /*************************************************************************
844  * CURSORICON_ExtCopy
845  *
846  * Copies an Image from the Cache if LR_COPYFROMRESOURCE is specified
847  *
848  * PARAMS
849  *      Handle     [I] handle to an Image
850  *      nType      [I] Type of Handle (IMAGE_CURSOR | IMAGE_ICON)
851  *      iDesiredCX [I] The Desired width of the Image
852  *      iDesiredCY [I] The desired height of the Image
853  *      nFlags     [I] The flags from CopyImage
854  *
855  * RETURNS
856  *     Success: The new handle of the Image
857  *
858  * NOTES
859  *     LR_COPYDELETEORG and LR_MONOCHROME are currently not implemented.
860  *     LR_MONOCHROME should be implemented by CURSORICON_CreateFromResource.
861  *     LR_COPYFROMRESOURCE will only work if the Image is in the Cache.
862  *
863  *
864  */
865
866 static HICON CURSORICON_ExtCopy(HICON hIcon, UINT nType,
867                            INT iDesiredCX, INT iDesiredCY,
868                            UINT nFlags)
869 {
870     HICON hNew=0;
871
872     TRACE_(icon)("hIcon %p, nType %u, iDesiredCX %i, iDesiredCY %i, nFlags %u\n",
873                  hIcon, nType, iDesiredCX, iDesiredCY, nFlags);
874
875     if(hIcon == 0)
876     {
877         return 0;
878     }
879
880     /* Best Fit or Monochrome */
881     if( (nFlags & LR_COPYFROMRESOURCE
882         && (iDesiredCX > 0 || iDesiredCY > 0))
883         || nFlags & LR_MONOCHROME)
884     {
885         ICONCACHE* pIconCache = CURSORICON_FindCache(hIcon);
886
887         /* Not Found in Cache, then do a straight copy
888         */
889         if(pIconCache == NULL)
890         {
891             hNew = CURSORICON_Copy(0, hIcon);
892             if(nFlags & LR_COPYFROMRESOURCE)
893             {
894                 TRACE_(icon)("LR_COPYFROMRESOURCE: Failed to load from cache\n");
895             }
896         }
897         else
898         {
899             int iTargetCY = iDesiredCY, iTargetCX = iDesiredCX;
900             LPBYTE pBits;
901             HANDLE hMem;
902             HRSRC hRsrc;
903             DWORD dwBytesInRes;
904             WORD wResId;
905             CURSORICONDIR *pDir;
906             CURSORICONDIRENTRY *pDirEntry;
907             BOOL bIsIcon = (nType == IMAGE_ICON);
908
909             /* Completing iDesiredCX CY for Monochrome Bitmaps if needed
910             */
911             if(((nFlags & LR_MONOCHROME) && !(nFlags & LR_COPYFROMRESOURCE))
912                 || (iDesiredCX == 0 && iDesiredCY == 0))
913             {
914                 iDesiredCY = GetSystemMetrics(bIsIcon ?
915                     SM_CYICON : SM_CYCURSOR);
916                 iDesiredCX = GetSystemMetrics(bIsIcon ?
917                     SM_CXICON : SM_CXCURSOR);
918             }
919
920             /* Retrieve the CURSORICONDIRENTRY
921             */
922             if (!(hMem = LoadResource( pIconCache->hModule ,
923                             pIconCache->hGroupRsrc)))
924             {
925                 return 0;
926             }
927             if (!(pDir = (CURSORICONDIR*)LockResource( hMem )))
928             {
929                 return 0;
930             }
931
932             /* Find Best Fit
933             */
934             if(bIsIcon)
935             {
936                 pDirEntry = (CURSORICONDIRENTRY *)CURSORICON_FindBestIcon(
937                                 pDir, iDesiredCX, iDesiredCY, 256);
938             }
939             else
940             {
941                 pDirEntry = (CURSORICONDIRENTRY *)CURSORICON_FindBestCursor(
942                                 pDir, iDesiredCX, iDesiredCY, 1);
943             }
944
945             wResId = pDirEntry->wResId;
946             dwBytesInRes = pDirEntry->dwBytesInRes;
947             FreeResource(hMem);
948
949             TRACE_(icon)("ResID %u, BytesInRes %lu, Width %d, Height %d DX %d, DY %d\n",
950                 wResId, dwBytesInRes,  pDirEntry->ResInfo.icon.bWidth,
951                 pDirEntry->ResInfo.icon.bHeight, iDesiredCX, iDesiredCY);
952
953             /* Get the Best Fit
954             */
955             if (!(hRsrc = FindResourceW(pIconCache->hModule ,
956                 MAKEINTRESOURCEW(wResId), (LPWSTR)(bIsIcon ? RT_ICON : RT_CURSOR))))
957             {
958                 return 0;
959             }
960             if (!(hMem = LoadResource( pIconCache->hModule , hRsrc )))
961             {
962                 return 0;
963             }
964
965             pBits = (LPBYTE)LockResource( hMem );
966
967             if(nFlags & LR_DEFAULTSIZE)
968             {
969                 iTargetCY = GetSystemMetrics(SM_CYICON);
970                 iTargetCX = GetSystemMetrics(SM_CXICON);
971             }
972
973             /* Create a New Icon with the proper dimension
974             */
975             hNew = CURSORICON_CreateFromResource( 0, 0, pBits, dwBytesInRes,
976                        bIsIcon, 0x00030000, iTargetCX, iTargetCY, nFlags);
977             FreeResource(hMem);
978         }
979     }
980     else hNew = CURSORICON_Copy(0, hIcon);
981     return hNew;
982 }
983
984
985 /***********************************************************************
986  *              CreateCursor (USER32.@)
987  */
988 HCURSOR WINAPI CreateCursor( HINSTANCE hInstance,
989                                  INT xHotSpot, INT yHotSpot,
990                                  INT nWidth, INT nHeight,
991                                  LPCVOID lpANDbits, LPCVOID lpXORbits )
992 {
993     CURSORICONINFO info;
994
995     TRACE_(cursor)("%dx%d spot=%d,%d xor=%p and=%p\n",
996                     nWidth, nHeight, xHotSpot, yHotSpot, lpXORbits, lpANDbits);
997
998     info.ptHotSpot.x = xHotSpot;
999     info.ptHotSpot.y = yHotSpot;
1000     info.nWidth = nWidth;
1001     info.nHeight = nHeight;
1002     info.nWidthBytes = 0;
1003     info.bPlanes = 1;
1004     info.bBitsPerPixel = 1;
1005
1006     return HICON_32(CreateCursorIconIndirect16(0, &info, lpANDbits, lpXORbits));
1007 }
1008
1009
1010 /***********************************************************************
1011  *              CreateIcon (USER.407)
1012  */
1013 HICON16 WINAPI CreateIcon16( HINSTANCE16 hInstance, INT16 nWidth,
1014                              INT16 nHeight, BYTE bPlanes, BYTE bBitsPixel,
1015                              LPCVOID lpANDbits, LPCVOID lpXORbits )
1016 {
1017     CURSORICONINFO info;
1018
1019     TRACE_(icon)("%dx%dx%d, xor=%p, and=%p\n",
1020                   nWidth, nHeight, bPlanes * bBitsPixel, lpXORbits, lpANDbits);
1021
1022     info.ptHotSpot.x = ICON_HOTSPOT;
1023     info.ptHotSpot.y = ICON_HOTSPOT;
1024     info.nWidth = nWidth;
1025     info.nHeight = nHeight;
1026     info.nWidthBytes = 0;
1027     info.bPlanes = bPlanes;
1028     info.bBitsPerPixel = bBitsPixel;
1029
1030     return CreateCursorIconIndirect16( hInstance, &info, lpANDbits, lpXORbits );
1031 }
1032
1033
1034 /***********************************************************************
1035  *              CreateIcon (USER32.@)
1036  *
1037  *  Creates an icon based on the specified bitmaps. The bitmaps must be
1038  *  provided in a device dependent format and will be resized to
1039  *  (SM_CXICON,SM_CYICON) and depth converted to match the screen's color
1040  *  depth. The provided bitmaps must be top-down bitmaps.
1041  *  Although Windows does not support 15bpp(*) this API must support it
1042  *  for Winelib applications.
1043  *
1044  *  (*) Windows does not support 15bpp but it supports the 555 RGB 16bpp
1045  *      format!
1046  *
1047  * BUGS
1048  *
1049  *  - The provided bitmaps are not resized!
1050  *  - The documentation says the lpXORbits bitmap must be in a device
1051  *    dependent format. But we must still resize it and perform depth
1052  *    conversions if necessary.
1053  *  - I'm a bit unsure about the how the 'device dependent format' thing works.
1054  *    I did some tests on windows and found that if you provide a 16bpp bitmap
1055  *    in lpXORbits, then its format but be 565 RGB if the screen's bit depth
1056  *    is 16bpp but it must be 555 RGB if the screen's bit depth is anything
1057  *    else. I don't know if this is part of the GDI specs or if this is a
1058  *    quirk of the graphics card driver.
1059  *  - You may think that we check whether the bit depths match or not
1060  *    as an optimization. But the truth is that the conversion using
1061  *    CreateDIBitmap does not work for some bit depth (e.g. 8bpp) and I have
1062  *    no idea why.
1063  *  - I'm pretty sure that all the things we do in CreateIcon should
1064  *    also be done in CreateIconIndirect...
1065  */
1066 HICON WINAPI CreateIcon(
1067     HINSTANCE hInstance,  /* [in] the application's hInstance */
1068     INT       nWidth,     /* [in] the width of the provided bitmaps */
1069     INT       nHeight,    /* [in] the height of the provided bitmaps */
1070     BYTE      bPlanes,    /* [in] the number of planes in the provided bitmaps */
1071     BYTE      bBitsPixel, /* [in] the number of bits per pixel of the lpXORbits bitmap */
1072     LPCVOID   lpANDbits,  /* [in] a monochrome bitmap representing the icon's mask */
1073     LPCVOID   lpXORbits)  /* [in] the icon's 'color' bitmap */
1074 {
1075     HICON hIcon;
1076     HDC hdc;
1077
1078     TRACE_(icon)("%dx%dx%d, xor=%p, and=%p\n",
1079                  nWidth, nHeight, bPlanes * bBitsPixel, lpXORbits, lpANDbits);
1080
1081     hdc=GetDC(0);
1082     if (!hdc)
1083         return 0;
1084
1085     if (GetDeviceCaps(hdc,BITSPIXEL)==bBitsPixel) {
1086         CURSORICONINFO info;
1087
1088         info.ptHotSpot.x = ICON_HOTSPOT;
1089         info.ptHotSpot.y = ICON_HOTSPOT;
1090         info.nWidth = nWidth;
1091         info.nHeight = nHeight;
1092         info.nWidthBytes = 0;
1093         info.bPlanes = bPlanes;
1094         info.bBitsPerPixel = bBitsPixel;
1095
1096         hIcon=HICON_32(CreateCursorIconIndirect16(0, &info, lpANDbits, lpXORbits));
1097     } else {
1098         ICONINFO iinfo;
1099         BITMAPINFO bmi;
1100
1101         iinfo.fIcon=TRUE;
1102         iinfo.xHotspot=ICON_HOTSPOT;
1103         iinfo.yHotspot=ICON_HOTSPOT;
1104         iinfo.hbmMask=CreateBitmap(nWidth,nHeight,1,1,lpANDbits);
1105
1106         bmi.bmiHeader.biSize=sizeof(bmi.bmiHeader);
1107         bmi.bmiHeader.biWidth=nWidth;
1108         bmi.bmiHeader.biHeight=-nHeight;
1109         bmi.bmiHeader.biPlanes=bPlanes;
1110         bmi.bmiHeader.biBitCount=bBitsPixel;
1111         bmi.bmiHeader.biCompression=BI_RGB;
1112         bmi.bmiHeader.biSizeImage=0;
1113         bmi.bmiHeader.biXPelsPerMeter=0;
1114         bmi.bmiHeader.biYPelsPerMeter=0;
1115         bmi.bmiHeader.biClrUsed=0;
1116         bmi.bmiHeader.biClrImportant=0;
1117
1118         iinfo.hbmColor = CreateDIBitmap( hdc, &bmi.bmiHeader,
1119                                          CBM_INIT, lpXORbits,
1120                                          &bmi, DIB_RGB_COLORS );
1121
1122         hIcon=CreateIconIndirect(&iinfo);
1123         DeleteObject(iinfo.hbmMask);
1124         DeleteObject(iinfo.hbmColor);
1125     }
1126     ReleaseDC(0,hdc);
1127     return hIcon;
1128 }
1129
1130
1131 /***********************************************************************
1132  *              CreateCursorIconIndirect (USER.408)
1133  */
1134 HGLOBAL16 WINAPI CreateCursorIconIndirect16( HINSTANCE16 hInstance,
1135                                            CURSORICONINFO *info,
1136                                            LPCVOID lpANDbits,
1137                                            LPCVOID lpXORbits )
1138 {
1139     HGLOBAL16 handle;
1140     char *ptr;
1141     int sizeAnd, sizeXor;
1142
1143     hInstance = GetExePtr( hInstance );  /* Make it a module handle */
1144     if (!lpXORbits || !lpANDbits || info->bPlanes != 1) return 0;
1145     info->nWidthBytes = get_bitmap_width_bytes(info->nWidth,info->bBitsPerPixel);
1146     sizeXor = info->nHeight * info->nWidthBytes;
1147     sizeAnd = info->nHeight * get_bitmap_width_bytes( info->nWidth, 1 );
1148     if (!(handle = GlobalAlloc16( GMEM_MOVEABLE,
1149                                   sizeof(CURSORICONINFO) + sizeXor + sizeAnd)))
1150         return 0;
1151     FarSetOwner16( handle, hInstance );
1152     ptr = (char *)GlobalLock16( handle );
1153     memcpy( ptr, info, sizeof(*info) );
1154     memcpy( ptr + sizeof(CURSORICONINFO), lpANDbits, sizeAnd );
1155     memcpy( ptr + sizeof(CURSORICONINFO) + sizeAnd, lpXORbits, sizeXor );
1156     GlobalUnlock16( handle );
1157     return handle;
1158 }
1159
1160
1161 /***********************************************************************
1162  *              CopyIcon (USER.368)
1163  */
1164 HICON16 WINAPI CopyIcon16( HINSTANCE16 hInstance, HICON16 hIcon )
1165 {
1166     TRACE_(icon)("%04x %04x\n", hInstance, hIcon );
1167     return HICON_16(CURSORICON_Copy(hInstance, HICON_32(hIcon)));
1168 }
1169
1170
1171 /***********************************************************************
1172  *              CopyIcon (USER32.@)
1173  */
1174 HICON WINAPI CopyIcon( HICON hIcon )
1175 {
1176     TRACE_(icon)("%p\n", hIcon );
1177     return CURSORICON_Copy( 0, hIcon );
1178 }
1179
1180
1181 /***********************************************************************
1182  *              CopyCursor (USER.369)
1183  */
1184 HCURSOR16 WINAPI CopyCursor16( HINSTANCE16 hInstance, HCURSOR16 hCursor )
1185 {
1186     TRACE_(cursor)("%04x %04x\n", hInstance, hCursor );
1187     return HICON_16(CURSORICON_Copy(hInstance, HCURSOR_32(hCursor)));
1188 }
1189
1190 /**********************************************************************
1191  *              DestroyIcon32 (USER.610)
1192  *
1193  * This routine is actually exported from Win95 USER under the name
1194  * DestroyIcon32 ...  The behaviour implemented here should mimic
1195  * the Win95 one exactly, especially the return values, which
1196  * depend on the setting of various flags.
1197  */
1198 WORD WINAPI DestroyIcon32( HGLOBAL16 handle, UINT16 flags )
1199 {
1200     WORD retv;
1201
1202     TRACE_(icon)("(%04x, %04x)\n", handle, flags );
1203
1204     /* Check whether destroying active cursor */
1205
1206     if ( QUEUE_Current()->cursor == HICON_32(handle) )
1207     {
1208         WARN_(cursor)("Destroying active cursor!\n" );
1209         SetCursor( 0 );
1210     }
1211
1212     /* Try shared cursor/icon first */
1213
1214     if ( !(flags & CID_NONSHARED) )
1215     {
1216         INT count = CURSORICON_DelSharedIcon(HICON_32(handle));
1217
1218         if ( count != -1 )
1219             return (flags & CID_WIN32)? TRUE : (count == 0);
1220
1221         /* FIXME: OEM cursors/icons should be recognized */
1222     }
1223
1224     /* Now assume non-shared cursor/icon */
1225
1226     retv = GlobalFree16( handle );
1227     return (flags & CID_RESOURCE)? retv : TRUE;
1228 }
1229
1230 /***********************************************************************
1231  *              DestroyIcon (USER32.@)
1232  */
1233 BOOL WINAPI DestroyIcon( HICON hIcon )
1234 {
1235     return DestroyIcon32(HICON_16(hIcon), CID_WIN32);
1236 }
1237
1238
1239 /***********************************************************************
1240  *              DestroyCursor (USER32.@)
1241  */
1242 BOOL WINAPI DestroyCursor( HCURSOR hCursor )
1243 {
1244     return DestroyIcon32(HCURSOR_16(hCursor), CID_WIN32);
1245 }
1246
1247
1248 /***********************************************************************
1249  *              DrawIcon (USER32.@)
1250  */
1251 BOOL WINAPI DrawIcon( HDC hdc, INT x, INT y, HICON hIcon )
1252 {
1253     CURSORICONINFO *ptr;
1254     HDC hMemDC;
1255     HBITMAP hXorBits, hAndBits;
1256     COLORREF oldFg, oldBg;
1257
1258     if (!(ptr = (CURSORICONINFO *)GlobalLock16(HICON_16(hIcon)))) return FALSE;
1259     if (!(hMemDC = CreateCompatibleDC( hdc ))) return FALSE;
1260     hAndBits = CreateBitmap( ptr->nWidth, ptr->nHeight, 1, 1,
1261                                (char *)(ptr+1) );
1262     hXorBits = CreateBitmap( ptr->nWidth, ptr->nHeight, ptr->bPlanes,
1263                                ptr->bBitsPerPixel, (char *)(ptr + 1)
1264                         + ptr->nHeight * get_bitmap_width_bytes(ptr->nWidth,1) );
1265     oldFg = SetTextColor( hdc, RGB(0,0,0) );
1266     oldBg = SetBkColor( hdc, RGB(255,255,255) );
1267
1268     if (hXorBits && hAndBits)
1269     {
1270         HBITMAP hBitTemp = SelectObject( hMemDC, hAndBits );
1271         BitBlt( hdc, x, y, ptr->nWidth, ptr->nHeight, hMemDC, 0, 0, SRCAND );
1272         SelectObject( hMemDC, hXorBits );
1273         BitBlt(hdc, x, y, ptr->nWidth, ptr->nHeight, hMemDC, 0, 0,SRCINVERT);
1274         SelectObject( hMemDC, hBitTemp );
1275     }
1276     DeleteDC( hMemDC );
1277     if (hXorBits) DeleteObject( hXorBits );
1278     if (hAndBits) DeleteObject( hAndBits );
1279     GlobalUnlock16(HICON_16(hIcon));
1280     SetTextColor( hdc, oldFg );
1281     SetBkColor( hdc, oldBg );
1282     return TRUE;
1283 }
1284
1285 /***********************************************************************
1286  *              DumpIcon (USER.459)
1287  */
1288 DWORD WINAPI DumpIcon16( SEGPTR pInfo, WORD *lpLen,
1289                        SEGPTR *lpXorBits, SEGPTR *lpAndBits )
1290 {
1291     CURSORICONINFO *info = MapSL( pInfo );
1292     int sizeAnd, sizeXor;
1293
1294     if (!info) return 0;
1295     sizeXor = info->nHeight * info->nWidthBytes;
1296     sizeAnd = info->nHeight * get_bitmap_width_bytes( info->nWidth, 1 );
1297     if (lpAndBits) *lpAndBits = pInfo + sizeof(CURSORICONINFO);
1298     if (lpXorBits) *lpXorBits = pInfo + sizeof(CURSORICONINFO) + sizeAnd;
1299     if (lpLen) *lpLen = sizeof(CURSORICONINFO) + sizeAnd + sizeXor;
1300     return MAKELONG( sizeXor, sizeXor );
1301 }
1302
1303
1304 /***********************************************************************
1305  *              SetCursor (USER32.@)
1306  * RETURNS:
1307  *      A handle to the previous cursor shape.
1308  */
1309 HCURSOR WINAPI SetCursor( HCURSOR hCursor /* [in] Handle of cursor to show */ )
1310 {
1311     MESSAGEQUEUE *queue = QUEUE_Current();
1312     HCURSOR hOldCursor;
1313
1314     if (hCursor == queue->cursor) return hCursor;  /* No change */
1315     TRACE_(cursor)("%p\n", hCursor );
1316     hOldCursor = queue->cursor;
1317     queue->cursor = hCursor;
1318     /* Change the cursor shape only if it is visible */
1319     if (queue->cursor_count >= 0)
1320     {
1321         USER_Driver.pSetCursor( (CURSORICONINFO*)GlobalLock16(HCURSOR_16(hCursor)) );
1322         GlobalUnlock16(HCURSOR_16(hCursor));
1323     }
1324     return hOldCursor;
1325 }
1326
1327 /***********************************************************************
1328  *              ShowCursor (USER32.@)
1329  */
1330 INT WINAPI ShowCursor( BOOL bShow )
1331 {
1332     MESSAGEQUEUE *queue = QUEUE_Current();
1333
1334     TRACE_(cursor)("%d, count=%d\n", bShow, queue->cursor_count );
1335
1336     if (bShow)
1337     {
1338         if (++queue->cursor_count == 0)  /* Show it */
1339         {
1340             USER_Driver.pSetCursor((CURSORICONINFO*)GlobalLock16(HCURSOR_16(queue->cursor)));
1341             GlobalUnlock16(HCURSOR_16(queue->cursor));
1342         }
1343     }
1344     else
1345     {
1346         if (--queue->cursor_count == -1)  /* Hide it */
1347             USER_Driver.pSetCursor( NULL );
1348     }
1349     return queue->cursor_count;
1350 }
1351
1352 /***********************************************************************
1353  *              GetCursor (USER32.@)
1354  */
1355 HCURSOR WINAPI GetCursor(void)
1356 {
1357     return QUEUE_Current()->cursor;
1358 }
1359
1360
1361 /***********************************************************************
1362  *              ClipCursor (USER.16)
1363  */
1364 BOOL16 WINAPI ClipCursor16( const RECT16 *rect )
1365 {
1366     if (!rect) SetRectEmpty( &CURSOR_ClipRect );
1367     else CONV_RECT16TO32( rect, &CURSOR_ClipRect );
1368     return TRUE;
1369 }
1370
1371
1372 /***********************************************************************
1373  *              ClipCursor (USER32.@)
1374  */
1375 BOOL WINAPI ClipCursor( const RECT *rect )
1376 {
1377     if (!rect) SetRectEmpty( &CURSOR_ClipRect );
1378     else CopyRect( &CURSOR_ClipRect, rect );
1379     return TRUE;
1380 }
1381
1382
1383 /***********************************************************************
1384  *              GetClipCursor (USER.309)
1385  */
1386 void WINAPI GetClipCursor16( RECT16 *rect )
1387 {
1388     if (rect) CONV_RECT32TO16( &CURSOR_ClipRect, rect );
1389 }
1390
1391
1392 /***********************************************************************
1393  *              GetClipCursor (USER32.@)
1394  */
1395 BOOL WINAPI GetClipCursor( RECT *rect )
1396 {
1397     if (rect)
1398     {
1399        CopyRect( rect, &CURSOR_ClipRect );
1400        return TRUE;
1401     }
1402     return FALSE;
1403 }
1404
1405 /**********************************************************************
1406  *              LookupIconIdFromDirectoryEx (USER.364)
1407  *
1408  * FIXME: exact parameter sizes
1409  */
1410 INT16 WINAPI LookupIconIdFromDirectoryEx16( LPBYTE dir, BOOL16 bIcon,
1411              INT16 width, INT16 height, UINT16 cFlag )
1412 {
1413     return LookupIconIdFromDirectoryEx( dir, bIcon, width, height, cFlag );
1414 }
1415
1416 /**********************************************************************
1417  *              LookupIconIdFromDirectoryEx (USER32.@)
1418  */
1419 INT WINAPI LookupIconIdFromDirectoryEx( LPBYTE xdir, BOOL bIcon,
1420              INT width, INT height, UINT cFlag )
1421 {
1422     CURSORICONDIR       *dir = (CURSORICONDIR*)xdir;
1423     UINT retVal = 0;
1424     if( dir && !dir->idReserved && (dir->idType & 3) )
1425     {
1426         CURSORICONDIRENTRY* entry;
1427         HDC hdc;
1428         UINT palEnts;
1429         int colors;
1430         hdc = GetDC(0);
1431         palEnts = GetSystemPaletteEntries(hdc, 0, 0, NULL);
1432         if (palEnts == 0)
1433             palEnts = 256;
1434         colors = (cFlag & LR_MONOCHROME) ? 2 : palEnts;
1435
1436         ReleaseDC(0, hdc);
1437
1438         if( bIcon )
1439             entry = CURSORICON_FindBestIcon( dir, width, height, colors );
1440         else
1441             entry = CURSORICON_FindBestCursor( dir, width, height, 1);
1442
1443         if( entry ) retVal = entry->wResId;
1444     }
1445     else WARN_(cursor)("invalid resource directory\n");
1446     return retVal;
1447 }
1448
1449 /**********************************************************************
1450  *              LookupIconIdFromDirectory (USER.?)
1451  */
1452 INT16 WINAPI LookupIconIdFromDirectory16( LPBYTE dir, BOOL16 bIcon )
1453 {
1454     return LookupIconIdFromDirectoryEx16( dir, bIcon,
1455            bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
1456            bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
1457 }
1458
1459 /**********************************************************************
1460  *              LookupIconIdFromDirectory (USER32.@)
1461  */
1462 INT WINAPI LookupIconIdFromDirectory( LPBYTE dir, BOOL bIcon )
1463 {
1464     return LookupIconIdFromDirectoryEx( dir, bIcon,
1465            bIcon ? GetSystemMetrics(SM_CXICON) : GetSystemMetrics(SM_CXCURSOR),
1466            bIcon ? GetSystemMetrics(SM_CYICON) : GetSystemMetrics(SM_CYCURSOR), bIcon ? 0 : LR_MONOCHROME );
1467 }
1468
1469 /**********************************************************************
1470  *              GetIconID (USER.455)
1471  */
1472 WORD WINAPI GetIconID16( HGLOBAL16 hResource, DWORD resType )
1473 {
1474     LPBYTE lpDir = (LPBYTE)GlobalLock16(hResource);
1475
1476     TRACE_(cursor)("hRes=%04x, entries=%i\n",
1477                     hResource, lpDir ? ((CURSORICONDIR*)lpDir)->idCount : 0);
1478
1479     switch(resType)
1480     {
1481         case RT_CURSOR:
1482              return (WORD)LookupIconIdFromDirectoryEx16( lpDir, FALSE,
1483                           GetSystemMetrics(SM_CXCURSOR), GetSystemMetrics(SM_CYCURSOR), LR_MONOCHROME );
1484         case RT_ICON:
1485              return (WORD)LookupIconIdFromDirectoryEx16( lpDir, TRUE,
1486                           GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), 0 );
1487         default:
1488              WARN_(cursor)("invalid res type %ld\n", resType );
1489     }
1490     return 0;
1491 }
1492
1493 /**********************************************************************
1494  *              LoadCursorIconHandler (USER.336)
1495  *
1496  * Supposed to load resources of Windows 2.x applications.
1497  */
1498 HGLOBAL16 WINAPI LoadCursorIconHandler16( HGLOBAL16 hResource, HMODULE16 hModule, HRSRC16 hRsrc )
1499 {
1500     FIXME_(cursor)("(%04x,%04x,%04x): old 2.x resources are not supported!\n",
1501           hResource, hModule, hRsrc);
1502     return (HGLOBAL16)0;
1503 }
1504
1505 /**********************************************************************
1506  *              LoadDIBIconHandler (USER.357)
1507  *
1508  * RT_ICON resource loader, installed by USER_SignalProc when module
1509  * is initialized.
1510  */
1511 HGLOBAL16 WINAPI LoadDIBIconHandler16( HGLOBAL16 hMemObj, HMODULE16 hModule, HRSRC16 hRsrc )
1512 {
1513     /* If hResource is zero we must allocate a new memory block, if it's
1514      * non-zero but GlobalLock() returns NULL then it was discarded and
1515      * we have to recommit some memory, otherwise we just need to check
1516      * the block size. See LoadProc() in 16-bit SDK for more.
1517      */
1518
1519      hMemObj = NE_DefResourceHandler( hMemObj, hModule, hRsrc );
1520      if( hMemObj )
1521      {
1522          LPBYTE bits = (LPBYTE)GlobalLock16( hMemObj );
1523          hMemObj = HICON_16(CURSORICON_CreateFromResource(
1524                                 hModule, hMemObj, bits,
1525                                 SizeofResource16(hModule, hRsrc), TRUE, 0x00030000,
1526                                 GetSystemMetrics(SM_CXICON),
1527                                 GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR));
1528      }
1529      return hMemObj;
1530 }
1531
1532 /**********************************************************************
1533  *              LoadDIBCursorHandler (USER.356)
1534  *
1535  * RT_CURSOR resource loader. Same as above.
1536  */
1537 HGLOBAL16 WINAPI LoadDIBCursorHandler16( HGLOBAL16 hMemObj, HMODULE16 hModule, HRSRC16 hRsrc )
1538 {
1539     hMemObj = NE_DefResourceHandler( hMemObj, hModule, hRsrc );
1540     if( hMemObj )
1541     {
1542         LPBYTE bits = (LPBYTE)GlobalLock16( hMemObj );
1543         hMemObj = HICON_16(CURSORICON_CreateFromResource(
1544                                 hModule, hMemObj, bits,
1545                                 SizeofResource16(hModule, hRsrc), FALSE, 0x00030000,
1546                                 GetSystemMetrics(SM_CXCURSOR),
1547                                 GetSystemMetrics(SM_CYCURSOR), LR_MONOCHROME));
1548     }
1549     return hMemObj;
1550 }
1551
1552 /**********************************************************************
1553  *              LoadIconHandler (USER.456)
1554  */
1555 HICON16 WINAPI LoadIconHandler16( HGLOBAL16 hResource, BOOL16 bNew )
1556 {
1557     LPBYTE bits = (LPBYTE)LockResource16( hResource );
1558
1559     TRACE_(cursor)("hRes=%04x\n",hResource);
1560
1561     return HICON_16(CURSORICON_CreateFromResource(0, 0, bits, 0, TRUE,
1562                       bNew ? 0x00030000 : 0x00020000, 0, 0, LR_DEFAULTCOLOR));
1563 }
1564
1565 /***********************************************************************
1566  *              LoadCursorW (USER32.@)
1567  */
1568 HCURSOR WINAPI LoadCursorW(HINSTANCE hInstance, LPCWSTR name)
1569 {
1570     return LoadImageW( hInstance, name, IMAGE_CURSOR, 0, 0,
1571                        LR_SHARED | LR_DEFAULTSIZE );
1572 }
1573
1574 /***********************************************************************
1575  *              LoadCursorA (USER32.@)
1576  */
1577 HCURSOR WINAPI LoadCursorA(HINSTANCE hInstance, LPCSTR name)
1578 {
1579     return LoadImageA( hInstance, name, IMAGE_CURSOR, 0, 0,
1580                        LR_SHARED | LR_DEFAULTSIZE );
1581 }
1582
1583 /***********************************************************************
1584  *              LoadCursorFromFileW (USER32.@)
1585  */
1586 HCURSOR WINAPI LoadCursorFromFileW (LPCWSTR name)
1587 {
1588     return LoadImageW( 0, name, IMAGE_CURSOR, 0, 0,
1589                        LR_LOADFROMFILE | LR_DEFAULTSIZE );
1590 }
1591
1592 /***********************************************************************
1593  *              LoadCursorFromFileA (USER32.@)
1594  */
1595 HCURSOR WINAPI LoadCursorFromFileA (LPCSTR name)
1596 {
1597     return LoadImageA( 0, name, IMAGE_CURSOR, 0, 0,
1598                        LR_LOADFROMFILE | LR_DEFAULTSIZE );
1599 }
1600
1601 /***********************************************************************
1602  *              LoadIconW (USER32.@)
1603  */
1604 HICON WINAPI LoadIconW(HINSTANCE hInstance, LPCWSTR name)
1605 {
1606     return LoadImageW( hInstance, name, IMAGE_ICON, 0, 0,
1607                        LR_SHARED | LR_DEFAULTSIZE );
1608 }
1609
1610 /***********************************************************************
1611  *              LoadIconA (USER32.@)
1612  */
1613 HICON WINAPI LoadIconA(HINSTANCE hInstance, LPCSTR name)
1614 {
1615     return LoadImageA( hInstance, name, IMAGE_ICON, 0, 0,
1616                        LR_SHARED | LR_DEFAULTSIZE );
1617 }
1618
1619 /**********************************************************************
1620  *              GetIconInfo (USER32.@)
1621  */
1622 BOOL WINAPI GetIconInfo(HICON hIcon, PICONINFO iconinfo)
1623 {
1624     CURSORICONINFO      *ciconinfo;
1625     INT height;
1626
1627     ciconinfo = GlobalLock16(HICON_16(hIcon));
1628     if (!ciconinfo)
1629         return FALSE;
1630
1631     if ( (ciconinfo->ptHotSpot.x == ICON_HOTSPOT) &&
1632          (ciconinfo->ptHotSpot.y == ICON_HOTSPOT) )
1633     {
1634       iconinfo->fIcon    = TRUE;
1635       iconinfo->xHotspot = ciconinfo->nWidth / 2;
1636       iconinfo->yHotspot = ciconinfo->nHeight / 2;
1637     }
1638     else
1639     {
1640       iconinfo->fIcon    = FALSE;
1641       iconinfo->xHotspot = ciconinfo->ptHotSpot.x;
1642       iconinfo->yHotspot = ciconinfo->ptHotSpot.y;
1643     }
1644
1645     if (ciconinfo->bBitsPerPixel > 1)
1646     {
1647         iconinfo->hbmColor = CreateBitmap( ciconinfo->nWidth, ciconinfo->nHeight,
1648                                 ciconinfo->bPlanes, ciconinfo->bBitsPerPixel,
1649                                 (char *)(ciconinfo + 1)
1650                                 + ciconinfo->nHeight *
1651                                 get_bitmap_width_bytes (ciconinfo->nWidth,1) );
1652         height = ciconinfo->nHeight;
1653     }
1654     else
1655     {
1656         iconinfo->hbmColor = 0;
1657         height = ciconinfo->nHeight * 2;
1658     }
1659
1660     iconinfo->hbmMask = CreateBitmap ( ciconinfo->nWidth, height,
1661                                 1, 1, (char *)(ciconinfo + 1));
1662
1663     GlobalUnlock16(HICON_16(hIcon));
1664
1665     return TRUE;
1666 }
1667
1668 /**********************************************************************
1669  *              CreateIconIndirect (USER32.@)
1670  */
1671 HICON WINAPI CreateIconIndirect(PICONINFO iconinfo)
1672 {
1673     BITMAP bmpXor,bmpAnd;
1674     HICON16 hObj;
1675     int sizeXor,sizeAnd;
1676
1677     GetObjectA( iconinfo->hbmColor, sizeof(bmpXor), &bmpXor );
1678     GetObjectA( iconinfo->hbmMask, sizeof(bmpAnd), &bmpAnd );
1679
1680     sizeXor = bmpXor.bmHeight * bmpXor.bmWidthBytes;
1681     sizeAnd = bmpAnd.bmHeight * bmpAnd.bmWidthBytes;
1682
1683     hObj = GlobalAlloc16( GMEM_MOVEABLE,
1684                      sizeof(CURSORICONINFO) + sizeXor + sizeAnd );
1685     if (hObj)
1686     {
1687         CURSORICONINFO *info;
1688
1689         info = (CURSORICONINFO *)GlobalLock16( hObj );
1690
1691         /* If we are creating an icon, the hotspot is unused */
1692         if (iconinfo->fIcon)
1693         {
1694           info->ptHotSpot.x   = ICON_HOTSPOT;
1695           info->ptHotSpot.y   = ICON_HOTSPOT;
1696         }
1697         else
1698         {
1699           info->ptHotSpot.x   = iconinfo->xHotspot;
1700           info->ptHotSpot.y   = iconinfo->yHotspot;
1701         }
1702
1703         info->nWidth        = bmpXor.bmWidth;
1704         info->nHeight       = bmpXor.bmHeight;
1705         info->nWidthBytes   = bmpXor.bmWidthBytes;
1706         info->bPlanes       = bmpXor.bmPlanes;
1707         info->bBitsPerPixel = bmpXor.bmBitsPixel;
1708
1709         /* Transfer the bitmap bits to the CURSORICONINFO structure */
1710
1711         GetBitmapBits( iconinfo->hbmMask ,sizeAnd,(char*)(info + 1) );
1712         GetBitmapBits( iconinfo->hbmColor,sizeXor,(char*)(info + 1) +sizeAnd);
1713         GlobalUnlock16( hObj );
1714     }
1715     return HICON_32(hObj);
1716 }
1717
1718 /******************************************************************************
1719  *              DrawIconEx (USER32.@) Draws an icon or cursor on device context
1720  *
1721  * NOTES
1722  *    Why is this using SM_CXICON instead of SM_CXCURSOR?
1723  *
1724  * PARAMS
1725  *    hdc     [I] Handle to device context
1726  *    x0      [I] X coordinate of upper left corner
1727  *    y0      [I] Y coordinate of upper left corner
1728  *    hIcon   [I] Handle to icon to draw
1729  *    cxWidth [I] Width of icon
1730  *    cyWidth [I] Height of icon
1731  *    istep   [I] Index of frame in animated cursor
1732  *    hbr     [I] Handle to background brush
1733  *    flags   [I] Icon-drawing flags
1734  *
1735  * RETURNS
1736  *    Success: TRUE
1737  *    Failure: FALSE
1738  */
1739 BOOL WINAPI DrawIconEx( HDC hdc, INT x0, INT y0, HICON hIcon,
1740                             INT cxWidth, INT cyWidth, UINT istep,
1741                             HBRUSH hbr, UINT flags )
1742 {
1743     CURSORICONINFO *ptr = (CURSORICONINFO *)GlobalLock16(HICON_16(hIcon));
1744     HDC hDC_off = 0, hMemDC;
1745     BOOL result = FALSE, DoOffscreen;
1746     HBITMAP hB_off = 0, hOld = 0;
1747
1748     if (!ptr) return FALSE;
1749     TRACE_(icon)("(hdc=%p,pos=%d.%d,hicon=%p,extend=%d.%d,istep=%d,br=%p,flags=0x%08x)\n",
1750                  hdc,x0,y0,hIcon,cxWidth,cyWidth,istep,hbr,flags );
1751
1752     hMemDC = CreateCompatibleDC (hdc);
1753     if (istep)
1754         FIXME_(icon)("Ignoring istep=%d\n", istep);
1755     if (flags & DI_COMPAT)
1756         FIXME_(icon)("Ignoring flag DI_COMPAT\n");
1757
1758     if (!flags) {
1759         FIXME_(icon)("no flags set? setting to DI_NORMAL\n");
1760         flags = DI_NORMAL;
1761     }
1762
1763     /* Calculate the size of the destination image.  */
1764     if (cxWidth == 0)
1765     {
1766       if (flags & DI_DEFAULTSIZE)
1767         cxWidth = GetSystemMetrics (SM_CXICON);
1768       else
1769         cxWidth = ptr->nWidth;
1770     }
1771     if (cyWidth == 0)
1772     {
1773       if (flags & DI_DEFAULTSIZE)
1774         cyWidth = GetSystemMetrics (SM_CYICON);
1775       else
1776         cyWidth = ptr->nHeight;
1777     }
1778
1779     DoOffscreen = (GetObjectType( hbr ) == OBJ_BRUSH);
1780
1781     if (DoOffscreen) {
1782       RECT r;
1783
1784       r.left = 0;
1785       r.top = 0;
1786       r.right = cxWidth;
1787       r.bottom = cxWidth;
1788
1789       hDC_off = CreateCompatibleDC(hdc);
1790       hB_off = CreateCompatibleBitmap(hdc, cxWidth, cyWidth);
1791       if (hDC_off && hB_off) {
1792         hOld = SelectObject(hDC_off, hB_off);
1793         FillRect(hDC_off, &r, hbr);
1794       }
1795     }
1796
1797     if (hMemDC && (!DoOffscreen || (hDC_off && hB_off)))
1798     {
1799         HBITMAP hXorBits, hAndBits;
1800         COLORREF  oldFg, oldBg;
1801         INT     nStretchMode;
1802
1803         nStretchMode = SetStretchBltMode (hdc, STRETCH_DELETESCANS);
1804
1805         hXorBits = CreateBitmap ( ptr->nWidth, ptr->nHeight,
1806                                     ptr->bPlanes, ptr->bBitsPerPixel,
1807                                     (char *)(ptr + 1)
1808                                     + ptr->nHeight *
1809                                     get_bitmap_width_bytes(ptr->nWidth,1) );
1810         hAndBits = CreateBitmap ( ptr->nWidth, ptr->nHeight,
1811                                     1, 1, (char *)(ptr+1) );
1812         oldFg = SetTextColor( hdc, RGB(0,0,0) );
1813         oldBg = SetBkColor( hdc, RGB(255,255,255) );
1814
1815         if (hXorBits && hAndBits)
1816         {
1817             HBITMAP hBitTemp = SelectObject( hMemDC, hAndBits );
1818             if (flags & DI_MASK)
1819             {
1820               if (DoOffscreen)
1821                 StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
1822                               hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
1823               else
1824                 StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
1825                               hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCAND);
1826             }
1827             SelectObject( hMemDC, hXorBits );
1828             if (flags & DI_IMAGE)
1829             {
1830               if (DoOffscreen)
1831                 StretchBlt (hDC_off, 0, 0, cxWidth, cyWidth,
1832                           hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
1833               else
1834                 StretchBlt (hdc, x0, y0, cxWidth, cyWidth,
1835                               hMemDC, 0, 0, ptr->nWidth, ptr->nHeight, SRCPAINT);
1836             }
1837             SelectObject( hMemDC, hBitTemp );
1838             result = TRUE;
1839         }
1840
1841         SetTextColor( hdc, oldFg );
1842         SetBkColor( hdc, oldBg );
1843         if (hXorBits) DeleteObject( hXorBits );
1844         if (hAndBits) DeleteObject( hAndBits );
1845         SetStretchBltMode (hdc, nStretchMode);
1846         if (DoOffscreen) {
1847           BitBlt(hdc, x0, y0, cxWidth, cyWidth, hDC_off, 0, 0, SRCCOPY);
1848           SelectObject(hDC_off, hOld);
1849         }
1850     }
1851     if (hMemDC) DeleteDC( hMemDC );
1852     if (hDC_off) DeleteDC(hDC_off);
1853     if (hB_off) DeleteObject(hB_off);
1854     GlobalUnlock16(HICON_16(hIcon));
1855     return result;
1856 }
1857
1858 /***********************************************************************
1859  *           DIB_FixColorsToLoadflags
1860  *
1861  * Change color table entries when LR_LOADTRANSPARENT or LR_LOADMAP3DCOLORS
1862  * are in loadflags
1863  */
1864 static void DIB_FixColorsToLoadflags(BITMAPINFO * bmi, UINT loadflags, BYTE pix)
1865 {
1866   int colors;
1867   COLORREF c_W, c_S, c_F, c_L, c_C;
1868   int incr,i;
1869   RGBQUAD *ptr;
1870
1871   if (bmi->bmiHeader.biBitCount > 8) return;
1872   if (bmi->bmiHeader.biSize == sizeof(BITMAPINFOHEADER)) incr = 4;
1873   else if (bmi->bmiHeader.biSize == sizeof(BITMAPCOREHEADER)) incr = 3;
1874   else {
1875     WARN_(resource)("Wrong bitmap header size!\n");
1876     return;
1877   }
1878   colors = bmi->bmiHeader.biClrUsed;
1879   if (!colors && (bmi->bmiHeader.biBitCount <= 8))
1880     colors = 1 << bmi->bmiHeader.biBitCount;
1881   c_W = GetSysColor(COLOR_WINDOW);
1882   c_S = GetSysColor(COLOR_3DSHADOW);
1883   c_F = GetSysColor(COLOR_3DFACE);
1884   c_L = GetSysColor(COLOR_3DLIGHT);
1885   if (loadflags & LR_LOADTRANSPARENT) {
1886     switch (bmi->bmiHeader.biBitCount) {
1887       case 1: pix = pix >> 7; break;
1888       case 4: pix = pix >> 4; break;
1889       case 8: break;
1890       default:
1891         WARN_(resource)("(%d): Unsupported depth\n", bmi->bmiHeader.biBitCount);
1892         return;
1893     }
1894     if (pix >= colors) {
1895       WARN_(resource)("pixel has color index greater than biClrUsed!\n");
1896       return;
1897     }
1898     if (loadflags & LR_LOADMAP3DCOLORS) c_W = c_F;
1899     ptr = (RGBQUAD*)((char*)bmi->bmiColors+pix*incr);
1900     ptr->rgbBlue = GetBValue(c_W);
1901     ptr->rgbGreen = GetGValue(c_W);
1902     ptr->rgbRed = GetRValue(c_W);
1903   }
1904   if (loadflags & LR_LOADMAP3DCOLORS)
1905     for (i=0; i<colors; i++) {
1906       ptr = (RGBQUAD*)((char*)bmi->bmiColors+i*incr);
1907       c_C = RGB(ptr->rgbRed, ptr->rgbGreen, ptr->rgbBlue);
1908       if (c_C == RGB(128, 128, 128)) {
1909         ptr->rgbRed = GetRValue(c_S);
1910         ptr->rgbGreen = GetGValue(c_S);
1911         ptr->rgbBlue = GetBValue(c_S);
1912       } else if (c_C == RGB(192, 192, 192)) {
1913         ptr->rgbRed = GetRValue(c_F);
1914         ptr->rgbGreen = GetGValue(c_F);
1915         ptr->rgbBlue = GetBValue(c_F);
1916       } else if (c_C == RGB(223, 223, 223)) {
1917         ptr->rgbRed = GetRValue(c_L);
1918         ptr->rgbGreen = GetGValue(c_L);
1919         ptr->rgbBlue = GetBValue(c_L);
1920       }
1921     }
1922 }
1923
1924
1925 /**********************************************************************
1926  *       BITMAP_Load
1927  */
1928 static HBITMAP BITMAP_Load( HINSTANCE instance,LPCWSTR name, UINT loadflags )
1929 {
1930     HBITMAP hbitmap = 0;
1931     HRSRC hRsrc;
1932     HGLOBAL handle;
1933     char *ptr = NULL;
1934     BITMAPINFO *info, *fix_info=NULL;
1935     HGLOBAL hFix;
1936     int size;
1937
1938     if (!(loadflags & LR_LOADFROMFILE))
1939     {
1940       if (!instance)
1941       {
1942           /* OEM bitmap: try to load the resource from user32.dll */
1943           if (HIWORD(name)) return 0;
1944           if (!(instance = GetModuleHandleA("user32.dll"))) return 0;
1945       }
1946       if (!(hRsrc = FindResourceW( instance, name, (LPWSTR)RT_BITMAP ))) return 0;
1947       if (!(handle = LoadResource( instance, hRsrc ))) return 0;
1948
1949       if ((info = (BITMAPINFO *)LockResource( handle )) == NULL) return 0;
1950     }
1951     else
1952     {
1953         if (!(ptr = map_fileW( name ))) return 0;
1954         info = (BITMAPINFO *)(ptr + sizeof(BITMAPFILEHEADER));
1955     }
1956     size = DIB_BitmapInfoSize(info, DIB_RGB_COLORS);
1957     if ((hFix = GlobalAlloc(0, size))) fix_info=GlobalLock(hFix);
1958     if (fix_info) {
1959       BYTE pix;
1960
1961       memcpy(fix_info, info, size);
1962       pix = *((LPBYTE)info+DIB_BitmapInfoSize(info, DIB_RGB_COLORS));
1963       DIB_FixColorsToLoadflags(fix_info, loadflags, pix);
1964       if (!screen_dc) screen_dc = CreateDCA( "DISPLAY", NULL, NULL, NULL );
1965       if (screen_dc)
1966       {
1967         char *bits = (char *)info + size;
1968         if (loadflags & LR_CREATEDIBSECTION) {
1969           DIBSECTION dib;
1970           hbitmap = CreateDIBSection(screen_dc, fix_info, DIB_RGB_COLORS, NULL, 0, 0);
1971           GetObjectA(hbitmap, sizeof(DIBSECTION), &dib);
1972           SetDIBits(screen_dc, hbitmap, 0, dib.dsBm.bmHeight, bits, info,
1973                     DIB_RGB_COLORS);
1974         }
1975         else {
1976           hbitmap = CreateDIBitmap( screen_dc, &fix_info->bmiHeader, CBM_INIT,
1977                                       bits, fix_info, DIB_RGB_COLORS );
1978         }
1979       }
1980       GlobalUnlock(hFix);
1981       GlobalFree(hFix);
1982     }
1983     if (loadflags & LR_LOADFROMFILE) UnmapViewOfFile( ptr );
1984     return hbitmap;
1985 }
1986
1987 /**********************************************************************
1988  *              LoadImageA (USER32.@)
1989  *
1990  * FIXME: implementation lacks some features, see LR_ defines in winuser.h
1991  */
1992
1993 /* filter for page-fault exceptions */
1994 static WINE_EXCEPTION_FILTER(page_fault)
1995 {
1996     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
1997         return EXCEPTION_EXECUTE_HANDLER;
1998     return EXCEPTION_CONTINUE_SEARCH;
1999 }
2000
2001 /*********************************************************************/
2002
2003 HANDLE WINAPI LoadImageA( HINSTANCE hinst, LPCSTR name, UINT type,
2004                               INT desiredx, INT desiredy, UINT loadflags)
2005 {
2006     HANDLE res;
2007     LPWSTR u_name;
2008
2009     if (!HIWORD(name))
2010         return LoadImageW(hinst, (LPWSTR)name, type, desiredx, desiredy, loadflags);
2011
2012     __TRY {
2013         DWORD len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 );
2014         u_name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2015         MultiByteToWideChar( CP_ACP, 0, name, -1, u_name, len );
2016     }
2017     __EXCEPT(page_fault) {
2018         SetLastError( ERROR_INVALID_PARAMETER );
2019         return 0;
2020     }
2021     __ENDTRY
2022     res = LoadImageW(hinst, u_name, type, desiredx, desiredy, loadflags);
2023     HeapFree(GetProcessHeap(), 0, u_name);
2024     return res;
2025 }
2026
2027
2028 /******************************************************************************
2029  *              LoadImageW (USER32.@) Loads an icon, cursor, or bitmap
2030  *
2031  * PARAMS
2032  *    hinst     [I] Handle of instance that contains image
2033  *    name      [I] Name of image
2034  *    type      [I] Type of image
2035  *    desiredx  [I] Desired width
2036  *    desiredy  [I] Desired height
2037  *    loadflags [I] Load flags
2038  *
2039  * RETURNS
2040  *    Success: Handle to newly loaded image
2041  *    Failure: NULL
2042  *
2043  * FIXME: Implementation lacks some features, see LR_ defines in winuser.h
2044  */
2045 HANDLE WINAPI LoadImageW( HINSTANCE hinst, LPCWSTR name, UINT type,
2046                 INT desiredx, INT desiredy, UINT loadflags )
2047 {
2048     if (HIWORD(name)) {
2049         TRACE_(resource)("(%p,%p,%d,%d,%d,0x%08x)\n",
2050               hinst,name,type,desiredx,desiredy,loadflags);
2051     } else {
2052         TRACE_(resource)("(%p,%p,%d,%d,%d,0x%08x)\n",
2053               hinst,name,type,desiredx,desiredy,loadflags);
2054     }
2055     if (loadflags & LR_DEFAULTSIZE) {
2056         if (type == IMAGE_ICON) {
2057             if (!desiredx) desiredx = GetSystemMetrics(SM_CXICON);
2058             if (!desiredy) desiredy = GetSystemMetrics(SM_CYICON);
2059         } else if (type == IMAGE_CURSOR) {
2060             if (!desiredx) desiredx = GetSystemMetrics(SM_CXCURSOR);
2061             if (!desiredy) desiredy = GetSystemMetrics(SM_CYCURSOR);
2062         }
2063     }
2064     if (loadflags & LR_LOADFROMFILE) loadflags &= ~LR_SHARED;
2065     switch (type) {
2066     case IMAGE_BITMAP:
2067         return BITMAP_Load( hinst, name, loadflags );
2068
2069     case IMAGE_ICON:
2070         if (!screen_dc) screen_dc = CreateDCW( DISPLAYW, NULL, NULL, NULL );
2071         if (screen_dc)
2072         {
2073             UINT palEnts = GetSystemPaletteEntries(screen_dc, 0, 0, NULL);
2074             if (palEnts == 0) palEnts = 256;
2075             return CURSORICON_Load(hinst, name, desiredx, desiredy,
2076                                    palEnts, FALSE, loadflags);
2077         }
2078         break;
2079
2080     case IMAGE_CURSOR:
2081         return CURSORICON_Load(hinst, name, desiredx, desiredy,
2082                                  1, TRUE, loadflags);
2083     }
2084     return 0;
2085 }
2086
2087 /******************************************************************************
2088  *              CopyImage (USER32.@) Creates new image and copies attributes to it
2089  *
2090  * PARAMS
2091  *    hnd      [I] Handle to image to copy
2092  *    type     [I] Type of image to copy
2093  *    desiredx [I] Desired width of new image
2094  *    desiredy [I] Desired height of new image
2095  *    flags    [I] Copy flags
2096  *
2097  * RETURNS
2098  *    Success: Handle to newly created image
2099  *    Failure: NULL
2100  *
2101  * FIXME: implementation still lacks nearly all features, see LR_*
2102  * defines in winuser.h
2103  */
2104 HICON WINAPI CopyImage( HANDLE hnd, UINT type, INT desiredx,
2105                              INT desiredy, UINT flags )
2106 {
2107     switch (type)
2108     {
2109         case IMAGE_BITMAP:
2110         {
2111             HBITMAP res;
2112             BITMAP bm;
2113
2114             if (!GetObjectW( hnd, sizeof(bm), &bm )) return 0;
2115             bm.bmBits = NULL;
2116             if ((res = CreateBitmapIndirect(&bm)))
2117             {
2118                 char *buf = HeapAlloc( GetProcessHeap(), 0, bm.bmWidthBytes * bm.bmHeight );
2119                 GetBitmapBits( hnd, bm.bmWidthBytes * bm.bmHeight, buf );
2120                 SetBitmapBits( res, bm.bmWidthBytes * bm.bmHeight, buf );
2121                 HeapFree( GetProcessHeap(), 0, buf );
2122             }
2123             return (HICON)res;
2124         }
2125         case IMAGE_ICON:
2126                 return CURSORICON_ExtCopy(hnd,type, desiredx, desiredy, flags);
2127         case IMAGE_CURSOR:
2128                 /* Should call CURSORICON_ExtCopy but more testing
2129                  * needs to be done before we change this
2130                  */
2131                 return CopyCursor(hnd);
2132     }
2133     return 0;
2134 }
2135
2136
2137 /******************************************************************************
2138  *              LoadBitmapW (USER32.@) Loads bitmap from the executable file
2139  *
2140  * RETURNS
2141  *    Success: Handle to specified bitmap
2142  *    Failure: NULL
2143  */
2144 HBITMAP WINAPI LoadBitmapW(
2145     HINSTANCE instance, /* [in] Handle to application instance */
2146     LPCWSTR name)         /* [in] Address of bitmap resource name */
2147 {
2148     return LoadImageW( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2149 }
2150
2151 /**********************************************************************
2152  *              LoadBitmapA (USER32.@)
2153  */
2154 HBITMAP WINAPI LoadBitmapA( HINSTANCE instance, LPCSTR name )
2155 {
2156     return LoadImageA( instance, name, IMAGE_BITMAP, 0, 0, 0 );
2157 }