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