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