Improvement on the code that deals with setting the color map in
[wine] / objects / palette.c
1 /*
2  * GDI palette objects
3  *
4  * Copyright 1993,1994 Alexandre Julliard
5  * Copyright 1996 Alex Korobka
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * NOTES:
22  * PALETTEOBJ is documented in the Dr. Dobbs Journal May 1993.
23  * Information in the "Undocumented Windows" is incorrect.
24  */
25
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include "windef.h"
31 #include "winbase.h"
32 #include "wingdi.h"
33 #include "wownt32.h"
34 #include "wine/winuser16.h"
35 #include "gdi.h"
36 #include "palette.h"
37 #include "wine/debug.h"
38 #include "winerror.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(palette);
41
42 static INT PALETTE_GetObject( HGDIOBJ handle, void *obj, INT count, LPVOID buffer );
43 static BOOL PALETTE_UnrealizeObject( HGDIOBJ handle, void *obj );
44 static BOOL PALETTE_DeleteObject( HGDIOBJ handle, void *obj );
45
46 static const struct gdi_obj_funcs palette_funcs =
47 {
48     NULL,                     /* pSelectObject */
49     PALETTE_GetObject,        /* pGetObject16 */
50     PALETTE_GetObject,        /* pGetObjectA */
51     PALETTE_GetObject,        /* pGetObjectW */
52     PALETTE_UnrealizeObject,  /* pUnrealizeObject */
53     PALETTE_DeleteObject      /* pDeleteObject */
54 };
55
56 /* Pointers to USER implementation of SelectPalette/RealizePalette */
57 /* they will be patched by USER on startup */
58 HPALETTE (WINAPI *pfnSelectPalette)(HDC hdc, HPALETTE hpal, WORD bkgnd ) = GDISelectPalette;
59 UINT (WINAPI *pfnRealizePalette)(HDC hdc) = GDIRealizePalette;
60
61 static UINT SystemPaletteUse = SYSPAL_STATIC;  /* currently not considered */
62
63 static HPALETTE hPrimaryPalette = 0; /* used for WM_PALETTECHANGED */
64 static HPALETTE hLastRealizedPalette = 0; /* UnrealizeObject() needs it */
65 static const DC_FUNCTIONS *pLastRealizedDC;
66
67 static const PALETTEENTRY sys_pal_template[NB_RESERVED_COLORS] =
68 {
69     /* first 10 entries in the system palette */
70     /* red  green blue  flags */
71     { 0x00, 0x00, 0x00, 0 },
72     { 0x80, 0x00, 0x00, 0 },
73     { 0x00, 0x80, 0x00, 0 },
74     { 0x80, 0x80, 0x00, 0 },
75     { 0x00, 0x00, 0x80, 0 },
76     { 0x80, 0x00, 0x80, 0 },
77     { 0x00, 0x80, 0x80, 0 },
78     { 0xc0, 0xc0, 0xc0, 0 },
79     { 0xc0, 0xdc, 0xc0, 0 },
80     { 0xa6, 0xca, 0xf0, 0 },
81
82     /* ... c_min/2 dynamic colorcells */
83
84     /* ... gap (for sparse palettes) */
85
86     /* ... c_min/2 dynamic colorcells */
87
88     { 0xff, 0xfb, 0xf0, 0 },
89     { 0xa0, 0xa0, 0xa4, 0 },
90     { 0x80, 0x80, 0x80, 0 },
91     { 0xff, 0x00, 0x00, 0 },
92     { 0x00, 0xff, 0x00, 0 },
93     { 0xff, 0xff, 0x00, 0 },
94     { 0x00, 0x00, 0xff, 0 },
95     { 0xff, 0x00, 0xff, 0 },
96     { 0x00, 0xff, 0xff, 0 },
97     { 0xff, 0xff, 0xff, 0 }     /* last 10 */
98 };
99
100 /***********************************************************************
101  *           PALETTE_Init
102  *
103  * Create the system palette.
104  */
105 HPALETTE PALETTE_Init(void)
106 {
107     HPALETTE          hpalette;
108     LOGPALETTE *        palPtr;
109     PALETTEOBJ*         palObj;
110
111     /* create default palette (20 system colors) */
112
113     palPtr = HeapAlloc( GetProcessHeap(), 0,
114              sizeof(LOGPALETTE) + (NB_RESERVED_COLORS-1)*sizeof(PALETTEENTRY));
115     if (!palPtr) return FALSE;
116
117     palPtr->palVersion = 0x300;
118     palPtr->palNumEntries = NB_RESERVED_COLORS;
119     memcpy( palPtr->palPalEntry, sys_pal_template, sizeof(sys_pal_template) );
120     hpalette = CreatePalette( palPtr );
121     HeapFree( GetProcessHeap(), 0, palPtr );
122
123     palObj = (PALETTEOBJ*) GDI_GetObjPtr( hpalette, PALETTE_MAGIC );
124     if (palObj)
125     {
126         if (!(palObj->mapping = HeapAlloc( GetProcessHeap(), 0, sizeof(int) * NB_RESERVED_COLORS )))
127             ERR("Can not create palette mapping -- out of memory!\n");
128         GDI_ReleaseObj( hpalette );
129     }
130     return hpalette;
131 }
132
133 /***********************************************************************
134  *           PALETTE_ValidateFlags
135  */
136 static void PALETTE_ValidateFlags(PALETTEENTRY* lpPalE, int size)
137 {
138     int i = 0;
139     for( ; i<size ; i++ )
140         lpPalE[i].peFlags = PC_SYS_USED | (lpPalE[i].peFlags & 0x07);
141 }
142
143
144 /***********************************************************************
145  * CreatePalette [GDI32.@]  Creates a logical color palette
146  *
147  * RETURNS
148  *    Success: Handle to logical palette
149  *    Failure: NULL
150  */
151 HPALETTE WINAPI CreatePalette(
152     const LOGPALETTE* palette) /* [in] Pointer to logical color palette */
153 {
154     PALETTEOBJ * palettePtr;
155     HPALETTE hpalette;
156     int size;
157
158     if (!palette) return 0;
159     TRACE("entries=%i\n", palette->palNumEntries);
160
161     size = sizeof(LOGPALETTE) + (palette->palNumEntries - 1) * sizeof(PALETTEENTRY);
162
163     if (!(palettePtr = GDI_AllocObject( size + sizeof(int*) +sizeof(GDIOBJHDR),
164                                         PALETTE_MAGIC, (HGDIOBJ *)&hpalette,
165                                         &palette_funcs ))) return 0;
166     memcpy( &palettePtr->logpalette, palette, size );
167     PALETTE_ValidateFlags(palettePtr->logpalette.palPalEntry,
168                           palettePtr->logpalette.palNumEntries);
169     palettePtr->mapping = NULL;
170     GDI_ReleaseObj( hpalette );
171
172     TRACE("   returning %p\n", hpalette);
173     return hpalette;
174 }
175
176
177 /***********************************************************************
178  * CreateHalftonePalette [GDI32.@]  Creates a halftone palette
179  *
180  * RETURNS
181  *    Success: Handle to logical halftone palette
182  *    Failure: 0
183  *
184  * FIXME: This simply creates the halftone palette dirived from runing
185  *        tests on an windows NT machine. this is assuming a color depth
186  *        of greater that 256 color. On a 256 color device the halftone
187  *        palette will be differnt and this funtion will be incorrect
188  */
189 HPALETTE WINAPI CreateHalftonePalette(
190     HDC hdc) /* [in] Handle to device context */
191 {
192     int i;
193     struct {
194         WORD Version;
195         WORD NumberOfEntries;
196         PALETTEENTRY aEntries[256];
197     } Palette;
198
199     Palette.Version = 0x300;
200     Palette.NumberOfEntries = 256;
201     GetSystemPaletteEntries(hdc, 0, 256, Palette.aEntries);
202
203     Palette.NumberOfEntries = 20;
204
205     for (i = 0; i < Palette.NumberOfEntries; i++)
206     {
207         Palette.aEntries[i].peRed=0xff;
208         Palette.aEntries[i].peGreen=0xff;
209         Palette.aEntries[i].peBlue=0xff;
210         Palette.aEntries[i].peFlags=0x00;
211     }
212
213     Palette.aEntries[0].peRed=0x00;
214     Palette.aEntries[0].peBlue=0x00;
215     Palette.aEntries[0].peGreen=0x00;
216
217     /* the first 6 */
218     for (i=1; i <= 6; i++)
219     {
220         Palette.aEntries[i].peRed=(i%2)?0x80:0;
221         Palette.aEntries[i].peGreen=(i==2)?0x80:(i==3)?0x80:(i==6)?0x80:0;
222         Palette.aEntries[i].peBlue=(i>3)?0x80:0;
223     }
224
225     for (i=7;  i <= 12; i++)
226     {
227         switch(i)
228         {
229             case 7:
230                 Palette.aEntries[i].peRed=0xc0;
231                 Palette.aEntries[i].peBlue=0xc0;
232                 Palette.aEntries[i].peGreen=0xc0;
233                 break;
234             case 8:
235                 Palette.aEntries[i].peRed=0xc0;
236                 Palette.aEntries[i].peGreen=0xdc;
237                 Palette.aEntries[i].peBlue=0xc0;
238                 break;
239             case 9:
240                 Palette.aEntries[i].peRed=0xa6;
241                 Palette.aEntries[i].peGreen=0xca;
242                 Palette.aEntries[i].peBlue=0xf0;
243                 break;
244             case 10:
245                 Palette.aEntries[i].peRed=0xff;
246                 Palette.aEntries[i].peGreen=0xfb;
247                 Palette.aEntries[i].peBlue=0xf0;
248                 break;
249             case 11:
250                 Palette.aEntries[i].peRed=0xa0;
251                 Palette.aEntries[i].peGreen=0xa0;
252                 Palette.aEntries[i].peBlue=0xa4;
253                 break;
254             case 12:
255                 Palette.aEntries[i].peRed=0x80;
256                 Palette.aEntries[i].peGreen=0x80;
257                 Palette.aEntries[i].peBlue=0x80;
258         }
259     }
260
261    for (i=13; i <= 18; i++)
262     {
263         Palette.aEntries[i].peRed=(i%2)?0xff:0;
264         Palette.aEntries[i].peGreen=(i==14)?0xff:(i==15)?0xff:(i==18)?0xff:0;
265         Palette.aEntries[i].peBlue=(i>15)?0xff:0x00;
266     }
267
268     return CreatePalette((LOGPALETTE *)&Palette);
269 }
270
271
272 /***********************************************************************
273  * GetPaletteEntries [GDI32.@]  Retrieves palette entries
274  *
275  * RETURNS
276  *    Success: Number of entries from logical palette
277  *    Failure: 0
278  */
279 UINT WINAPI GetPaletteEntries(
280     HPALETTE hpalette,    /* [in]  Handle of logical palette */
281     UINT start,           /* [in]  First entry to receive */
282     UINT count,           /* [in]  Number of entries to receive */
283     LPPALETTEENTRY entries) /* [out] Address of array receiving entries */
284 {
285     PALETTEOBJ * palPtr;
286     UINT numEntries;
287
288     TRACE("hpal = %p, count=%i\n", hpalette, count );
289
290     palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hpalette, PALETTE_MAGIC );
291     if (!palPtr) return 0;
292
293     /* NOTE: not documented but test show this to be the case */
294     if (count == 0)
295     {
296         int rc = palPtr->logpalette.palNumEntries;
297             GDI_ReleaseObj( hpalette );
298         return rc;
299     }
300
301     numEntries = palPtr->logpalette.palNumEntries;
302     if (start+count > numEntries) count = numEntries - start;
303     if (entries)
304     {
305       if (start >= numEntries)
306       {
307         GDI_ReleaseObj( hpalette );
308         return 0;
309       }
310       memcpy( entries, &palPtr->logpalette.palPalEntry[start],
311               count * sizeof(PALETTEENTRY) );
312       for( numEntries = 0; numEntries < count ; numEntries++ )
313            if (entries[numEntries].peFlags & 0xF0)
314                entries[numEntries].peFlags = 0;
315     }
316
317     GDI_ReleaseObj( hpalette );
318     return count;
319 }
320
321
322 /***********************************************************************
323  * SetPaletteEntries [GDI32.@]  Sets color values for range in palette
324  *
325  * RETURNS
326  *    Success: Number of entries that were set
327  *    Failure: 0
328  */
329 UINT WINAPI SetPaletteEntries(
330     HPALETTE hpalette,    /* [in] Handle of logical palette */
331     UINT start,           /* [in] Index of first entry to set */
332     UINT count,           /* [in] Number of entries to set */
333     const PALETTEENTRY *entries) /* [in] Address of array of structures */
334 {
335     PALETTEOBJ * palPtr;
336     UINT numEntries;
337
338     TRACE("hpal=%p,start=%i,count=%i\n",hpalette,start,count );
339
340     if (hpalette == GetStockObject(DEFAULT_PALETTE)) return 0;
341     palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hpalette, PALETTE_MAGIC );
342     if (!palPtr) return 0;
343
344     numEntries = palPtr->logpalette.palNumEntries;
345     if (start >= numEntries)
346     {
347       GDI_ReleaseObj( hpalette );
348       return 0;
349     }
350     if (start+count > numEntries) count = numEntries - start;
351     memcpy( &palPtr->logpalette.palPalEntry[start], entries,
352             count * sizeof(PALETTEENTRY) );
353     PALETTE_ValidateFlags(palPtr->logpalette.palPalEntry,
354                           palPtr->logpalette.palNumEntries);
355     UnrealizeObject( hpalette );
356     GDI_ReleaseObj( hpalette );
357     return count;
358 }
359
360
361 /***********************************************************************
362  * ResizePalette [GDI32.@]  Resizes logical palette
363  *
364  * RETURNS
365  *    Success: TRUE
366  *    Failure: FALSE
367  */
368 BOOL WINAPI ResizePalette(
369     HPALETTE hPal, /* [in] Handle of logical palette */
370     UINT cEntries) /* [in] Number of entries in logical palette */
371 {
372     PALETTEOBJ * palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hPal, PALETTE_MAGIC );
373     UINT         cPrevEnt, prevVer;
374     int          prevsize, size = sizeof(LOGPALETTE) + (cEntries - 1) * sizeof(PALETTEENTRY);
375     int*         mapping = NULL;
376
377     TRACE("hpal = %p, prev = %i, new = %i\n",
378           hPal, palPtr ? palPtr->logpalette.palNumEntries : -1, cEntries );
379     if( !palPtr ) return FALSE;
380     cPrevEnt = palPtr->logpalette.palNumEntries;
381     prevVer = palPtr->logpalette.palVersion;
382     prevsize = sizeof(LOGPALETTE) + (cPrevEnt - 1) * sizeof(PALETTEENTRY) +
383                                         sizeof(int*) + sizeof(GDIOBJHDR);
384     size += sizeof(int*) + sizeof(GDIOBJHDR);
385     mapping = palPtr->mapping;
386
387     if (!(palPtr = GDI_ReallocObject( size, hPal, palPtr ))) return FALSE;
388
389     if( mapping )
390     {
391         int *newMap = (int*) HeapReAlloc(GetProcessHeap(), 0,
392                                     mapping, cEntries * sizeof(int) );
393         if(newMap == NULL)
394         {
395             ERR("Can not resize mapping -- out of memory!\n");
396             GDI_ReleaseObj( hPal );
397             return FALSE;
398         }
399         palPtr->mapping = newMap;
400     }
401
402     if( cEntries > cPrevEnt )
403     {
404         if( mapping )
405             memset(palPtr->mapping + cPrevEnt, 0, (cEntries - cPrevEnt)*sizeof(int));
406         memset( (BYTE*)palPtr + prevsize, 0, size - prevsize );
407         PALETTE_ValidateFlags((PALETTEENTRY*)((BYTE*)palPtr + prevsize),
408                                                      cEntries - cPrevEnt );
409     }
410     palPtr->logpalette.palNumEntries = cEntries;
411     palPtr->logpalette.palVersion = prevVer;
412     GDI_ReleaseObj( hPal );
413     return TRUE;
414 }
415
416
417 /***********************************************************************
418  * AnimatePalette [GDI32.@]  Replaces entries in logical palette
419  *
420  * RETURNS
421  *    Success: TRUE
422  *    Failure: FALSE
423  *
424  * FIXME
425  *    Should use existing mapping when animating a primary palette
426  */
427 BOOL WINAPI AnimatePalette(
428     HPALETTE hPal,              /* [in] Handle to logical palette */
429     UINT StartIndex,            /* [in] First entry in palette */
430     UINT NumEntries,            /* [in] Count of entries in palette */
431     const PALETTEENTRY* PaletteColors) /* [in] Pointer to first replacement */
432 {
433     TRACE("%p (%i - %i)\n", hPal, StartIndex,StartIndex+NumEntries);
434
435     if( hPal != GetStockObject(DEFAULT_PALETTE) )
436     {
437         if (!SetPaletteEntries( hPal, StartIndex, NumEntries, PaletteColors )) return FALSE;
438
439         if (pLastRealizedDC && pLastRealizedDC->pRealizePalette)
440             pLastRealizedDC->pRealizePalette( NULL, hPal, hPal == hPrimaryPalette );
441     }
442     return TRUE;
443 }
444
445
446 /***********************************************************************
447  * SetSystemPaletteUse [GDI32.@]
448  *
449  * RETURNS
450  *    Success: Previous system palette
451  *    Failure: SYSPAL_ERROR
452  */
453 UINT WINAPI SetSystemPaletteUse(
454     HDC hdc,  /* [in] Handle of device context */
455     UINT use) /* [in] Palette-usage flag */
456 {
457     UINT old = SystemPaletteUse;
458
459     /* Device doesn't support colour palettes */
460     if (!(GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE)) {
461         return SYSPAL_ERROR;
462     }
463
464     switch (use) {
465         case SYSPAL_NOSTATIC:
466         case SYSPAL_NOSTATIC256:        /* WINVER >= 0x0500 */
467         case SYSPAL_STATIC:
468             SystemPaletteUse = use;
469             return old;
470         default:
471             return SYSPAL_ERROR;
472     }
473 }
474
475
476 /***********************************************************************
477  * GetSystemPaletteUse [GDI32.@]  Gets state of system palette
478  *
479  * RETURNS
480  *    Current state of system palette
481  */
482 UINT WINAPI GetSystemPaletteUse(
483     HDC hdc) /* [in] Handle of device context */
484 {
485     return SystemPaletteUse;
486 }
487
488
489 /***********************************************************************
490  * GetSystemPaletteEntries [GDI32.@]  Gets range of palette entries
491  *
492  * RETURNS
493  *    Success: Number of entries retrieved from palette
494  *    Failure: 0
495  */
496 UINT WINAPI GetSystemPaletteEntries(
497     HDC hdc,              /* [in]  Handle of device context */
498     UINT start,           /* [in]  Index of first entry to be retrieved */
499     UINT count,           /* [in]  Number of entries to be retrieved */
500     LPPALETTEENTRY entries) /* [out] Array receiving system-palette entries */
501 {
502     UINT ret = 0;
503     DC *dc;
504
505     TRACE("hdc=%p,start=%i,count=%i\n", hdc,start,count);
506
507     if ((dc = DC_GetDCPtr( hdc )))
508     {
509         if (dc->funcs->pGetSystemPaletteEntries)
510             ret = dc->funcs->pGetSystemPaletteEntries( dc->physDev, start, count, entries );
511         GDI_ReleaseObj( hdc );
512     }
513     return ret;
514 }
515
516
517 /***********************************************************************
518  * GetNearestPaletteIndex [GDI32.@]  Gets palette index for color
519  *
520  * NOTES
521  *    Should index be initialized to CLR_INVALID instead of 0?
522  *
523  * RETURNS
524  *    Success: Index of entry in logical palette
525  *    Failure: CLR_INVALID
526  */
527 UINT WINAPI GetNearestPaletteIndex(
528     HPALETTE hpalette, /* [in] Handle of logical color palette */
529     COLORREF color)      /* [in] Color to be matched */
530 {
531     PALETTEOBJ* palObj = (PALETTEOBJ*)GDI_GetObjPtr( hpalette, PALETTE_MAGIC );
532     UINT index  = 0;
533
534     if( palObj )
535     {
536         int i, diff = 0x7fffffff;
537         int r,g,b;
538         PALETTEENTRY* entry = palObj->logpalette.palPalEntry;
539
540         for( i = 0; i < palObj->logpalette.palNumEntries && diff ; i++, entry++)
541         {
542             if (!(entry->peFlags & PC_SYS_USED)) continue;
543
544             r = entry->peRed - GetRValue(color);
545             g = entry->peGreen - GetGValue(color);
546             b = entry->peBlue - GetBValue(color);
547
548             r = r*r + g*g + b*b;
549
550             if( r < diff ) { index = i; diff = r; }
551         }
552         GDI_ReleaseObj( hpalette );
553     }
554     TRACE("(%p,%06lx): returning %d\n", hpalette, color, index );
555     return index;
556 }
557
558
559 /***********************************************************************
560  * GetNearestColor [GDI32.@]  Gets a system color to match
561  *
562  * RETURNS
563  *    Success: Color from system palette that corresponds to given color
564  *    Failure: CLR_INVALID
565  */
566 COLORREF WINAPI GetNearestColor(
567     HDC hdc,      /* [in] Handle of device context */
568     COLORREF color) /* [in] Color to be matched */
569 {
570     unsigned char spec_type;
571     COLORREF nearest;
572     DC          *dc;
573
574     if (!(dc = DC_GetDCPtr( hdc ))) return CLR_INVALID;
575
576     if (dc->funcs->pGetNearestColor)
577     {
578         nearest = dc->funcs->pGetNearestColor( dc->physDev, color );
579         GDI_ReleaseObj( hdc );
580         return nearest;
581     }
582
583     if (!(GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE))
584     {
585         GDI_ReleaseObj( hdc );
586         return color;
587     }
588
589     spec_type = color >> 24;
590     if (spec_type == 1 || spec_type == 2)
591     {
592         /* we need logical palette for PALETTERGB and PALETTEINDEX colorrefs */
593
594         UINT index;
595         PALETTEENTRY entry;
596         HPALETTE hpal = dc->hPalette ? dc->hPalette : GetStockObject( DEFAULT_PALETTE );
597
598         if (spec_type == 2) /* PALETTERGB */
599             index = GetNearestPaletteIndex( hpal, color );
600         else  /* PALETTEINDEX */
601             index = LOWORD(color);
602
603         if (!GetPaletteEntries( hpal, index, 1, &entry ))
604         {
605             WARN("RGB(%lx) : idx %d is out of bounds, assuming NULL\n", color, index );
606             if (!GetPaletteEntries( hpal, 0, 1, &entry ))
607             {
608                 GDI_ReleaseObj( hdc );
609                 return CLR_INVALID;
610             }
611         }
612         color = RGB( entry.peRed, entry.peGreen, entry.peBlue );
613     }
614     nearest = color & 0x00ffffff;
615     GDI_ReleaseObj( hdc );
616
617     TRACE("(%06lx): returning %06lx\n", color, nearest );
618     return nearest;
619 }
620
621
622 /***********************************************************************
623  *           PALETTE_GetObject
624  */
625 static INT PALETTE_GetObject( HGDIOBJ handle, void *obj, INT count, LPVOID buffer )
626 {
627     PALETTEOBJ *palette = obj;
628
629     if( !buffer )
630         return sizeof(WORD);
631
632     if (count > sizeof(WORD)) count = sizeof(WORD);
633     memcpy( buffer, &palette->logpalette.palNumEntries, count );
634     return count;
635 }
636
637
638 /***********************************************************************
639  *           PALETTE_UnrealizeObject
640  */
641 static BOOL PALETTE_UnrealizeObject( HGDIOBJ handle, void *obj )
642 {
643     PALETTEOBJ *palette = obj;
644
645     if (palette->mapping)
646     {
647         HeapFree( GetProcessHeap(), 0, palette->mapping );
648         palette->mapping = NULL;
649     }
650     if (hLastRealizedPalette == handle)
651     {
652         hLastRealizedPalette = 0;
653         pLastRealizedDC = NULL;
654     }
655     return TRUE;
656 }
657
658
659 /***********************************************************************
660  *           PALETTE_DeleteObject
661  */
662 static BOOL PALETTE_DeleteObject( HGDIOBJ handle, void *obj )
663 {
664     PALETTEOBJ *palette = obj;
665
666     HeapFree( GetProcessHeap(), 0, palette->mapping );
667     if (hLastRealizedPalette == handle)
668     {
669         hLastRealizedPalette = 0;
670         pLastRealizedDC = NULL;
671     }
672     return GDI_FreeObject( handle, obj );
673 }
674
675
676 /***********************************************************************
677  *           GDISelectPalette    (Not a Windows API)
678  */
679 HPALETTE WINAPI GDISelectPalette( HDC hdc, HPALETTE hpal, WORD wBkg)
680 {
681     HPALETTE ret;
682     DC *dc;
683
684     TRACE("%p %p\n", hdc, hpal );
685
686     if (GetObjectType(hpal) != OBJ_PAL)
687     {
688       WARN("invalid selected palette %p\n",hpal);
689       return 0;
690     }
691     if (!(dc = DC_GetDCPtr( hdc ))) return 0;
692     ret = dc->hPalette;
693     if (dc->funcs->pSelectPalette) hpal = dc->funcs->pSelectPalette( dc->physDev, hpal, FALSE );
694     if (hpal)
695     {
696         dc->hPalette = hpal;
697         if (!wBkg) hPrimaryPalette = hpal;
698     }
699     else ret = 0;
700     GDI_ReleaseObj( hdc );
701     return ret;
702 }
703
704
705 /***********************************************************************
706  *           GDIRealizePalette    (Not a Windows API)
707  */
708 UINT WINAPI GDIRealizePalette( HDC hdc )
709 {
710     UINT realized = 0;
711     DC* dc = DC_GetDCPtr( hdc );
712
713     if (!dc) return 0;
714
715     TRACE("%p...\n", hdc );
716
717     if( dc->hPalette == GetStockObject( DEFAULT_PALETTE ))
718     {
719         if (dc->funcs->pRealizeDefaultPalette)
720             realized = dc->funcs->pRealizeDefaultPalette( dc->physDev );
721     }
722     else if(dc->hPalette != hLastRealizedPalette )
723     {
724         if (dc->funcs->pRealizePalette)
725             realized = dc->funcs->pRealizePalette( dc->physDev, dc->hPalette,
726                                                    (dc->hPalette == hPrimaryPalette) );
727         hLastRealizedPalette = dc->hPalette;
728         pLastRealizedDC = dc->funcs;
729     }
730     else TRACE("  skipping (hLastRealizedPalette = %p)\n", hLastRealizedPalette);
731
732     GDI_ReleaseObj( hdc );
733     TRACE("   realized %i colors.\n", realized );
734     return realized;
735 }
736
737
738 /***********************************************************************
739  *           RealizeDefaultPalette    (GDI.365)
740  */
741 UINT16 WINAPI RealizeDefaultPalette16( HDC16 hdc )
742 {
743     UINT16 ret = 0;
744     DC          *dc;
745
746     TRACE("%04x\n", hdc );
747
748     if (!(dc = DC_GetDCPtr( HDC_32(hdc) ))) return 0;
749
750     if (dc->funcs->pRealizeDefaultPalette) ret = dc->funcs->pRealizeDefaultPalette( dc->physDev );
751     GDI_ReleaseObj( HDC_32(hdc) );
752     return ret;
753 }
754
755 /***********************************************************************
756  *           IsDCCurrentPalette   (GDI.412)
757  */
758 BOOL16 WINAPI IsDCCurrentPalette16(HDC16 hDC)
759 {
760     DC *dc = DC_GetDCPtr( HDC_32(hDC) );
761     if (dc)
762     {
763       BOOL bRet = dc->hPalette == hPrimaryPalette;
764       GDI_ReleaseObj( HDC_32(hDC) );
765       return bRet;
766     }
767     return FALSE;
768 }
769
770
771 /***********************************************************************
772  * SelectPalette [GDI32.@]  Selects logical palette into DC
773  *
774  * RETURNS
775  *    Success: Previous logical palette
776  *    Failure: NULL
777  */
778 HPALETTE WINAPI SelectPalette(
779     HDC hDC,               /* [in] Handle of device context */
780     HPALETTE hPal,         /* [in] Handle of logical color palette */
781     BOOL bForceBackground) /* [in] Foreground/background mode */
782 {
783     return pfnSelectPalette( hDC, hPal, bForceBackground );
784 }
785
786
787 /***********************************************************************
788  * RealizePalette [GDI32.@]  Maps palette entries to system palette
789  *
790  * RETURNS
791  *    Success: Number of entries in logical palette
792  *    Failure: GDI_ERROR
793  */
794 UINT WINAPI RealizePalette(
795     HDC hDC) /* [in] Handle of device context */
796 {
797     return pfnRealizePalette( hDC );
798 }
799
800
801 typedef HWND (WINAPI *WindowFromDC_funcptr)( HDC );
802 typedef BOOL (WINAPI *RedrawWindow_funcptr)( HWND, const RECT *, HRGN, UINT );
803
804 /**********************************************************************
805  * UpdateColors [GDI32.@]  Remaps current colors to logical palette
806  *
807  * RETURNS
808  *    Success: TRUE
809  *    Failure: FALSE
810  */
811 BOOL WINAPI UpdateColors(
812     HDC hDC) /* [in] Handle of device context */
813 {
814     HMODULE mod;
815     int size = GetDeviceCaps( hDC, SIZEPALETTE );
816
817     if (!size) return 0;
818
819     mod = GetModuleHandleA("user32.dll");
820     if (mod)
821     {
822         WindowFromDC_funcptr pWindowFromDC = (WindowFromDC_funcptr)GetProcAddress(mod,"WindowFromDC");
823         if (pWindowFromDC)
824         {
825             HWND hWnd = pWindowFromDC( hDC );
826
827             /* Docs say that we have to remap current drawable pixel by pixel
828              * but it would take forever given the speed of XGet/PutPixel.
829              */
830             if (hWnd && size)
831             {
832                 RedrawWindow_funcptr pRedrawWindow = GetProcAddress( mod, "RedrawWindow" );
833                 if (pRedrawWindow) pRedrawWindow( hWnd, NULL, 0, RDW_INVALIDATE );
834             }
835         }
836     }
837     return 0x666;
838 }
839
840
841 /*********************************************************************
842  *           SetMagicColors   (GDI.606)
843  */
844 VOID WINAPI SetMagicColors16(HDC16 hDC, COLORREF color, UINT16 index)
845 {
846     FIXME("(hDC %04x, color %04x, index %04x): stub\n", hDC, (int)color, index);
847
848 }
849
850 /**********************************************************************
851  * GetICMProfileA [GDI32.@]
852  *
853  * Returns the filename of the specified device context's color
854  * management profile, even if color management is not enabled
855  * for that DC.
856  *
857  * RETURNS
858  *    TRUE if name copied successfully OR lpszFilename is NULL
859  *    FALSE if the buffer length pointed to by lpcbName is too small
860  *
861  * NOTE
862  *    The buffer length pointed to by lpcbName is ALWAYS updated to
863  *    the length required regardless of other actions this function
864  *    may take.
865  *
866  * FIXME
867  *    How does Windows assign these?  Some registry key?
868  */
869
870 #define WINEICM "winefake.icm"  /* easy-to-identify fake filename */
871
872 /*********************************************************************/
873
874 BOOL WINAPI GetICMProfileA(HDC hDC, LPDWORD lpcbName, LPSTR lpszFilename)
875 {
876     DWORD callerLen;
877
878     FIXME("(%p, %p, %p): partial stub\n", hDC, lpcbName, lpszFilename);
879
880     callerLen = *lpcbName;
881
882     /* all 3 behaviors require the required buffer size to be set */
883     *lpcbName = strlen(WINEICM);
884
885     /* behavior 1: if lpszFilename is NULL, return size of string and no error */
886     if ((DWORD)lpszFilename == (DWORD)0x00000000)
887         return TRUE;
888
889     /* behavior 2: if buffer size too small, return size of string and error */
890     if (callerLen < strlen(WINEICM))
891     {
892         SetLastError(ERROR_INSUFFICIENT_BUFFER);
893         return FALSE;
894     }
895
896     /* behavior 3: if buffer size OK and pointer not NULL, copy and return size */
897     strcpy(lpszFilename, WINEICM);
898     return TRUE;
899 }