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