winex11: Add a few 'fall through' comments.
[wine] / dlls / winex11.drv / palette.c
1 /*
2  * X11DRV OEM bitmap objects
3  *
4  * Copyright 1994, 1995 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "x11drv.h"
30 #include "wine/debug.h"
31
32 WINE_DEFAULT_DEBUG_CHANNEL(palette);
33
34 /* Palette indexed mode:
35  *      logical palette -> mapping -> pixel
36  *
37  *
38  * Windows needs contiguous color space ( from 0 to n ) but
39  * it is possible only with the private colormap. Otherwise we
40  * have to map DC palette indices to real pixel values. With
41  * private colormaps it boils down to the identity mapping. The
42  * other special case is when we have a fixed color visual with
43  * the screendepth > 8 - we abandon palette mappings altogether
44  * because pixel values can be calculated without X server
45  * assistance.
46  */
47
48 #define NB_RESERVED_COLORS     20   /* number of fixed colors in system palette */
49
50 #define PC_SYS_USED            0x80 /* palentry is used (both system and logical) */
51 #define PC_SYS_RESERVED        0x40 /* system palentry is not to be mapped to */
52
53 static PALETTEENTRY *COLOR_sysPal; /* current system palette */
54
55 static int COLOR_gapStart = 256;
56 static int COLOR_gapEnd = -1;
57 static int COLOR_gapFilled = 0;
58
59 UINT16   X11DRV_PALETTE_PaletteFlags     = 0;
60
61 /* initialize to zero to handle abortive X11DRV_PALETTE_VIRTUAL visuals */
62 ColorShifts X11DRV_PALETTE_default_shifts = { {0,0,0,}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} };
63 static int X11DRV_PALETTE_Graymax        = 0;
64
65 static int palette_size;
66
67 /* First free dynamic color cell, 0 = full palette, -1 = fixed palette */
68 static int           X11DRV_PALETTE_firstFree = 0;
69 static unsigned char X11DRV_PALETTE_freeList[256];
70
71 static XContext palette_context;  /* X context to associate a color mapping to a palette */
72
73 static CRITICAL_SECTION palette_cs;
74 static CRITICAL_SECTION_DEBUG critsect_debug =
75 {
76     0, 0, &palette_cs,
77     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
78       0, 0, { (DWORD_PTR)(__FILE__ ": palette_cs") }
79 };
80 static CRITICAL_SECTION palette_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
81
82 /**********************************************************************/
83
84    /* Map an EGA index (0..15) to a pixel value in the system color space.  */
85
86 int X11DRV_PALETTE_mapEGAPixel[16];
87
88 /**********************************************************************/
89
90 #define NB_COLORCUBE_START_INDEX        63
91 #define NB_PALETTE_EMPTY_VALUE          -1
92
93 /* Maps entry in the system palette to X pixel value */
94 int *X11DRV_PALETTE_PaletteToXPixel = NULL;
95
96 /* Maps pixel to the entry in the system palette */
97 int *X11DRV_PALETTE_XPixelToPalette = NULL;
98
99 /**********************************************************************/
100
101 static BOOL X11DRV_PALETTE_BuildPrivateMap( const PALETTEENTRY *sys_pal_template );
102 static BOOL X11DRV_PALETTE_BuildSharedMap( const PALETTEENTRY *sys_pal_template );
103 static void X11DRV_PALETTE_FillDefaultColors( const PALETTEENTRY *sys_pal_template );
104 static void X11DRV_PALETTE_FormatSystemPalette(void);
105 static BOOL X11DRV_PALETTE_CheckSysColor( const PALETTEENTRY *sys_pal_template, COLORREF c);
106 static int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col);
107
108
109 /***********************************************************************
110  *           palette_get_mapping
111  */
112 static int *palette_get_mapping( HPALETTE hpal )
113 {
114     int *mapping;
115
116     if (XFindContext( gdi_display, (XID)hpal, palette_context, (char **)&mapping )) mapping = NULL;
117     return mapping;
118 }
119
120
121 /***********************************************************************
122  *           palette_set_mapping
123  */
124 static void palette_set_mapping( HPALETTE hpal, int *mapping )
125 {
126     XSaveContext( gdi_display, (XID)hpal, palette_context, (char *)mapping );
127 }
128
129
130 /***********************************************************************
131  *           COLOR_Init
132  *
133  * Initialize color management.
134  */
135 int X11DRV_PALETTE_Init(void)
136 {
137     int *mapping;
138     PALETTEENTRY sys_pal_template[NB_RESERVED_COLORS];
139
140     TRACE("initializing palette manager...\n");
141
142     palette_context = XUniqueContext();
143     palette_size = default_visual.colormap_size;
144
145     switch(default_visual.class)
146     {
147     case DirectColor:
148         X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_VIRTUAL;
149         /* fall through */
150     case GrayScale:
151     case PseudoColor:
152         if (private_color_map)
153         {
154             XSetWindowAttributes win_attr;
155
156             XFreeColormap( gdi_display, default_colormap );
157             default_colormap = XCreateColormap( gdi_display, root_window,
158                                                 default_visual.visual, AllocAll );
159             if (default_colormap)
160             {
161                 X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_PRIVATE;
162
163                 if( root_window != DefaultRootWindow(gdi_display) )
164                 {
165                     win_attr.colormap = default_colormap;
166                     XChangeWindowAttributes( gdi_display, root_window, CWColormap, &win_attr );
167                 }
168             }
169         }
170         break;
171
172     case StaticGray:
173         X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_FIXED;
174         X11DRV_PALETTE_Graymax = (1 << default_visual.depth)-1;
175         break;
176
177     case TrueColor:
178         X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_VIRTUAL;
179         /* fall through */
180     case StaticColor:
181         X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_FIXED;
182         X11DRV_PALETTE_ComputeColorShifts(&X11DRV_PALETTE_default_shifts, default_visual.red_mask, default_visual.green_mask, default_visual.blue_mask);
183         break;
184     }
185
186     if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
187     {
188         palette_size = 0;
189     }
190     else
191     {
192         GetPaletteEntries( GetStockObject(DEFAULT_PALETTE), 0, NB_RESERVED_COLORS, sys_pal_template );
193
194         if ((mapping = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(int) * NB_RESERVED_COLORS )))
195             palette_set_mapping( GetStockObject(DEFAULT_PALETTE), mapping );
196
197         if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
198             X11DRV_PALETTE_BuildPrivateMap( sys_pal_template );
199         else
200             X11DRV_PALETTE_BuildSharedMap( sys_pal_template );
201
202         /* Build free list */
203
204         if( X11DRV_PALETTE_firstFree != -1 )
205             X11DRV_PALETTE_FormatSystemPalette();
206
207         X11DRV_PALETTE_FillDefaultColors( sys_pal_template );
208         palette_size = default_visual.colormap_size;
209     }
210
211     return palette_size;
212 }
213
214 /***********************************************************************
215  *              X11DRV_PALETTE_ComputeChannelShift
216  *
217  * Calculate conversion parameters for a given color mask
218  */
219 static void X11DRV_PALETTE_ComputeChannelShift(unsigned long maskbits, ChannelShift *physical, ChannelShift *to_logical)
220 {
221     int i;
222
223     if (maskbits==0)
224     {
225         physical->shift=0;
226         physical->scale=0;
227         physical->max=0;
228         to_logical->shift=0;
229         to_logical->scale=0;
230         to_logical->max=0;
231         return;
232     }
233
234     for(i=0;!(maskbits&1);i++)
235         maskbits >>= 1;
236
237     physical->shift = i;
238     physical->max = maskbits;
239
240     for(i=0;maskbits!=0;i++)
241         maskbits >>= 1;
242     physical->scale = i;
243
244     if (physical->scale>8)
245     {
246         /* On FreeBSD, VNC's default 32bpp mode is bgrabb (ffc00000,3ff800,7ff)!
247          * So we adjust the shifts to also normalize the color fields to
248          * the Win32 standard of 8 bits per color.
249          */
250         to_logical->shift=physical->shift+(physical->scale-8);
251         to_logical->scale=8;
252         to_logical->max=0xff;
253     } else {
254         to_logical->shift=physical->shift;
255         to_logical->scale=physical->scale;
256         to_logical->max=physical->max;
257     }
258 }
259
260 /***********************************************************************
261  *      X11DRV_PALETTE_ComputeColorShifts
262  *
263  * Calculate conversion parameters for a given color
264  */
265 void X11DRV_PALETTE_ComputeColorShifts(ColorShifts *shifts, unsigned long redMask, unsigned long greenMask, unsigned long blueMask)
266 {
267     X11DRV_PALETTE_ComputeChannelShift(redMask, &shifts->physicalRed, &shifts->logicalRed);
268     X11DRV_PALETTE_ComputeChannelShift(greenMask, &shifts->physicalGreen, &shifts->logicalGreen);
269     X11DRV_PALETTE_ComputeChannelShift(blueMask, &shifts->physicalBlue, &shifts->logicalBlue);
270 }
271
272 /***********************************************************************
273  *           X11DRV_PALETTE_BuildPrivateMap
274  *
275  * Allocate colorcells and initialize mapping tables.
276  */
277 static BOOL X11DRV_PALETTE_BuildPrivateMap( const PALETTEENTRY *sys_pal_template )
278 {
279     /* Private colormap - identity mapping */
280
281     XColor color;
282     int i;
283
284     if((COLOR_sysPal = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY)*palette_size)) == NULL) {
285         WARN("Unable to allocate the system palette\n");
286         return FALSE;
287     }
288
289     TRACE("Building private map - %i palette entries\n", palette_size);
290
291       /* Allocate system palette colors */
292
293     for( i=0; i < palette_size; i++ )
294     {
295        if( i < NB_RESERVED_COLORS/2 )
296        {
297          color.red   = sys_pal_template[i].peRed * 65535 / 255;
298          color.green = sys_pal_template[i].peGreen * 65535 / 255;
299          color.blue  = sys_pal_template[i].peBlue * 65535 / 255;
300          COLOR_sysPal[i] = sys_pal_template[i];
301          COLOR_sysPal[i].peFlags |= PC_SYS_USED;
302        }
303        else if( i >= palette_size - NB_RESERVED_COLORS/2 )
304        {
305          int j = NB_RESERVED_COLORS + i - palette_size;
306          color.red   = sys_pal_template[j].peRed * 65535 / 255;
307          color.green = sys_pal_template[j].peGreen * 65535 / 255;
308          color.blue  = sys_pal_template[j].peBlue * 65535 / 255;
309          COLOR_sysPal[i] = sys_pal_template[j];
310          COLOR_sysPal[i].peFlags |= PC_SYS_USED;
311        }
312
313        color.flags = DoRed | DoGreen | DoBlue;
314        color.pixel = i;
315        XStoreColor(gdi_display, default_colormap, &color);
316
317        /* Set EGA mapping if color is from the first or last eight */
318
319        if (i < 8)
320            X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
321        else if (i >= palette_size - 8 )
322            X11DRV_PALETTE_mapEGAPixel[i - (palette_size - 16)] = color.pixel;
323     }
324
325     X11DRV_PALETTE_XPixelToPalette = X11DRV_PALETTE_PaletteToXPixel = NULL;
326
327     COLOR_gapStart = 256; COLOR_gapEnd = -1;
328
329     X11DRV_PALETTE_firstFree = (palette_size > NB_RESERVED_COLORS)?NB_RESERVED_COLORS/2 : -1;
330
331     return FALSE;
332 }
333
334 /***********************************************************************
335  *           X11DRV_PALETTE_BuildSharedMap
336  *
337  * Allocate colorcells and initialize mapping tables.
338  */
339 static BOOL X11DRV_PALETTE_BuildSharedMap( const PALETTEENTRY *sys_pal_template )
340 {
341    XColor               color;
342    unsigned long        sysPixel[NB_RESERVED_COLORS];
343    unsigned long*       pixDynMapping = NULL;
344    unsigned long        plane_masks[1];
345    int                  i, j, warn = 0;
346    int                  diff, r, g, b, bp = 0, wp = 1;
347    int                  step = 1;
348    unsigned int max = 256;
349    Colormap             defaultCM;
350    XColor               defaultColors[256];
351
352    /* Copy the first bunch of colors out of the default colormap to prevent
353     * colormap flashing as much as possible.  We're likely to get the most
354     * important Window Manager colors, etc in the first 128 colors */
355    defaultCM = DefaultColormap( gdi_display, DefaultScreen(gdi_display) );
356
357    if (copy_default_colors > 256) copy_default_colors = 256;
358    for (i = 0; i < copy_default_colors; i++)
359        defaultColors[i].pixel = (long) i;
360    XQueryColors(gdi_display, defaultCM, &defaultColors[0], copy_default_colors);
361    for (i = 0; i < copy_default_colors; i++)
362        XAllocColor( gdi_display, default_colormap, &defaultColors[i] );
363
364    if (alloc_system_colors > 256) alloc_system_colors = 256;
365    else if (alloc_system_colors < 20) alloc_system_colors = 20;
366    TRACE("%d colors configured.\n", alloc_system_colors);
367
368    TRACE("Building shared map - %i palette entries\n", palette_size);
369
370    /* Be nice and allocate system colors as read-only */
371
372    for( i = 0; i < NB_RESERVED_COLORS; i++ )
373      {
374         color.red   = sys_pal_template[i].peRed * 65535 / 255;
375         color.green = sys_pal_template[i].peGreen * 65535 / 255;
376         color.blue  = sys_pal_template[i].peBlue * 65535 / 255;
377         color.flags = DoRed | DoGreen | DoBlue;
378
379         if (!XAllocColor( gdi_display, default_colormap, &color ))
380         {
381              XColor     best, c;
382
383              if( !warn++ )
384              {
385                   WARN("Not enough colors for the full system palette.\n");
386
387                   bp = BlackPixel(gdi_display, DefaultScreen(gdi_display));
388                   wp = WhitePixel(gdi_display, DefaultScreen(gdi_display));
389
390                   max = 0xffffffff >> (32 - default_visual.depth);
391                   if( max > 256 )
392                   {
393                       step = max/256;
394                       max = 256;
395                   }
396              }
397
398              /* reinit color (XAllocColor() may change it)
399               * and map to the best shared colorcell */
400
401              color.red   = sys_pal_template[i].peRed * 65535 / 255;
402              color.green = sys_pal_template[i].peGreen * 65535 / 255;
403              color.blue  = sys_pal_template[i].peBlue * 65535 / 255;
404
405              best.pixel = best.red = best.green = best.blue = 0;
406              for( c.pixel = 0, diff = 0x7fffffff; c.pixel < max; c.pixel += step )
407              {
408                 XQueryColor(gdi_display, default_colormap, &c);
409                 r = (c.red - color.red)>>8;
410                 g = (c.green - color.green)>>8;
411                 b = (c.blue - color.blue)>>8;
412                 r = r*r + g*g + b*b;
413                 if( r < diff ) { best = c; diff = r; }
414              }
415
416              if( XAllocColor(gdi_display, default_colormap, &best) )
417                  color.pixel = best.pixel;
418              else color.pixel = (i < NB_RESERVED_COLORS/2)? bp : wp;
419         }
420
421         sysPixel[i] = color.pixel;
422
423         TRACE("syscolor(%x) -> pixel %i\n", *(const COLORREF*)(sys_pal_template+i),
424               (int)color.pixel);
425
426         /* Set EGA mapping if color in the first or last eight */
427
428         if (i < 8)
429             X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
430         else if (i >= NB_RESERVED_COLORS - 8 )
431             X11DRV_PALETTE_mapEGAPixel[i - (NB_RESERVED_COLORS-16)] = color.pixel;
432      }
433
434    /* now allocate changeable set */
435
436    if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
437      {
438         int c_min = 0, c_max = palette_size, c_val;
439
440         TRACE("Dynamic colormap...\n");
441
442         /* let's become the first client that actually follows
443          * X guidelines and does binary search...
444          */
445
446         if((pixDynMapping = HeapAlloc(GetProcessHeap(), 0, sizeof(long)*palette_size)) == NULL) {
447             WARN("Out of memory while building system palette.\n");
448             return FALSE;
449         }
450
451         /* comment this out if you want to debug palette init */
452         XGrabServer(gdi_display);
453
454         while( c_max - c_min > 0 )
455           {
456              c_val = (c_max + c_min)/2 + (c_max + c_min)%2;
457
458              if( !XAllocColorCells(gdi_display, default_colormap, False,
459                                    plane_masks, 0, pixDynMapping, c_val) )
460                  c_max = c_val - 1;
461              else
462                {
463                  XFreeColors(gdi_display, default_colormap, pixDynMapping, c_val, 0);
464                  c_min = c_val;
465                }
466           }
467
468         if( c_min > alloc_system_colors - NB_RESERVED_COLORS)
469             c_min = alloc_system_colors - NB_RESERVED_COLORS;
470
471         c_min = (c_min/2) + (c_min/2);          /* need even set for split palette */
472
473         if( c_min > 0 )
474           if( !XAllocColorCells(gdi_display, default_colormap, False,
475                                 plane_masks, 0, pixDynMapping, c_min) )
476             {
477               WARN("Inexplicable failure during colorcell allocation.\n");
478               c_min = 0;
479             }
480
481         palette_size = c_min + NB_RESERVED_COLORS;
482
483         XUngrabServer(gdi_display);
484
485         TRACE("adjusted size %i colorcells\n", palette_size);
486      }
487    else if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
488         {
489           /* virtual colorspace - ToPhysical takes care of
490            * color translations but we have to allocate full palette
491            * to maintain compatibility
492            */
493           palette_size = 256;
494           TRACE("Virtual colorspace - screendepth %i\n", default_visual.depth);
495         }
496    else palette_size = NB_RESERVED_COLORS;      /* system palette only - however we can alloc a bunch
497                                          * of colors and map to them */
498
499    TRACE("Shared system palette uses %i colors.\n", palette_size);
500
501    /* set gap to account for pixel shortage. It has to be right in the center
502     * of the system palette because otherwise raster ops get screwed. */
503
504    if( palette_size >= 256 )
505      { COLOR_gapStart = 256; COLOR_gapEnd = -1; }
506    else
507      { COLOR_gapStart = palette_size/2; COLOR_gapEnd = 255 - palette_size/2; }
508
509    X11DRV_PALETTE_firstFree = ( palette_size > NB_RESERVED_COLORS &&
510                       (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL || !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED)) )
511                      ? NB_RESERVED_COLORS/2 : -1;
512
513    COLOR_sysPal = HeapAlloc(GetProcessHeap(),0,sizeof(PALETTEENTRY)*256);
514    if(COLOR_sysPal == NULL) {
515        ERR("Unable to allocate the system palette!\n");
516        HeapFree(GetProcessHeap(), 0, pixDynMapping);
517        return FALSE;
518    }
519
520    /* setup system palette entry <-> pixel mappings and fill in 20 fixed entries */
521
522    if (default_visual.depth <= 8)
523    {
524        X11DRV_PALETTE_XPixelToPalette = HeapAlloc( GetProcessHeap(), 0, 256 * sizeof(int) );
525        if(X11DRV_PALETTE_XPixelToPalette == NULL) {
526            ERR("Out of memory: XPixelToPalette!\n");
527            HeapFree(GetProcessHeap(), 0, pixDynMapping);
528            return FALSE;
529        }
530        for( i = 0; i < 256; i++ )
531            X11DRV_PALETTE_XPixelToPalette[i] = NB_PALETTE_EMPTY_VALUE;
532    }
533
534    /* for hicolor visuals PaletteToPixel mapping is used to skip
535     * RGB->pixel calculation in X11DRV_PALETTE_ToPhysical().
536     */
537
538    X11DRV_PALETTE_PaletteToXPixel = HeapAlloc(GetProcessHeap(),0,sizeof(int)*256);
539    if(X11DRV_PALETTE_PaletteToXPixel == NULL) {
540        ERR("Out of memory: PaletteToXPixel!\n");
541        HeapFree(GetProcessHeap(), 0, pixDynMapping);
542        return FALSE;
543    }
544
545    for( i = j = 0; i < 256; i++ )
546    {
547       if( i >= COLOR_gapStart && i <= COLOR_gapEnd )
548       {
549          X11DRV_PALETTE_PaletteToXPixel[i] = NB_PALETTE_EMPTY_VALUE;
550          COLOR_sysPal[i].peFlags = 0;   /* mark as unused */
551          continue;
552       }
553
554       if( i < NB_RESERVED_COLORS/2 )
555       {
556         X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[i];
557         COLOR_sysPal[i] = sys_pal_template[i];
558         COLOR_sysPal[i].peFlags |= PC_SYS_USED;
559       }
560       else if( i >= 256 - NB_RESERVED_COLORS/2 )
561       {
562         X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[(i + NB_RESERVED_COLORS) - 256];
563         COLOR_sysPal[i] = sys_pal_template[(i + NB_RESERVED_COLORS) - 256];
564         COLOR_sysPal[i].peFlags |= PC_SYS_USED;
565       }
566       else if( pixDynMapping )
567              X11DRV_PALETTE_PaletteToXPixel[i] = pixDynMapping[j++];
568            else
569              X11DRV_PALETTE_PaletteToXPixel[i] = i;
570
571       TRACE("index %i -> pixel %i\n", i, X11DRV_PALETTE_PaletteToXPixel[i]);
572
573       if( X11DRV_PALETTE_XPixelToPalette )
574           X11DRV_PALETTE_XPixelToPalette[X11DRV_PALETTE_PaletteToXPixel[i]] = i;
575    }
576
577    HeapFree(GetProcessHeap(), 0, pixDynMapping);
578
579    return TRUE;
580 }
581
582 /***********************************************************************
583  *      Colormap Initialization
584  */
585 static void X11DRV_PALETTE_FillDefaultColors( const PALETTEENTRY *sys_pal_template )
586 {
587  /* initialize unused entries to what Windows uses as a color
588   * cube - based on Greg Kreider's code.
589   */
590
591   int i = 0, idx = 0;
592   int red, no_r, inc_r;
593   int green, no_g, inc_g;
594   int blue, no_b, inc_b;
595
596   if (palette_size <= NB_RESERVED_COLORS)
597         return;
598   while (i*i*i < (palette_size - NB_RESERVED_COLORS)) i++;
599   no_r = no_g = no_b = --i;
600   if ((no_r * (no_g+1) * no_b) < (palette_size - NB_RESERVED_COLORS)) no_g++;
601   if ((no_r * no_g * (no_b+1)) < (palette_size - NB_RESERVED_COLORS)) no_b++;
602   inc_r = (255 - NB_COLORCUBE_START_INDEX)/no_r;
603   inc_g = (255 - NB_COLORCUBE_START_INDEX)/no_g;
604   inc_b = (255 - NB_COLORCUBE_START_INDEX)/no_b;
605
606   idx = X11DRV_PALETTE_firstFree;
607
608   if( idx != -1 )
609     for (blue = NB_COLORCUBE_START_INDEX; blue < 256 && idx; blue += inc_b )
610      for (green = NB_COLORCUBE_START_INDEX; green < 256 && idx; green += inc_g )
611       for (red = NB_COLORCUBE_START_INDEX; red < 256 && idx; red += inc_r )
612       {
613          /* weird but true */
614
615          if( red == NB_COLORCUBE_START_INDEX && green == red && blue == green ) continue;
616
617          COLOR_sysPal[idx].peRed = red;
618          COLOR_sysPal[idx].peGreen = green;
619          COLOR_sysPal[idx].peBlue = blue;
620
621          /* set X color */
622
623          if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
624          {
625             ColorShifts *shifts = &X11DRV_PALETTE_default_shifts;
626             if (shifts->physicalRed.max != 255) no_r = (red * shifts->physicalRed.max) / 255;
627             if (shifts->physicalGreen.max != 255) no_g = (green * shifts->physicalGreen.max) / 255;
628             if (shifts->physicalBlue.max != 255) no_b = (blue * shifts->physicalBlue.max) / 255;
629
630             X11DRV_PALETTE_PaletteToXPixel[idx] = (no_r << shifts->physicalRed.shift) | (no_g << shifts->physicalGreen.shift) | (no_b << shifts->physicalBlue.shift);
631          }
632          else if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
633          {
634            XColor color;
635            color.pixel = (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[idx] : idx;
636            color.red = COLOR_sysPal[idx].peRed << 8;
637            color.green = COLOR_sysPal[idx].peGreen << 8;
638            color.blue =  COLOR_sysPal[idx].peBlue << 8;
639            color.flags = DoRed | DoGreen | DoBlue;
640            XStoreColor(gdi_display, default_colormap, &color);
641          }
642          idx = X11DRV_PALETTE_freeList[idx];
643       }
644
645   /* try to fill some entries in the "gap" with
646    * what's already in the colormap - they will be
647    * mappable to but not changeable. */
648
649   if( COLOR_gapStart < COLOR_gapEnd && X11DRV_PALETTE_XPixelToPalette )
650   {
651     XColor      xc;
652     int         r, g, b, max;
653
654     max = alloc_system_colors - (256 - (COLOR_gapEnd - COLOR_gapStart));
655     for ( i = 0, idx = COLOR_gapStart; i < 256 && idx <= COLOR_gapEnd; i++ )
656       if( X11DRV_PALETTE_XPixelToPalette[i] == NB_PALETTE_EMPTY_VALUE )
657         {
658           xc.pixel = i;
659
660           XQueryColor(gdi_display, default_colormap, &xc);
661           r = xc.red>>8; g = xc.green>>8; b = xc.blue>>8;
662
663           if( xc.pixel < 256 && X11DRV_PALETTE_CheckSysColor( sys_pal_template, RGB(r, g, b)) &&
664               XAllocColor(gdi_display, default_colormap, &xc) )
665           {
666              X11DRV_PALETTE_XPixelToPalette[xc.pixel] = idx;
667              X11DRV_PALETTE_PaletteToXPixel[idx] = xc.pixel;
668            *(COLORREF*)(COLOR_sysPal + idx) = RGB(r, g, b);
669              COLOR_sysPal[idx++].peFlags |= PC_SYS_USED;
670              if( --max <= 0 ) break;
671           }
672         }
673     COLOR_gapFilled = idx - COLOR_gapStart;
674   }
675 }
676
677
678 /***********************************************************************
679  *           X11DRV_IsSolidColor
680  *
681  * Check whether 'color' can be represented with a solid color.
682  */
683 BOOL X11DRV_IsSolidColor( COLORREF color )
684 {
685     int i;
686     const PALETTEENTRY *pEntry = COLOR_sysPal;
687
688     if (color & 0xff000000) return TRUE;  /* indexed color */
689
690     if (!color || (color == 0xffffff)) return TRUE;  /* black or white */
691
692     if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL) return TRUE;  /* no palette */
693
694     EnterCriticalSection( &palette_cs );
695     for (i = 0; i < palette_size ; i++, pEntry++)
696     {
697         if( i < COLOR_gapStart || i > COLOR_gapEnd )
698             if ((GetRValue(color) == pEntry->peRed) &&
699                 (GetGValue(color) == pEntry->peGreen) &&
700                 (GetBValue(color) == pEntry->peBlue))
701             {
702                 LeaveCriticalSection( &palette_cs );
703                 return TRUE;
704             }
705     }
706     LeaveCriticalSection( &palette_cs );
707     return FALSE;
708 }
709
710
711 /***********************************************************************
712  *           X11DRV_PALETTE_ToLogical
713  *
714  * Return RGB color for given X pixel.
715  */
716 COLORREF X11DRV_PALETTE_ToLogical(X11DRV_PDEVICE *physDev, int pixel)
717 {
718     XColor color;
719
720     /* check for hicolor visuals first */
721
722     if ( (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) && !X11DRV_PALETTE_Graymax )
723     {
724          ColorShifts *shifts = &X11DRV_PALETTE_default_shifts;
725
726          if(physDev->color_shifts)
727              shifts = physDev->color_shifts;
728
729          color.red = (pixel >> shifts->logicalRed.shift) & shifts->logicalRed.max;
730          if (shifts->logicalRed.scale<8)
731              color.red=  color.red   << (8-shifts->logicalRed.scale) |
732                          color.red   >> (2*shifts->logicalRed.scale-8);
733          color.green = (pixel >> shifts->logicalGreen.shift) & shifts->logicalGreen.max;
734          if (shifts->logicalGreen.scale<8)
735              color.green=color.green << (8-shifts->logicalGreen.scale) |
736                          color.green >> (2*shifts->logicalGreen.scale-8);
737          color.blue = (pixel >> shifts->logicalBlue.shift) & shifts->logicalBlue.max;
738          if (shifts->logicalBlue.scale<8)
739              color.blue= color.blue  << (8-shifts->logicalBlue.scale)  |
740                          color.blue  >> (2*shifts->logicalBlue.scale-8);
741                  return RGB(color.red,color.green,color.blue);
742     }
743
744     /* check if we can bypass X */
745
746     if ((default_visual.depth <= 8) && (pixel < 256) &&
747         !(X11DRV_PALETTE_PaletteFlags & (X11DRV_PALETTE_VIRTUAL | X11DRV_PALETTE_FIXED)) ) {
748         COLORREF ret;
749         EnterCriticalSection( &palette_cs );
750         ret = *(COLORREF *)(COLOR_sysPal + (X11DRV_PALETTE_XPixelToPalette ? X11DRV_PALETTE_XPixelToPalette[pixel]: pixel)) & 0x00ffffff;
751         LeaveCriticalSection( &palette_cs );
752         return ret;
753     }
754
755     color.pixel = pixel;
756     XQueryColor(gdi_display, default_colormap, &color);
757     return RGB(color.red >> 8, color.green >> 8, color.blue >> 8);
758 }
759
760
761 /***********************************************************************
762  *           X11DRV_SysPaletteLookupPixel
763  */
764 static int X11DRV_SysPaletteLookupPixel( COLORREF col, BOOL skipReserved )
765 {
766     int i, best = 0, diff = 0x7fffffff;
767     int r,g,b;
768
769     for( i = 0; i < palette_size && diff ; i++ )
770     {
771         if( !(COLOR_sysPal[i].peFlags & PC_SYS_USED) ||
772             (skipReserved && COLOR_sysPal[i].peFlags  & PC_SYS_RESERVED) )
773             continue;
774
775         r = COLOR_sysPal[i].peRed - GetRValue(col);
776         g = COLOR_sysPal[i].peGreen - GetGValue(col);
777         b = COLOR_sysPal[i].peBlue - GetBValue(col);
778
779         r = r*r + g*g + b*b;
780
781         if( r < diff ) { best = i; diff = r; }
782     }
783     return best;
784 }
785
786  
787 static inline BOOL colour_is_brighter(RGBQUAD c1, RGBQUAD c2)
788 {
789     return (c1.rgbRed * c1.rgbRed + c1.rgbGreen * c1.rgbGreen + c1.rgbBlue * c1.rgbBlue) > 
790         (c2.rgbRed * c2.rgbRed + c2.rgbGreen * c2.rgbGreen + c2.rgbBlue * c2.rgbBlue);
791 }
792
793 /***********************************************************************
794  *           X11DRV_PALETTE_GetColor
795  *
796  * Resolve PALETTEINDEX/PALETTERGB/DIBINDEX COLORREFs to an RGB COLORREF.
797  */
798 COLORREF X11DRV_PALETTE_GetColor( X11DRV_PDEVICE *physDev, COLORREF color )
799 {
800     HPALETTE             hPal = GetCurrentObject(physDev->dev.hdc, OBJ_PAL );
801     PALETTEENTRY         entry;
802
803     if (color & (1 << 24))  /* PALETTEINDEX */
804     {
805         unsigned int idx = LOWORD(color);
806         if (!GetPaletteEntries( hPal, idx, 1, &entry )) return 0;
807         return RGB( entry.peRed, entry.peGreen, entry.peBlue );
808     }
809
810     if (color >> 24 == 2)  /* PALETTERGB */
811     {
812         unsigned int idx = GetNearestPaletteIndex( hPal, color & 0xffffff );
813         if (!GetPaletteEntries( hPal, idx, 1, &entry )) return 0;
814         return RGB( entry.peRed, entry.peGreen, entry.peBlue );
815     }
816
817     if (color >> 16 == 0x10ff)  /* DIBINDEX */
818         return 0;
819
820     return color & 0xffffff;
821 }
822
823 /***********************************************************************
824  *           X11DRV_PALETTE_ToPhysical
825  *
826  * Return the physical color closest to 'color'.
827  */
828 int X11DRV_PALETTE_ToPhysical( X11DRV_PDEVICE *physDev, COLORREF color )
829 {
830     WORD                 index = 0;
831     HPALETTE             hPal = GetCurrentObject(physDev->dev.hdc, OBJ_PAL );
832     int *mapping = palette_get_mapping( hPal );
833     PALETTEENTRY entry;
834     ColorShifts *shifts = &X11DRV_PALETTE_default_shifts;
835
836     if(physDev->color_shifts)
837         shifts = physDev->color_shifts;
838
839     if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED )
840     {
841         /* there is no colormap limitation; we are going to have to compute
842          * the pixel value from the visual information stored earlier
843          */
844         unsigned long red, green, blue;
845
846         if (color & (1 << 24))  /* PALETTEINDEX */
847         {
848             unsigned int idx = LOWORD( color );
849
850             if (!GetPaletteEntries( hPal, idx, 1, &entry ))
851             {
852                 WARN("PALETTEINDEX(%x) : idx %d is out of bounds, assuming black\n", color, idx);
853                 return 0;
854             }
855             if (mapping) return mapping[idx];
856             red   = entry.peRed;
857             green = entry.peGreen;
858             blue  = entry.peBlue;
859         }
860         else if (color >> 16 == 0x10ff)  /* DIBINDEX */
861         {
862             return 0;
863         }
864         else  /* RGB */
865         {
866             if (physDev->depth == 1)
867                 return (((color >> 16) & 0xff) +
868                         ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
869             red   = GetRValue( color );
870             green = GetGValue( color );
871             blue  = GetBValue( color );
872         }
873
874         if (X11DRV_PALETTE_Graymax)
875         {
876             /* grayscale only; return scaled value */
877             return ( (red * 30 + green * 59 + blue * 11) * X11DRV_PALETTE_Graymax) / 25500;
878         }
879         else
880         {
881             /* scale each individually and construct the TrueColor pixel value */
882             if (shifts->physicalRed.scale < 8)
883                 red = red >> (8-shifts->physicalRed.scale);
884             else if (shifts->physicalRed.scale > 8)
885                 red = red << (shifts->physicalRed.scale-8) |
886                       red >> (16-shifts->physicalRed.scale);
887             if (shifts->physicalGreen.scale < 8)
888                 green = green >> (8-shifts->physicalGreen.scale);
889             else if (shifts->physicalGreen.scale > 8)
890                 green = green << (shifts->physicalGreen.scale-8) |
891                         green >> (16-shifts->physicalGreen.scale);
892             if (shifts->physicalBlue.scale < 8)
893                 blue =  blue >> (8-shifts->physicalBlue.scale);
894             else if (shifts->physicalBlue.scale > 8)
895                 blue =  blue << (shifts->physicalBlue.scale-8) |
896                         blue >> (16-shifts->physicalBlue.scale);
897
898             return (red << shifts->physicalRed.shift) | (green << shifts->physicalGreen.shift) | (blue << shifts->physicalBlue.shift);
899         }
900     }
901     else
902     {
903         if (!mapping)
904             WARN("Palette %p is not realized\n", hPal);
905
906         if (color & (1 << 24))  /* PALETTEINDEX */
907         {
908             index = LOWORD( color );
909             if (!GetPaletteEntries( hPal, index, 1, &entry ))
910                 WARN("PALETTEINDEX(%x) : index %i is out of bounds\n", color, index);
911             else if (mapping) index = mapping[index];
912         }
913         else if (color >> 24 == 2)  /* PALETTERGB */
914         {
915             index = GetNearestPaletteIndex( hPal, color );
916             if (mapping) index = mapping[index];
917         }
918         else if (color >> 16 == 0x10ff)  /* DIBINDEX */
919         {
920             return 0;
921         }
922         else  /* RGB */
923         {
924             if (physDev->depth == 1)
925                 return (((color >> 16) & 0xff) +
926                         ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
927
928             EnterCriticalSection( &palette_cs );
929             index = X11DRV_SysPaletteLookupPixel( color & 0xffffff, FALSE);
930             if (X11DRV_PALETTE_PaletteToXPixel) index = X11DRV_PALETTE_PaletteToXPixel[index];
931             LeaveCriticalSection( &palette_cs );
932         }
933     }
934     return index;
935 }
936
937 /***********************************************************************
938  *           X11DRV_PALETTE_LookupPixel
939  */
940 static int X11DRV_PALETTE_LookupPixel(ColorShifts *shifts, COLORREF color )
941 {
942     unsigned char spec_type = color >> 24;
943
944     /* Only accept RGB which has spec_type = 0 */
945     if(spec_type)
946         return 0;
947
948     color &= 0xffffff;
949
950     if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED )
951     {
952         unsigned long red, green, blue;
953         red = GetRValue(color); green = GetGValue(color); blue = GetBValue(color);
954
955         if (X11DRV_PALETTE_Graymax)
956         {
957             /* grayscale only; return scaled value */
958             return ( (red * 30 + green * 59 + blue * 11) * X11DRV_PALETTE_Graymax) / 25500;
959         }
960         else
961         {
962             /* No shifts are set in case of 1-bit */
963             if(!shifts) shifts = &X11DRV_PALETTE_default_shifts;
964
965             /* scale each individually and construct the TrueColor pixel value */
966             if (shifts->physicalRed.scale < 8)
967                 red = red >> (8-shifts->physicalRed.scale);
968             else if (shifts->physicalRed.scale > 8)
969                 red = red << (shifts->physicalRed.scale-8) |
970                       red >> (16-shifts->physicalRed.scale);
971             if (shifts->physicalGreen.scale < 8)
972                 green = green >> (8-shifts->physicalGreen.scale);
973             else if (shifts->physicalGreen.scale > 8)
974                 green = green << (shifts->physicalGreen.scale-8) |
975                         green >> (16-shifts->physicalGreen.scale);
976             if (shifts->physicalBlue.scale < 8)
977                 blue =  blue >> (8-shifts->physicalBlue.scale);
978             else if (shifts->physicalBlue.scale > 8)
979                 blue =  blue << (shifts->physicalBlue.scale-8) |
980                         blue >> (16-shifts->physicalBlue.scale);
981
982             return (red << shifts->physicalRed.shift) | (green << shifts->physicalGreen.shift) | (blue << shifts->physicalBlue.shift);
983         }
984     }
985     else
986     {
987         WORD index;
988         HPALETTE hPal = GetStockObject(DEFAULT_PALETTE);
989         int *mapping = palette_get_mapping( hPal );
990
991         if (!mapping)
992             WARN("Palette %p is not realized\n", hPal);
993
994         EnterCriticalSection( &palette_cs );
995         index = X11DRV_SysPaletteLookupPixel( color, FALSE);
996         if (X11DRV_PALETTE_PaletteToXPixel)
997             index = X11DRV_PALETTE_PaletteToXPixel[index];
998         LeaveCriticalSection( &palette_cs );
999         return index;
1000     }
1001 }
1002
1003
1004 /***********************************************************************
1005  *           X11DRV_PALETTE_LookupSystemXPixel
1006  */
1007 static int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col)
1008 {
1009  int            i, best = 0, diff = 0x7fffffff;
1010  int            size = palette_size;
1011  int            r,g,b;
1012
1013  for( i = 0; i < size && diff ; i++ )
1014     {
1015       if( i == NB_RESERVED_COLORS/2 )
1016       {
1017         int newi = size - NB_RESERVED_COLORS/2;
1018         if (newi>i) i=newi;
1019       }
1020
1021       r = COLOR_sysPal[i].peRed - GetRValue(col);
1022       g = COLOR_sysPal[i].peGreen - GetGValue(col);
1023       b = COLOR_sysPal[i].peBlue - GetBValue(col);
1024
1025       r = r*r + g*g + b*b;
1026
1027       if( r < diff ) { best = i; diff = r; }
1028     }
1029
1030  return (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[best] : best;
1031 }
1032
1033 /***********************************************************************
1034  *           X11DRV_PALETTE_FormatSystemPalette
1035  */
1036 static void X11DRV_PALETTE_FormatSystemPalette(void)
1037 {
1038  /* Build free list so we'd have an easy way to find
1039   * out if there are any available colorcells.
1040   */
1041
1042   int i, j = X11DRV_PALETTE_firstFree = NB_RESERVED_COLORS/2;
1043
1044   COLOR_sysPal[j].peFlags = 0;
1045   for( i = NB_RESERVED_COLORS/2 + 1 ; i < 256 - NB_RESERVED_COLORS/2 ; i++ )
1046     if( i < COLOR_gapStart || i > COLOR_gapEnd )
1047       {
1048         COLOR_sysPal[i].peFlags = 0;  /* unused tag */
1049         X11DRV_PALETTE_freeList[j] = i;   /* next */
1050         j = i;
1051       }
1052   X11DRV_PALETTE_freeList[j] = 0;
1053 }
1054
1055 /***********************************************************************
1056  *           X11DRV_PALETTE_CheckSysColor
1057  */
1058 static BOOL X11DRV_PALETTE_CheckSysColor( const PALETTEENTRY *sys_pal_template, COLORREF c)
1059 {
1060   int i;
1061   for( i = 0; i < NB_RESERVED_COLORS; i++ )
1062        if( c == (*(const COLORREF*)(sys_pal_template + i) & 0x00ffffff) )
1063            return 0;
1064   return 1;
1065 }
1066
1067
1068 /***********************************************************************
1069  *           X11DRV_LookupSysPaletteExact
1070  */
1071 static int X11DRV_LookupSysPaletteExact( BYTE r, BYTE g, BYTE b )
1072 {
1073     int i;
1074     for( i = 0; i < palette_size; i++ )
1075     {
1076         if( COLOR_sysPal[i].peFlags & PC_SYS_USED )  /* skips gap */
1077             if( COLOR_sysPal[i].peRed == r &&
1078                 COLOR_sysPal[i].peGreen == g &&
1079                 COLOR_sysPal[i].peBlue == b )
1080                 return i;
1081     }
1082     return -1;
1083 }
1084
1085
1086 /***********************************************************************
1087  *              RealizePalette    (X11DRV.@)
1088  */
1089 UINT X11DRV_RealizePalette( PHYSDEV dev, HPALETTE hpal, BOOL primary )
1090 {
1091     X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );
1092     char flag;
1093     int  index;
1094     UINT i, iRemapped = 0;
1095     int *prev_mapping, *mapping;
1096     PALETTEENTRY entries[256];
1097     WORD num_entries;
1098
1099     if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL) return 0;
1100
1101     if (!GetObjectW( hpal, sizeof(num_entries), &num_entries )) return 0;
1102
1103     /* initialize palette mapping table */
1104     prev_mapping = palette_get_mapping( hpal );
1105     if (prev_mapping)
1106         mapping = HeapReAlloc( GetProcessHeap(), 0, prev_mapping, sizeof(int)*num_entries);
1107     else 
1108         mapping = HeapAlloc( GetProcessHeap(), 0, sizeof(int)*num_entries);
1109
1110     if(mapping == NULL) {
1111         ERR("Unable to allocate new mapping -- memory exhausted!\n");
1112         return 0;
1113     }
1114     palette_set_mapping( hpal, mapping );
1115
1116     if (num_entries > 256)
1117     {
1118         FIXME( "more than 256 entries not supported\n" );
1119         num_entries = 256;
1120     }
1121     if (!(num_entries = GetPaletteEntries( hpal, 0, num_entries, entries ))) return 0;
1122
1123     /* reset dynamic system palette entries */
1124
1125     EnterCriticalSection( &palette_cs );
1126     if( primary && X11DRV_PALETTE_firstFree != -1)
1127          X11DRV_PALETTE_FormatSystemPalette();
1128
1129     for (i = 0; i < num_entries; i++)
1130     {
1131         index = -1;
1132         flag = PC_SYS_USED;
1133
1134         /* Even though the docs say that only one flag is to be set,
1135          * they are a bitmask. At least one app sets more than one at
1136          * the same time. */
1137         if ( entries[i].peFlags & PC_EXPLICIT ) {
1138             /* palette entries are indices into system palette */
1139             index = *(WORD*)&entries[i];
1140             if( index > 255 || (index >= COLOR_gapStart && index <= COLOR_gapEnd) )
1141             {
1142                 WARN("PC_EXPLICIT: idx %d out of system palette, assuming black.\n", index);
1143                 index = 0;
1144             }
1145             if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
1146         } else {
1147             if ( entries[i].peFlags & PC_RESERVED ) {
1148                 /* forbid future mappings to this entry */
1149                 flag |= PC_SYS_RESERVED;
1150             }
1151             
1152             if (! (entries[i].peFlags & PC_NOCOLLAPSE) ) {
1153                 /* try to collapse identical colors */
1154                 index = X11DRV_LookupSysPaletteExact( entries[i].peRed, entries[i].peGreen, entries[i].peBlue );
1155             }
1156
1157             if( index < 0 )
1158             {
1159                 if( X11DRV_PALETTE_firstFree > 0 )
1160                 {
1161                     XColor color;
1162                     index = X11DRV_PALETTE_firstFree;  /* ought to be available */
1163                     X11DRV_PALETTE_firstFree = X11DRV_PALETTE_freeList[index];
1164
1165                     color.pixel = (X11DRV_PALETTE_PaletteToXPixel) ? X11DRV_PALETTE_PaletteToXPixel[index] : index;
1166                     color.red = entries[i].peRed << 8;
1167                     color.green = entries[i].peGreen << 8;
1168                     color.blue = entries[i].peBlue << 8;
1169                     color.flags = DoRed | DoGreen | DoBlue;
1170                     XStoreColor(gdi_display, default_colormap, &color);
1171
1172                     COLOR_sysPal[index] = entries[i];
1173                     COLOR_sysPal[index].peFlags = flag;
1174                     X11DRV_PALETTE_freeList[index] = 0;
1175
1176                     if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
1177                 }
1178                 else if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
1179                 {
1180                     index = X11DRV_PALETTE_LookupPixel( physDev->color_shifts, RGB( entries[i].peRed, entries[i].peGreen, entries[i].peBlue ));
1181                 }
1182
1183                 /* we have to map to existing entry in the system palette */
1184
1185                 index = X11DRV_SysPaletteLookupPixel( RGB( entries[i].peRed, entries[i].peGreen, entries[i].peBlue ),
1186                                                       TRUE );
1187             }
1188
1189             if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
1190         }
1191
1192         if( !prev_mapping || mapping[i] != index ) iRemapped++;
1193         mapping[i] = index;
1194
1195         TRACE("entry %i (%x) -> pixel %i\n", i, *(COLORREF*)&entries[i], index);
1196
1197     }
1198     LeaveCriticalSection( &palette_cs );
1199     return iRemapped;
1200 }
1201
1202
1203 /***********************************************************************
1204  *              UnrealizePalette    (X11DRV.@)
1205  */
1206 BOOL X11DRV_UnrealizePalette( HPALETTE hpal )
1207 {
1208     int *mapping = palette_get_mapping( hpal );
1209
1210     if (mapping)
1211     {
1212         XDeleteContext( gdi_display, (XID)hpal, palette_context );
1213         HeapFree( GetProcessHeap(), 0, mapping );
1214     }
1215     return TRUE;
1216 }
1217
1218
1219 /***********************************************************************
1220  *              GetSystemPaletteEntries   (X11DRV.@)
1221  */
1222 UINT X11DRV_GetSystemPaletteEntries( PHYSDEV dev, UINT start, UINT count, LPPALETTEENTRY entries )
1223 {
1224     UINT i;
1225
1226     if (!entries) return palette_size;
1227     if (start >= palette_size) return 0;
1228     if (start + count >= palette_size) count = palette_size - start;
1229
1230     EnterCriticalSection( &palette_cs );
1231     for (i = 0; i < count; i++)
1232     {
1233         entries[i].peRed   = COLOR_sysPal[start + i].peRed;
1234         entries[i].peGreen = COLOR_sysPal[start + i].peGreen;
1235         entries[i].peBlue  = COLOR_sysPal[start + i].peBlue;
1236         entries[i].peFlags = 0;
1237         TRACE("\tidx(%02x) -> RGB(%08x)\n", start + i, *(COLORREF*)(entries + i) );
1238     }
1239     LeaveCriticalSection( &palette_cs );
1240     return count;
1241 }
1242
1243
1244 /***********************************************************************
1245  *              GetNearestColor   (X11DRV.@)
1246  */
1247 COLORREF X11DRV_GetNearestColor( PHYSDEV dev, COLORREF color )
1248 {
1249     unsigned char spec_type = color >> 24;
1250     COLORREF nearest;
1251
1252     if (!palette_size) return color;
1253
1254     if (spec_type == 1 || spec_type == 2)
1255     {
1256         /* we need logical palette for PALETTERGB and PALETTEINDEX colorrefs */
1257
1258         UINT index;
1259         PALETTEENTRY entry;
1260         HPALETTE hpal = GetCurrentObject( dev->hdc, OBJ_PAL );
1261
1262         if (!hpal) hpal = GetStockObject( DEFAULT_PALETTE );
1263
1264         if (spec_type == 2) /* PALETTERGB */
1265             index = GetNearestPaletteIndex( hpal, color );
1266         else  /* PALETTEINDEX */
1267             index = LOWORD(color);
1268
1269         if (!GetPaletteEntries( hpal, index, 1, &entry ))
1270         {
1271             WARN("RGB(%x) : idx %d is out of bounds, assuming NULL\n", color, index );
1272             if (!GetPaletteEntries( hpal, 0, 1, &entry )) return CLR_INVALID;
1273         }
1274         color = RGB( entry.peRed,  entry.peGreen, entry.peBlue );
1275     }
1276     color &= 0x00ffffff;
1277     EnterCriticalSection( &palette_cs );
1278     nearest = (0x00ffffff & *(COLORREF*)(COLOR_sysPal + X11DRV_SysPaletteLookupPixel(color, FALSE)));
1279     LeaveCriticalSection( &palette_cs );
1280
1281     TRACE("(%06x): returning %06x\n", color, nearest );
1282     return nearest;
1283 }
1284
1285
1286 /***********************************************************************
1287  *              RealizeDefaultPalette    (X11DRV.@)
1288  */
1289 UINT X11DRV_RealizeDefaultPalette( PHYSDEV dev )
1290 {
1291     UINT ret = 0;
1292
1293     if (palette_size && GetObjectType(dev->hdc) != OBJ_MEMDC)
1294     {
1295         /* lookup is needed to account for SetSystemPaletteUse() stuff */
1296         int i, index, *mapping = palette_get_mapping( GetStockObject(DEFAULT_PALETTE) );
1297         PALETTEENTRY entries[NB_RESERVED_COLORS];
1298
1299         GetPaletteEntries( GetStockObject(DEFAULT_PALETTE), 0, NB_RESERVED_COLORS, entries );
1300         EnterCriticalSection( &palette_cs );
1301         for( i = 0; i < NB_RESERVED_COLORS; i++ )
1302         {
1303             index = X11DRV_PALETTE_LookupSystemXPixel( RGB(entries[i].peRed,
1304                                                            entries[i].peGreen,
1305                                                            entries[i].peBlue) );
1306             /* mapping is allocated in COLOR_InitPalette() */
1307             if( index != mapping[i] )
1308             {
1309                 mapping[i]=index;
1310                 ret++;
1311             }
1312         }
1313         LeaveCriticalSection( &palette_cs );
1314     }
1315     return ret;
1316 }