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