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