winspool: Remove cross calls W->A for the "Printers" registry path.
[wine] / dlls / gdi / 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 "gdi_private.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("Cannot 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.@]
146  *
147  * Creates a logical color palette.
148  *
149  * RETURNS
150  *    Success: Handle to logical palette
151  *    Failure: NULL
152  */
153 HPALETTE WINAPI CreatePalette(
154     const LOGPALETTE* palette) /* [in] Pointer to logical color palette */
155 {
156     PALETTEOBJ * palettePtr;
157     HPALETTE hpalette;
158     int size;
159
160     if (!palette) return 0;
161     TRACE("entries=%i\n", palette->palNumEntries);
162
163     size = sizeof(LOGPALETTE) + (palette->palNumEntries - 1) * sizeof(PALETTEENTRY);
164
165     if (!(palettePtr = GDI_AllocObject( size + sizeof(int*) +sizeof(GDIOBJHDR),
166                                         PALETTE_MAGIC, (HGDIOBJ *)&hpalette,
167                                         &palette_funcs ))) return 0;
168     memcpy( &palettePtr->logpalette, palette, size );
169     PALETTE_ValidateFlags(palettePtr->logpalette.palPalEntry,
170                           palettePtr->logpalette.palNumEntries);
171     palettePtr->mapping = NULL;
172     GDI_ReleaseObj( hpalette );
173
174     TRACE("   returning %p\n", hpalette);
175     return hpalette;
176 }
177
178
179 /***********************************************************************
180  * CreateHalftonePalette [GDI32.@]
181  *
182  * Creates a halftone palette.
183  *
184  * RETURNS
185  *    Success: Handle to logical halftone palette
186  *    Failure: 0
187  *
188  * FIXME: This simply creates the halftone palette derived from running
189  *        tests on a windows NT machine. This is assuming a color depth
190  *        of greater that 256 color. On a 256 color device the halftone
191  *        palette will be different and this function will be incorrect
192  */
193 HPALETTE WINAPI CreateHalftonePalette(
194     HDC hdc) /* [in] Handle to device context */
195 {
196     int i;
197     struct {
198         WORD Version;
199         WORD NumberOfEntries;
200         PALETTEENTRY aEntries[256];
201     } Palette;
202
203     Palette.Version = 0x300;
204     Palette.NumberOfEntries = 256;
205     GetSystemPaletteEntries(hdc, 0, 256, Palette.aEntries);
206
207     Palette.NumberOfEntries = 20;
208
209     for (i = 0; i < Palette.NumberOfEntries; i++)
210     {
211         Palette.aEntries[i].peRed=0xff;
212         Palette.aEntries[i].peGreen=0xff;
213         Palette.aEntries[i].peBlue=0xff;
214         Palette.aEntries[i].peFlags=0x00;
215     }
216
217     Palette.aEntries[0].peRed=0x00;
218     Palette.aEntries[0].peBlue=0x00;
219     Palette.aEntries[0].peGreen=0x00;
220
221     /* the first 6 */
222     for (i=1; i <= 6; i++)
223     {
224         Palette.aEntries[i].peRed=(i%2)?0x80:0;
225         Palette.aEntries[i].peGreen=(i==2)?0x80:(i==3)?0x80:(i==6)?0x80:0;
226         Palette.aEntries[i].peBlue=(i>3)?0x80:0;
227     }
228
229     for (i=7;  i <= 12; i++)
230     {
231         switch(i)
232         {
233             case 7:
234                 Palette.aEntries[i].peRed=0xc0;
235                 Palette.aEntries[i].peBlue=0xc0;
236                 Palette.aEntries[i].peGreen=0xc0;
237                 break;
238             case 8:
239                 Palette.aEntries[i].peRed=0xc0;
240                 Palette.aEntries[i].peGreen=0xdc;
241                 Palette.aEntries[i].peBlue=0xc0;
242                 break;
243             case 9:
244                 Palette.aEntries[i].peRed=0xa6;
245                 Palette.aEntries[i].peGreen=0xca;
246                 Palette.aEntries[i].peBlue=0xf0;
247                 break;
248             case 10:
249                 Palette.aEntries[i].peRed=0xff;
250                 Palette.aEntries[i].peGreen=0xfb;
251                 Palette.aEntries[i].peBlue=0xf0;
252                 break;
253             case 11:
254                 Palette.aEntries[i].peRed=0xa0;
255                 Palette.aEntries[i].peGreen=0xa0;
256                 Palette.aEntries[i].peBlue=0xa4;
257                 break;
258             case 12:
259                 Palette.aEntries[i].peRed=0x80;
260                 Palette.aEntries[i].peGreen=0x80;
261                 Palette.aEntries[i].peBlue=0x80;
262         }
263     }
264
265    for (i=13; i <= 18; i++)
266     {
267         Palette.aEntries[i].peRed=(i%2)?0xff:0;
268         Palette.aEntries[i].peGreen=(i==14)?0xff:(i==15)?0xff:(i==18)?0xff:0;
269         Palette.aEntries[i].peBlue=(i>15)?0xff:0x00;
270     }
271
272     return CreatePalette((LOGPALETTE *)&Palette);
273 }
274
275
276 /***********************************************************************
277  * GetPaletteEntries [GDI32.@]
278  *
279  * Retrieves palette entries.
280  *
281  * RETURNS
282  *    Success: Number of entries from logical palette
283  *    Failure: 0
284  */
285 UINT WINAPI GetPaletteEntries(
286     HPALETTE hpalette,    /* [in]  Handle of logical palette */
287     UINT start,           /* [in]  First entry to receive */
288     UINT count,           /* [in]  Number of entries to receive */
289     LPPALETTEENTRY entries) /* [out] Address of array receiving entries */
290 {
291     PALETTEOBJ * palPtr;
292     UINT numEntries;
293
294     TRACE("hpal = %p, count=%i\n", hpalette, count );
295
296     palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hpalette, PALETTE_MAGIC );
297     if (!palPtr) return 0;
298
299     /* NOTE: not documented but test show this to be the case */
300     if (count == 0)
301     {
302         int rc = palPtr->logpalette.palNumEntries;
303             GDI_ReleaseObj( hpalette );
304         return rc;
305     }
306
307     numEntries = palPtr->logpalette.palNumEntries;
308     if (start+count > numEntries) count = numEntries - start;
309     if (entries)
310     {
311       if (start >= numEntries)
312       {
313         GDI_ReleaseObj( hpalette );
314         return 0;
315       }
316       memcpy( entries, &palPtr->logpalette.palPalEntry[start],
317               count * sizeof(PALETTEENTRY) );
318       for( numEntries = 0; numEntries < count ; numEntries++ )
319            if (entries[numEntries].peFlags & 0xF0)
320                entries[numEntries].peFlags = 0;
321     }
322
323     GDI_ReleaseObj( hpalette );
324     return count;
325 }
326
327
328 /***********************************************************************
329  * SetPaletteEntries [GDI32.@]
330  *
331  * Sets color values for range in palette.
332  *
333  * RETURNS
334  *    Success: Number of entries that were set
335  *    Failure: 0
336  */
337 UINT WINAPI SetPaletteEntries(
338     HPALETTE hpalette,    /* [in] Handle of logical palette */
339     UINT start,           /* [in] Index of first entry to set */
340     UINT count,           /* [in] Number of entries to set */
341     const PALETTEENTRY *entries) /* [in] Address of array of structures */
342 {
343     PALETTEOBJ * palPtr;
344     UINT numEntries;
345
346     TRACE("hpal=%p,start=%i,count=%i\n",hpalette,start,count );
347
348     if (hpalette == GetStockObject(DEFAULT_PALETTE)) return 0;
349     palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hpalette, PALETTE_MAGIC );
350     if (!palPtr) return 0;
351
352     numEntries = palPtr->logpalette.palNumEntries;
353     if (start >= numEntries)
354     {
355       GDI_ReleaseObj( hpalette );
356       return 0;
357     }
358     if (start+count > numEntries) count = numEntries - start;
359     memcpy( &palPtr->logpalette.palPalEntry[start], entries,
360             count * sizeof(PALETTEENTRY) );
361     PALETTE_ValidateFlags(palPtr->logpalette.palPalEntry,
362                           palPtr->logpalette.palNumEntries);
363     UnrealizeObject( hpalette );
364     GDI_ReleaseObj( hpalette );
365     return count;
366 }
367
368
369 /***********************************************************************
370  * ResizePalette [GDI32.@]
371  *
372  * Resizes logical palette.
373  *
374  * RETURNS
375  *    Success: TRUE
376  *    Failure: FALSE
377  */
378 BOOL WINAPI ResizePalette(
379     HPALETTE hPal, /* [in] Handle of logical palette */
380     UINT cEntries) /* [in] Number of entries in logical palette */
381 {
382     PALETTEOBJ * palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hPal, PALETTE_MAGIC );
383     UINT         cPrevEnt, prevVer;
384     int          prevsize, size = sizeof(LOGPALETTE) + (cEntries - 1) * sizeof(PALETTEENTRY);
385     int*         mapping = NULL;
386
387     TRACE("hpal = %p, prev = %i, new = %i\n",
388           hPal, palPtr ? palPtr->logpalette.palNumEntries : -1, cEntries );
389     if( !palPtr ) return FALSE;
390     cPrevEnt = palPtr->logpalette.palNumEntries;
391     prevVer = palPtr->logpalette.palVersion;
392     prevsize = sizeof(LOGPALETTE) + (cPrevEnt - 1) * sizeof(PALETTEENTRY) +
393                                         sizeof(int*) + sizeof(GDIOBJHDR);
394     size += sizeof(int*) + sizeof(GDIOBJHDR);
395     mapping = palPtr->mapping;
396
397     if (!(palPtr = GDI_ReallocObject( size, hPal, palPtr ))) return FALSE;
398
399     if( mapping )
400     {
401         int *newMap = HeapReAlloc(GetProcessHeap(), 0, mapping, cEntries * sizeof(int) );
402         if(newMap == NULL)
403         {
404             ERR("Cannot resize mapping -- out of memory!\n");
405             GDI_ReleaseObj( hPal );
406             return FALSE;
407         }
408         palPtr->mapping = newMap;
409     }
410
411     if( cEntries > cPrevEnt )
412     {
413         if( mapping )
414             memset(palPtr->mapping + cPrevEnt, 0, (cEntries - cPrevEnt)*sizeof(int));
415         memset( (BYTE*)palPtr + prevsize, 0, size - prevsize );
416         PALETTE_ValidateFlags((PALETTEENTRY*)((BYTE*)palPtr + prevsize),
417                                                      cEntries - cPrevEnt );
418     }
419     palPtr->logpalette.palNumEntries = cEntries;
420     palPtr->logpalette.palVersion = prevVer;
421     GDI_ReleaseObj( hPal );
422     return TRUE;
423 }
424
425
426 /***********************************************************************
427  * AnimatePalette [GDI32.@]
428  *
429  * Replaces entries in logical palette.
430  *
431  * RETURNS
432  *    Success: TRUE
433  *    Failure: FALSE
434  *
435  * FIXME
436  *    Should use existing mapping when animating a primary palette
437  */
438 BOOL WINAPI AnimatePalette(
439     HPALETTE hPal,              /* [in] Handle to logical palette */
440     UINT StartIndex,            /* [in] First entry in palette */
441     UINT NumEntries,            /* [in] Count of entries in palette */
442     const PALETTEENTRY* PaletteColors) /* [in] Pointer to first replacement */
443 {
444     TRACE("%p (%i - %i)\n", hPal, StartIndex,StartIndex+NumEntries);
445
446     if( hPal != GetStockObject(DEFAULT_PALETTE) )
447     {
448         PALETTEOBJ * palPtr;
449         UINT pal_entries;
450         const PALETTEENTRY *pptr = PaletteColors;
451
452         palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hPal, PALETTE_MAGIC );
453         if (!palPtr) return 0;
454
455         pal_entries = palPtr->logpalette.palNumEntries;
456         if (StartIndex >= pal_entries)
457         {
458           GDI_ReleaseObj( hPal );
459           return 0;
460         }
461         if (StartIndex+NumEntries > pal_entries) NumEntries = pal_entries - StartIndex;
462         
463         for (NumEntries += StartIndex; StartIndex < NumEntries; StartIndex++, pptr++) {
464           /* According to MSDN, only animate PC_RESERVED colours */
465           if (palPtr->logpalette.palPalEntry[StartIndex].peFlags & PC_RESERVED) {
466             TRACE("Animating colour (%d,%d,%d) to (%d,%d,%d)\n",
467               palPtr->logpalette.palPalEntry[StartIndex].peRed,
468               palPtr->logpalette.palPalEntry[StartIndex].peGreen,
469               palPtr->logpalette.palPalEntry[StartIndex].peBlue,
470               pptr->peRed, pptr->peGreen, pptr->peBlue);
471             memcpy( &palPtr->logpalette.palPalEntry[StartIndex], pptr,
472                     sizeof(PALETTEENTRY) );
473             PALETTE_ValidateFlags(&palPtr->logpalette.palPalEntry[StartIndex], 1);
474           } else {
475             TRACE("Not animating entry %d -- not PC_RESERVED\n", StartIndex);
476           }
477         }
478         
479         GDI_ReleaseObj( hPal );
480         
481         TRACE("pLastRealizedDC %p -- pLastRealizedDC->pRealizePalette %p\n",
482           pLastRealizedDC, pLastRealizedDC ? pLastRealizedDC->pRealizePalette : 0);
483
484         if (pLastRealizedDC && pLastRealizedDC->pRealizePalette)
485             pLastRealizedDC->pRealizePalette( NULL, hPal, hPal == hPrimaryPalette );
486     }
487     return TRUE;
488 }
489
490
491 /***********************************************************************
492  * SetSystemPaletteUse [GDI32.@]
493  *
494  * Specify whether the system palette contains 2 or 20 static colors.
495  *
496  * RETURNS
497  *    Success: Previous system palette
498  *    Failure: SYSPAL_ERROR
499  */
500 UINT WINAPI SetSystemPaletteUse(
501     HDC hdc,  /* [in] Handle of device context */
502     UINT use) /* [in] Palette-usage flag */
503 {
504     UINT old = SystemPaletteUse;
505
506     /* Device doesn't support colour palettes */
507     if (!(GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE)) {
508         return SYSPAL_ERROR;
509     }
510
511     switch (use) {
512         case SYSPAL_NOSTATIC:
513         case SYSPAL_NOSTATIC256:        /* WINVER >= 0x0500 */
514         case SYSPAL_STATIC:
515             SystemPaletteUse = use;
516             return old;
517         default:
518             return SYSPAL_ERROR;
519     }
520 }
521
522
523 /***********************************************************************
524  * GetSystemPaletteUse [GDI32.@]
525  *
526  * Gets state of system palette.
527  *
528  * RETURNS
529  *    Current state of system palette
530  */
531 UINT WINAPI GetSystemPaletteUse(
532     HDC hdc) /* [in] Handle of device context */
533 {
534     return SystemPaletteUse;
535 }
536
537
538 /***********************************************************************
539  * GetSystemPaletteEntries [GDI32.@]
540  *
541  * Gets range of palette entries.
542  *
543  * RETURNS
544  *    Success: Number of entries retrieved from palette
545  *    Failure: 0
546  */
547 UINT WINAPI GetSystemPaletteEntries(
548     HDC hdc,              /* [in]  Handle of device context */
549     UINT start,           /* [in]  Index of first entry to be retrieved */
550     UINT count,           /* [in]  Number of entries to be retrieved */
551     LPPALETTEENTRY entries) /* [out] Array receiving system-palette entries */
552 {
553     UINT ret = 0;
554     DC *dc;
555
556     TRACE("hdc=%p,start=%i,count=%i\n", hdc,start,count);
557
558     if ((dc = DC_GetDCPtr( hdc )))
559     {
560         if (dc->funcs->pGetSystemPaletteEntries)
561             ret = dc->funcs->pGetSystemPaletteEntries( dc->physDev, start, count, entries );
562         GDI_ReleaseObj( hdc );
563     }
564     return ret;
565 }
566
567
568 /***********************************************************************
569  * GetNearestPaletteIndex [GDI32.@]
570  *
571  * Gets palette index for color.
572  *
573  * NOTES
574  *    Should index be initialized to CLR_INVALID instead of 0?
575  *
576  * RETURNS
577  *    Success: Index of entry in logical palette
578  *    Failure: CLR_INVALID
579  */
580 UINT WINAPI GetNearestPaletteIndex(
581     HPALETTE hpalette, /* [in] Handle of logical color palette */
582     COLORREF color)      /* [in] Color to be matched */
583 {
584     PALETTEOBJ* palObj = (PALETTEOBJ*)GDI_GetObjPtr( hpalette, PALETTE_MAGIC );
585     UINT index  = 0;
586
587     if( palObj )
588     {
589         int i, diff = 0x7fffffff;
590         int r,g,b;
591         PALETTEENTRY* entry = palObj->logpalette.palPalEntry;
592
593         for( i = 0; i < palObj->logpalette.palNumEntries && diff ; i++, entry++)
594         {
595             if (!(entry->peFlags & PC_SYS_USED)) continue;
596
597             r = entry->peRed - GetRValue(color);
598             g = entry->peGreen - GetGValue(color);
599             b = entry->peBlue - GetBValue(color);
600
601             r = r*r + g*g + b*b;
602
603             if( r < diff ) { index = i; diff = r; }
604         }
605         GDI_ReleaseObj( hpalette );
606     }
607     TRACE("(%p,%06lx): returning %d\n", hpalette, color, index );
608     return index;
609 }
610
611
612 /***********************************************************************
613  * GetNearestColor [GDI32.@]
614  *
615  * Gets a system color to match.
616  *
617  * RETURNS
618  *    Success: Color from system palette that corresponds to given color
619  *    Failure: CLR_INVALID
620  */
621 COLORREF WINAPI GetNearestColor(
622     HDC hdc,      /* [in] Handle of device context */
623     COLORREF color) /* [in] Color to be matched */
624 {
625     unsigned char spec_type;
626     COLORREF nearest;
627     DC          *dc;
628
629     if (!(dc = DC_GetDCPtr( hdc ))) return CLR_INVALID;
630
631     if (dc->funcs->pGetNearestColor)
632     {
633         nearest = dc->funcs->pGetNearestColor( dc->physDev, color );
634         GDI_ReleaseObj( hdc );
635         return nearest;
636     }
637
638     if (!(GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE))
639     {
640         GDI_ReleaseObj( hdc );
641         return color;
642     }
643
644     spec_type = color >> 24;
645     if (spec_type == 1 || spec_type == 2)
646     {
647         /* we need logical palette for PALETTERGB and PALETTEINDEX colorrefs */
648
649         UINT index;
650         PALETTEENTRY entry;
651         HPALETTE hpal = dc->hPalette ? dc->hPalette : GetStockObject( DEFAULT_PALETTE );
652
653         if (spec_type == 2) /* PALETTERGB */
654             index = GetNearestPaletteIndex( hpal, color );
655         else  /* PALETTEINDEX */
656             index = LOWORD(color);
657
658         if (!GetPaletteEntries( hpal, index, 1, &entry ))
659         {
660             WARN("RGB(%lx) : idx %d is out of bounds, assuming NULL\n", color, index );
661             if (!GetPaletteEntries( hpal, 0, 1, &entry ))
662             {
663                 GDI_ReleaseObj( hdc );
664                 return CLR_INVALID;
665             }
666         }
667         color = RGB( entry.peRed, entry.peGreen, entry.peBlue );
668     }
669     nearest = color & 0x00ffffff;
670     GDI_ReleaseObj( hdc );
671
672     TRACE("(%06lx): returning %06lx\n", color, nearest );
673     return nearest;
674 }
675
676
677 /***********************************************************************
678  *           PALETTE_GetObject
679  */
680 static INT PALETTE_GetObject( HGDIOBJ handle, void *obj, INT count, LPVOID buffer )
681 {
682     PALETTEOBJ *palette = obj;
683
684     if( !buffer )
685         return sizeof(WORD);
686
687     if (count > sizeof(WORD)) count = sizeof(WORD);
688     memcpy( buffer, &palette->logpalette.palNumEntries, count );
689     return count;
690 }
691
692
693 /***********************************************************************
694  *           PALETTE_UnrealizeObject
695  */
696 static BOOL PALETTE_UnrealizeObject( HGDIOBJ handle, void *obj )
697 {
698     PALETTEOBJ *palette = obj;
699
700     HeapFree( GetProcessHeap(), 0, palette->mapping );
701     palette->mapping = NULL;
702
703     if (hLastRealizedPalette == handle)
704     {
705         TRACE("unrealizing palette %p\n", handle);
706         hLastRealizedPalette = 0;
707         pLastRealizedDC = NULL;
708     }
709     return TRUE;
710 }
711
712
713 /***********************************************************************
714  *           PALETTE_DeleteObject
715  */
716 static BOOL PALETTE_DeleteObject( HGDIOBJ handle, void *obj )
717 {
718     PALETTEOBJ *palette = obj;
719
720     HeapFree( GetProcessHeap(), 0, palette->mapping );
721     if (hLastRealizedPalette == handle)
722     {
723         TRACE("unrealizing palette %p\n", handle);
724         hLastRealizedPalette = 0;
725         pLastRealizedDC = NULL;
726     }
727     return GDI_FreeObject( handle, obj );
728 }
729
730
731 /***********************************************************************
732  *           GDISelectPalette    (Not a Windows API)
733  */
734 HPALETTE WINAPI GDISelectPalette( HDC hdc, HPALETTE hpal, WORD wBkg)
735 {
736     HPALETTE ret;
737     DC *dc;
738
739     TRACE("%p %p\n", hdc, hpal );
740
741     if (GetObjectType(hpal) != OBJ_PAL)
742     {
743       WARN("invalid selected palette %p\n",hpal);
744       return 0;
745     }
746     if (!(dc = DC_GetDCPtr( hdc ))) return 0;
747     ret = dc->hPalette;
748     if (dc->funcs->pSelectPalette) hpal = dc->funcs->pSelectPalette( dc->physDev, hpal, FALSE );
749     if (hpal)
750     {
751         dc->hPalette = hpal;
752         if (!wBkg) hPrimaryPalette = hpal;
753     }
754     else ret = 0;
755     GDI_ReleaseObj( hdc );
756     return ret;
757 }
758
759
760 /***********************************************************************
761  *           GDIRealizePalette    (Not a Windows API)
762  */
763 UINT WINAPI GDIRealizePalette( HDC hdc )
764 {
765     UINT realized = 0;
766     DC* dc = DC_GetDCPtr( hdc );
767
768     if (!dc) return 0;
769
770     TRACE("%p...\n", hdc );
771
772     if( dc->hPalette == GetStockObject( DEFAULT_PALETTE ))
773     {
774         if (dc->funcs->pRealizeDefaultPalette)
775             realized = dc->funcs->pRealizeDefaultPalette( dc->physDev );
776     }
777     else if(dc->hPalette != hLastRealizedPalette )
778     {
779         if (dc->funcs->pRealizePalette)
780             realized = dc->funcs->pRealizePalette( dc->physDev, dc->hPalette,
781                                                    (dc->hPalette == hPrimaryPalette) );
782         hLastRealizedPalette = dc->hPalette;
783         pLastRealizedDC = dc->funcs;
784     }
785     else TRACE("  skipping (hLastRealizedPalette = %p)\n", hLastRealizedPalette);
786
787     GDI_ReleaseObj( hdc );
788     TRACE("   realized %i colors.\n", realized );
789     return realized;
790 }
791
792
793 /***********************************************************************
794  *           RealizeDefaultPalette    (GDI.365)
795  */
796 UINT16 WINAPI RealizeDefaultPalette16( HDC16 hdc )
797 {
798     UINT16 ret = 0;
799     DC          *dc;
800
801     TRACE("%04x\n", hdc );
802
803     if (!(dc = DC_GetDCPtr( HDC_32(hdc) ))) return 0;
804
805     if (dc->funcs->pRealizeDefaultPalette) ret = dc->funcs->pRealizeDefaultPalette( dc->physDev );
806     GDI_ReleaseObj( HDC_32(hdc) );
807     return ret;
808 }
809
810 /***********************************************************************
811  *           IsDCCurrentPalette   (GDI.412)
812  */
813 BOOL16 WINAPI IsDCCurrentPalette16(HDC16 hDC)
814 {
815     DC *dc = DC_GetDCPtr( HDC_32(hDC) );
816     if (dc)
817     {
818       BOOL bRet = dc->hPalette == hPrimaryPalette;
819       GDI_ReleaseObj( HDC_32(hDC) );
820       return bRet;
821     }
822     return FALSE;
823 }
824
825
826 /***********************************************************************
827  * SelectPalette [GDI32.@]
828  *
829  * Selects logical palette into DC.
830  *
831  * RETURNS
832  *    Success: Previous logical palette
833  *    Failure: NULL
834  */
835 HPALETTE WINAPI SelectPalette(
836     HDC hDC,               /* [in] Handle of device context */
837     HPALETTE hPal,         /* [in] Handle of logical color palette */
838     BOOL bForceBackground) /* [in] Foreground/background mode */
839 {
840     return pfnSelectPalette( hDC, hPal, bForceBackground );
841 }
842
843
844 /***********************************************************************
845  * RealizePalette [GDI32.@]
846  *
847  * Maps palette entries to system palette.
848  *
849  * RETURNS
850  *    Success: Number of entries in logical palette
851  *    Failure: GDI_ERROR
852  */
853 UINT WINAPI RealizePalette(
854     HDC hDC) /* [in] Handle of device context */
855 {
856     return pfnRealizePalette( hDC );
857 }
858
859
860 typedef HWND (WINAPI *WindowFromDC_funcptr)( HDC );
861 typedef BOOL (WINAPI *RedrawWindow_funcptr)( HWND, const RECT *, HRGN, UINT );
862
863 /**********************************************************************
864  * UpdateColors [GDI32.@]
865  *
866  * Remaps current colors to logical palette.
867  *
868  * RETURNS
869  *    Success: TRUE
870  *    Failure: FALSE
871  */
872 BOOL WINAPI UpdateColors(
873     HDC hDC) /* [in] Handle of device context */
874 {
875     HMODULE mod;
876     int size = GetDeviceCaps( hDC, SIZEPALETTE );
877
878     if (!size) return 0;
879
880     mod = GetModuleHandleA("user32.dll");
881     if (mod)
882     {
883         WindowFromDC_funcptr pWindowFromDC = (WindowFromDC_funcptr)GetProcAddress(mod,"WindowFromDC");
884         if (pWindowFromDC)
885         {
886             HWND hWnd = pWindowFromDC( hDC );
887
888             /* Docs say that we have to remap current drawable pixel by pixel
889              * but it would take forever given the speed of XGet/PutPixel.
890              */
891             if (hWnd && size)
892             {
893                 RedrawWindow_funcptr pRedrawWindow = GetProcAddress( mod, "RedrawWindow" );
894                 if (pRedrawWindow) pRedrawWindow( hWnd, NULL, 0, RDW_INVALIDATE );
895             }
896         }
897     }
898     return 0x666;
899 }
900
901
902 /*********************************************************************
903  *           SetMagicColors   (GDI.606)
904  */
905 VOID WINAPI SetMagicColors16(HDC16 hDC, COLORREF color, UINT16 index)
906 {
907     FIXME("(hDC %04x, color %04x, index %04x): stub\n", hDC, (int)color, index);
908
909 }
910
911 /*********************************************************************
912  *           SetMagicColors   (GDI.@)
913  */
914 BOOL WINAPI SetMagicColors(HDC hdc, ULONG u1, ULONG u2)
915 {
916     FIXME("(%p 0x%08lx 0x%08lx): stub\n", hdc, u1, u2);
917     return TRUE;
918 }
919
920 /**********************************************************************
921  * GetICMProfileA [GDI32.@]
922  *
923  * Returns the filename of the specified device context's color
924  * management profile, even if color management is not enabled
925  * for that DC.
926  *
927  * RETURNS
928  *    TRUE if name copied successfully OR lpszFilename is NULL
929  *    FALSE if the buffer length pointed to by lpcbName is too small
930  *
931  * NOTE
932  *    The buffer length pointed to by lpcbName is ALWAYS updated to
933  *    the length required regardless of other actions this function
934  *    may take.
935  *
936  * FIXME
937  *    How does Windows assign these?  Some registry key?
938  */
939
940
941 /*********************************************************************/
942
943 BOOL WINAPI GetICMProfileA(HDC hDC, LPDWORD lpcbName, LPSTR lpszFilename)
944 {
945     DWORD callerLen;
946     static const char icm[] = "winefake.icm";
947
948     FIXME("(%p, %p, %p): partial stub\n", hDC, lpcbName, lpszFilename);
949
950     callerLen = *lpcbName;
951
952     /* all 3 behaviors require the required buffer size to be set */
953     *lpcbName = sizeof(icm);
954
955     /* behavior 1: if lpszFilename is NULL, return size of string and no error */
956     if (!lpszFilename) return TRUE;
957
958     /* behavior 2: if buffer size too small, return size of string and error */
959     if (callerLen < sizeof(icm))
960     {
961         SetLastError(ERROR_INSUFFICIENT_BUFFER);
962         return FALSE;
963     }
964
965     /* behavior 3: if buffer size OK and pointer not NULL, copy and return size */
966     memcpy(lpszFilename, icm, sizeof(icm));
967     return TRUE;
968 }
969
970 /**********************************************************************
971  * GetICMProfileW [GDI32.@]
972  **/
973 BOOL WINAPI GetICMProfileW(HDC hDC, LPDWORD lpcbName, LPWSTR lpszFilename)
974 {
975     DWORD callerLen;
976     static const WCHAR icm[] = { 'w','i','n','e','f','a','k','e','.','i','c','m', 0 };
977
978     FIXME("(%p, %p, %p): partial stub\n", hDC, lpcbName, lpszFilename);
979
980     callerLen = *lpcbName;
981
982     /* all 3 behaviors require the required buffer size to be set */
983     *lpcbName = sizeof(icm) / sizeof(WCHAR);
984
985     /* behavior 1: if lpszFilename is NULL, return size of string and no error */
986     if (!lpszFilename) return TRUE;
987
988     /* behavior 2: if buffer size too small, return size of string and error */
989     if (callerLen < sizeof(icm)/sizeof(WCHAR))
990     {
991         SetLastError(ERROR_INSUFFICIENT_BUFFER);
992         return FALSE;
993     }
994
995     /* behavior 3: if buffer size OK and pointer not NULL, copy and return size */
996     memcpy(lpszFilename, icm, sizeof(icm));
997     return TRUE;
998 }
999
1000 /**********************************************************************
1001  * GetLogColorSpaceA [GDI32.@]
1002  *
1003  */
1004 BOOL WINAPI GetLogColorSpaceA(HCOLORSPACE hColorSpace, LPLOGCOLORSPACEA lpBuffer, DWORD nSize)
1005 {
1006     FIXME("%p %p 0x%08lx: stub!\n", hColorSpace, lpBuffer, nSize);
1007     return FALSE;
1008 }
1009
1010 /**********************************************************************
1011  * GetLogColorSpaceW [GDI32.@]
1012  *
1013  */
1014 BOOL WINAPI GetLogColorSpaceW(HCOLORSPACE hColorSpace, LPLOGCOLORSPACEW lpBuffer, DWORD nSize)
1015 {
1016     FIXME("%p %p 0x%08lx: stub!\n", hColorSpace, lpBuffer, nSize);
1017     return FALSE;
1018 }
1019
1020 /**********************************************************************
1021  * SetICMProfileA [GDI32.@]
1022  *
1023  */
1024 BOOL WINAPI SetICMProfileA(HDC hDC, LPSTR lpszFilename)
1025 {
1026     FIXME("hDC %p filename '%s': stub!\n", hDC, debugstr_a(lpszFilename));
1027     return TRUE; /* success */
1028 }
1029
1030 /**********************************************************************
1031  * SetICMProfileA [GDI32.@]
1032  *
1033  */
1034 BOOL WINAPI SetICMProfileW(HDC hDC, LPWSTR lpszFilename)
1035 {
1036     FIXME("hDC %p filename '%s': stub!\n", hDC, debugstr_w(lpszFilename));
1037     return TRUE; /* success */
1038 }
1039
1040 /**********************************************************************
1041  * UpdateICMRegKeyA [GDI32.@]
1042  *
1043  */
1044 BOOL WINAPI UpdateICMRegKeyA(DWORD dwReserved, LPSTR lpszCMID, LPSTR lpszFileName, UINT nCommand)
1045 {
1046     FIXME("(0x%08lx, %s, %s, 0x%08x): stub!\n", dwReserved, debugstr_a(lpszCMID),
1047           debugstr_a(lpszFileName), nCommand);
1048     return TRUE; /* success */
1049 }
1050
1051 /**********************************************************************
1052  * UpdateICMRegKeyW [GDI32.@]
1053  *
1054  */
1055 BOOL WINAPI UpdateICMRegKeyW(DWORD dwReserved, LPWSTR lpszCMID, LPWSTR lpszFileName, UINT nCommand)
1056 {
1057     FIXME("(0x%08lx, %s, %s, 0x%08x): stub!\n", dwReserved, debugstr_w(lpszCMID),
1058           debugstr_w(lpszFileName), nCommand);
1059     return TRUE; /* success */
1060 }