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