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