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