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