Fixed drive mapping in GET ALLOCATION.
[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, max = 256, bp = 0, wp = 1;
389    int                  step = 1;
390    int                  defaultCM_max_copy;
391    Colormap             defaultCM;
392    XColor               defaultColors[256];
393    HKEY hkey;
394
395    defaultCM_max_copy = 128;
396    COLOR_max = 256;
397
398    if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", &hkey))
399    {
400         char buffer[20];
401         DWORD type, count;
402
403         count = sizeof(buffer);
404         if(!RegQueryValueExA(hkey, "CopyDefaultColors", 0, &type, buffer, &count))
405             defaultCM_max_copy = atoi(buffer);
406
407         count = sizeof(buffer);
408         if(!RegQueryValueExA(hkey, "AllocSystemColors", 0, &type, buffer, &count))
409             COLOR_max = atoi(buffer);
410
411         RegCloseKey(hkey);
412    }
413
414    /* Copy the first bunch of colors out of the default colormap to prevent
415     * colormap flashing as much as possible.  We're likely to get the most
416     * important Window Manager colors, etc in the first 128 colors */
417    defaultCM = DefaultColormap( gdi_display, DefaultScreen(gdi_display) );
418
419    for (i = 0; i < defaultCM_max_copy; i++)
420        defaultColors[i].pixel = (long) i;
421    wine_tsx11_lock();
422    XQueryColors(gdi_display, defaultCM, &defaultColors[0], defaultCM_max_copy);
423    for (i = 0; i < defaultCM_max_copy; i++)
424        XAllocColor( gdi_display, X11DRV_PALETTE_PaletteXColormap, &defaultColors[i] );
425
426    if (COLOR_max > 256) COLOR_max = 256;
427    else if (COLOR_max < 20) COLOR_max = 20;
428    TRACE("%d colors configured.\n", COLOR_max);
429
430    TRACE("Building shared map - %i palette entries\n", palette_size);
431
432    /* Be nice and allocate system colors as read-only */
433
434    for( i = 0; i < NB_RESERVED_COLORS; i++ )
435      {
436         color.red   = sys_pal_template[i].peRed * 65535 / 255;
437         color.green = sys_pal_template[i].peGreen * 65535 / 255;
438         color.blue  = sys_pal_template[i].peBlue * 65535 / 255;
439         color.flags = DoRed | DoGreen | DoBlue;
440
441         if (!XAllocColor( gdi_display, X11DRV_PALETTE_PaletteXColormap, &color ))
442         {
443              XColor     best, c;
444
445              if( !warn++ )
446              {
447                   WARN("Not enough colors for the full system palette.\n");
448
449                   bp = BlackPixel(gdi_display, DefaultScreen(gdi_display));
450                   wp = WhitePixel(gdi_display, DefaultScreen(gdi_display));
451
452                   max = (0xffffffff)>>(32 - screen_depth);
453                   if( max > 256 )
454                   {
455                       step = max/256;
456                       max = 256;
457                   }
458              }
459
460              /* reinit color (XAllocColor() may change it)
461               * and map to the best shared colorcell */
462
463              color.red   = sys_pal_template[i].peRed * 65535 / 255;
464              color.green = sys_pal_template[i].peGreen * 65535 / 255;
465              color.blue  = sys_pal_template[i].peBlue * 65535 / 255;
466
467              best.pixel = best.red = best.green = best.blue = 0;
468              for( c.pixel = 0, diff = 0x7fffffff; c.pixel < max; c.pixel += step )
469              {
470                 XQueryColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &c);
471                 r = (c.red - color.red)>>8;
472                 g = (c.green - color.green)>>8;
473                 b = (c.blue - color.blue)>>8;
474                 r = r*r + g*g + b*b;
475                 if( r < diff ) { best = c; diff = r; }
476              }
477
478              if( XAllocColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &best) )
479                  color.pixel = best.pixel;
480              else color.pixel = (i < NB_RESERVED_COLORS/2)? bp : wp;
481         }
482
483         sysPixel[i] = color.pixel;
484
485         TRACE("syscolor(%lx) -> pixel %i\n",
486                       *(COLORREF*)(sys_pal_template+i), (int)color.pixel);
487
488         /* Set EGA mapping if color in the first or last eight */
489
490         if (i < 8)
491             X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
492         else if (i >= NB_RESERVED_COLORS - 8 )
493             X11DRV_PALETTE_mapEGAPixel[i - (NB_RESERVED_COLORS-16)] = color.pixel;
494      }
495    wine_tsx11_unlock();
496
497    /* now allocate changeable set */
498
499    if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
500      {
501         int c_min = 0, c_max = palette_size, c_val;
502
503         TRACE("Dynamic colormap... \n");
504
505         /* let's become the first client that actually follows
506          * X guidelines and does binary search...
507          */
508
509         if((pixDynMapping = (unsigned long*)HeapAlloc(GetProcessHeap(), 0, sizeof(long)*palette_size)) == NULL) {
510             WARN("Out of memory while building system palette.\n");
511             return FALSE;
512         }
513
514         wine_tsx11_lock();
515         /* comment this out if you want to debug palette init */
516         XGrabServer(gdi_display);
517
518         while( c_max - c_min > 0 )
519           {
520              c_val = (c_max + c_min)/2 + (c_max + c_min)%2;
521
522              if( !XAllocColorCells(gdi_display, X11DRV_PALETTE_PaletteXColormap, False,
523                                    plane_masks, 0, pixDynMapping, c_val) )
524                  c_max = c_val - 1;
525              else
526                {
527                  XFreeColors(gdi_display, X11DRV_PALETTE_PaletteXColormap, pixDynMapping, c_val, 0);
528                  c_min = c_val;
529                }
530           }
531
532         if( c_min > COLOR_max - NB_RESERVED_COLORS)
533             c_min = COLOR_max - NB_RESERVED_COLORS;
534
535         c_min = (c_min/2) + (c_min/2);          /* need even set for split palette */
536
537         if( c_min > 0 )
538           if( !XAllocColorCells(gdi_display, X11DRV_PALETTE_PaletteXColormap, False,
539                                 plane_masks, 0, pixDynMapping, c_min) )
540             {
541               WARN("Inexplicable failure during colorcell allocation.\n");
542               c_min = 0;
543             }
544
545         palette_size = c_min + NB_RESERVED_COLORS;
546
547         XUngrabServer(gdi_display);
548         wine_tsx11_unlock();
549
550         TRACE("adjusted size %i colorcells\n", palette_size);
551      }
552    else if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
553         {
554           /* virtual colorspace - ToPhysical takes care of
555            * color translations but we have to allocate full palette
556            * to maintain compatibility
557            */
558           palette_size = 256;
559           TRACE("Virtual colorspace - screendepth %i\n", screen_depth);
560         }
561    else palette_size = NB_RESERVED_COLORS;      /* system palette only - however we can alloc a bunch
562                                          * of colors and map to them */
563
564    TRACE("Shared system palette uses %i colors.\n", palette_size);
565
566    /* set gap to account for pixel shortage. It has to be right in the center
567     * of the system palette because otherwise raster ops get screwed. */
568
569    if( palette_size >= 256 )
570      { COLOR_gapStart = 256; COLOR_gapEnd = -1; }
571    else
572      { COLOR_gapStart = palette_size/2; COLOR_gapEnd = 255 - palette_size/2; }
573
574    X11DRV_PALETTE_firstFree = ( palette_size > NB_RESERVED_COLORS &&
575                       (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL || !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED)) )
576                      ? NB_RESERVED_COLORS/2 : -1;
577
578    COLOR_sysPal = (PALETTEENTRY*)HeapAlloc(GetProcessHeap(),0,sizeof(PALETTEENTRY)*256);
579    if(COLOR_sysPal == NULL) {
580        ERR("Can not allocate system palette!\n");
581        return FALSE;
582    }
583
584    /* setup system palette entry <-> pixel mappings and fill in 20 fixed entries */
585
586    if (screen_depth <= 8)
587    {
588        X11DRV_PALETTE_XPixelToPalette = HeapAlloc( GetProcessHeap(), 0, 256 * sizeof(int) );
589        if(X11DRV_PALETTE_XPixelToPalette == NULL) {
590            ERR("Out of memory: XPixelToPalette!\n");
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 = (int*)HeapAlloc(GetProcessHeap(),0,sizeof(int)*256);
602    if(X11DRV_PALETTE_PaletteToXPixel == NULL) {
603        ERR("Out of memory: PaletteToXPixel!\n");
604        return FALSE;
605    }
606
607    for( i = j = 0; i < 256; i++ )
608    {
609       if( i >= COLOR_gapStart && i <= COLOR_gapEnd )
610       {
611          X11DRV_PALETTE_PaletteToXPixel[i] = NB_PALETTE_EMPTY_VALUE;
612          COLOR_sysPal[i].peFlags = 0;   /* mark as unused */
613          continue;
614       }
615
616       if( i < NB_RESERVED_COLORS/2 )
617       {
618         X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[i];
619         COLOR_sysPal[i] = sys_pal_template[i];
620         COLOR_sysPal[i].peFlags |= PC_SYS_USED;
621       }
622       else if( i >= 256 - NB_RESERVED_COLORS/2 )
623       {
624         X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[(i + NB_RESERVED_COLORS) - 256];
625         COLOR_sysPal[i] = sys_pal_template[(i + NB_RESERVED_COLORS) - 256];
626         COLOR_sysPal[i].peFlags |= PC_SYS_USED;
627       }
628       else if( pixDynMapping )
629              X11DRV_PALETTE_PaletteToXPixel[i] = pixDynMapping[j++];
630            else
631              X11DRV_PALETTE_PaletteToXPixel[i] = i;
632
633       TRACE("index %i -> pixel %i\n", i, X11DRV_PALETTE_PaletteToXPixel[i]);
634
635       if( X11DRV_PALETTE_XPixelToPalette )
636           X11DRV_PALETTE_XPixelToPalette[X11DRV_PALETTE_PaletteToXPixel[i]] = i;
637    }
638
639    if( pixDynMapping ) HeapFree(GetProcessHeap(), 0, pixDynMapping);
640
641    return TRUE;
642 }
643
644 /***********************************************************************
645  *      Colormap Initialization
646  */
647 static void X11DRV_PALETTE_FillDefaultColors( const PALETTEENTRY *sys_pal_template )
648 {
649  /* initialize unused entries to what Windows uses as a color
650   * cube - based on Greg Kreider's code.
651   */
652
653   int i = 0, idx = 0;
654   int red, no_r, inc_r;
655   int green, no_g, inc_g;
656   int blue, no_b, inc_b;
657
658   if (palette_size <= NB_RESERVED_COLORS)
659         return;
660   while (i*i*i < (palette_size - NB_RESERVED_COLORS)) i++;
661   no_r = no_g = no_b = --i;
662   if ((no_r * (no_g+1) * no_b) < (palette_size - NB_RESERVED_COLORS)) no_g++;
663   if ((no_r * no_g * (no_b+1)) < (palette_size - NB_RESERVED_COLORS)) no_b++;
664   inc_r = (255 - NB_COLORCUBE_START_INDEX)/no_r;
665   inc_g = (255 - NB_COLORCUBE_START_INDEX)/no_g;
666   inc_b = (255 - NB_COLORCUBE_START_INDEX)/no_b;
667
668   wine_tsx11_lock();
669
670   idx = X11DRV_PALETTE_firstFree;
671
672   if( idx != -1 )
673     for (blue = NB_COLORCUBE_START_INDEX; blue < 256 && idx; blue += inc_b )
674      for (green = NB_COLORCUBE_START_INDEX; green < 256 && idx; green += inc_g )
675       for (red = NB_COLORCUBE_START_INDEX; red < 256 && idx; red += inc_r )
676       {
677          /* weird but true */
678
679          if( red == NB_COLORCUBE_START_INDEX && green == red && blue == green ) continue;
680
681          COLOR_sysPal[idx].peRed = red;
682          COLOR_sysPal[idx].peGreen = green;
683          COLOR_sysPal[idx].peBlue = blue;
684
685          /* set X color */
686
687          if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
688          {
689             if (X11DRV_PALETTE_PRed.max != 255) no_r = (red * X11DRV_PALETTE_PRed.max) / 255;
690             if (X11DRV_PALETTE_PGreen.max != 255) no_g = (green * X11DRV_PALETTE_PGreen.max) / 255;
691             if (X11DRV_PALETTE_PBlue.max != 255) no_b = (blue * X11DRV_PALETTE_PBlue.max) / 255;
692
693             X11DRV_PALETTE_PaletteToXPixel[idx] = (no_r << X11DRV_PALETTE_PRed.shift) | (no_g << X11DRV_PALETTE_PGreen.shift) | (no_b << X11DRV_PALETTE_PBlue.shift);
694          }
695          else if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
696          {
697            XColor color;
698            color.pixel = (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[idx] : idx;
699            color.red = COLOR_sysPal[idx].peRed << 8;
700            color.green = COLOR_sysPal[idx].peGreen << 8;
701            color.blue =  COLOR_sysPal[idx].peBlue << 8;
702            color.flags = DoRed | DoGreen | DoBlue;
703            XStoreColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &color);
704          }
705          idx = X11DRV_PALETTE_freeList[idx];
706       }
707
708   /* try to fill some entries in the "gap" with
709    * what's already in the colormap - they will be
710    * mappable to but not changeable. */
711
712   if( COLOR_gapStart < COLOR_gapEnd && X11DRV_PALETTE_XPixelToPalette )
713   {
714     XColor      xc;
715     int         r, g, b, max;
716
717     max = COLOR_max - (256 - (COLOR_gapEnd - COLOR_gapStart));
718     for ( i = 0, idx = COLOR_gapStart; i < 256 && idx <= COLOR_gapEnd; i++ )
719       if( X11DRV_PALETTE_XPixelToPalette[i] == NB_PALETTE_EMPTY_VALUE )
720         {
721           xc.pixel = i;
722
723           XQueryColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &xc);
724           r = xc.red>>8; g = xc.green>>8; b = xc.blue>>8;
725
726           if( xc.pixel < 256 && X11DRV_PALETTE_CheckSysColor( sys_pal_template, RGB(r, g, b)) &&
727               XAllocColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &xc) )
728           {
729              X11DRV_PALETTE_XPixelToPalette[xc.pixel] = idx;
730              X11DRV_PALETTE_PaletteToXPixel[idx] = xc.pixel;
731            *(COLORREF*)(COLOR_sysPal + idx) = RGB(r, g, b);
732              COLOR_sysPal[idx++].peFlags |= PC_SYS_USED;
733              if( --max <= 0 ) break;
734           }
735         }
736     COLOR_gapFilled = idx - COLOR_gapStart;
737   }
738   wine_tsx11_unlock();
739 }
740
741
742 /***********************************************************************
743  *           X11DRV_IsSolidColor
744  *
745  * Check whether 'color' can be represented with a solid color.
746  */
747 BOOL X11DRV_IsSolidColor( COLORREF color )
748 {
749     int i;
750     const PALETTEENTRY *pEntry = COLOR_sysPal;
751
752     if (color & 0xff000000) return TRUE;  /* indexed color */
753
754     if (!color || (color == 0xffffff)) return TRUE;  /* black or white */
755
756     if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL) return TRUE;  /* no palette */
757
758     for (i = 0; i < palette_size ; i++, pEntry++)
759     {
760         if( i < COLOR_gapStart || i > COLOR_gapEnd )
761             if ((GetRValue(color) == pEntry->peRed) &&
762                 (GetGValue(color) == pEntry->peGreen) &&
763                 (GetBValue(color) == pEntry->peBlue)) return TRUE;
764     }
765     return FALSE;
766 }
767
768
769 /***********************************************************************
770  *           X11DRV_PALETTE_ToLogical
771  *
772  * Return RGB color for given X pixel.
773  */
774 COLORREF X11DRV_PALETTE_ToLogical(int pixel)
775 {
776     XColor color;
777
778 #if 0
779     /* truecolor visual */
780
781     if (screen_depth >= 24) return pixel;
782 #endif
783
784     /* check for hicolor visuals first */
785
786     if ( (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) && !X11DRV_PALETTE_Graymax )
787     {
788          color.red = (pixel >> X11DRV_PALETTE_LRed.shift) & X11DRV_PALETTE_LRed.max;
789          if (X11DRV_PALETTE_LRed.scale<8)
790              color.red=  color.red   << (8-X11DRV_PALETTE_LRed.scale) |
791                          color.red   >> (2*X11DRV_PALETTE_LRed.scale-8);
792          color.green = (pixel >> X11DRV_PALETTE_LGreen.shift) & X11DRV_PALETTE_LGreen.max;
793          if (X11DRV_PALETTE_LGreen.scale<8)
794              color.green=color.green << (8-X11DRV_PALETTE_LGreen.scale) |
795                          color.green >> (2*X11DRV_PALETTE_LGreen.scale-8);
796          color.blue = (pixel >> X11DRV_PALETTE_LBlue.shift) & X11DRV_PALETTE_LBlue.max;
797          if (X11DRV_PALETTE_LBlue.scale<8)
798              color.blue= color.blue  << (8-X11DRV_PALETTE_LBlue.scale)  |
799                          color.blue  >> (2*X11DRV_PALETTE_LBlue.scale-8);
800                  return RGB(color.red,color.green,color.blue);
801     }
802
803     /* check if we can bypass X */
804
805     if ((screen_depth <= 8) && (pixel < 256) &&
806         !(X11DRV_PALETTE_PaletteFlags & (X11DRV_PALETTE_VIRTUAL | X11DRV_PALETTE_FIXED)) ) {
807          return  ( *(COLORREF*)(COLOR_sysPal +
808                    ((X11DRV_PALETTE_XPixelToPalette)?X11DRV_PALETTE_XPixelToPalette[pixel]:pixel)) ) & 0x00ffffff;
809     }
810
811     wine_tsx11_lock();
812     color.pixel = pixel;
813     XQueryColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &color);
814     wine_tsx11_unlock();
815     return RGB(color.red >> 8, color.green >> 8, color.blue >> 8);
816 }
817
818
819 /***********************************************************************
820  *           X11DRV_SysPaletteLookupPixel
821  */
822 static int X11DRV_SysPaletteLookupPixel( COLORREF col, BOOL skipReserved )
823 {
824     int i, best = 0, diff = 0x7fffffff;
825     int r,g,b;
826
827     for( i = 0; i < palette_size && diff ; i++ )
828     {
829         if( !(COLOR_sysPal[i].peFlags & PC_SYS_USED) ||
830             (skipReserved && COLOR_sysPal[i].peFlags  & PC_SYS_RESERVED) )
831             continue;
832
833         r = COLOR_sysPal[i].peRed - GetRValue(col);
834         g = COLOR_sysPal[i].peGreen - GetGValue(col);
835         b = COLOR_sysPal[i].peBlue - GetBValue(col);
836
837         r = r*r + g*g + b*b;
838
839         if( r < diff ) { best = i; diff = r; }
840     }
841     return best;
842 }
843
844
845 /***********************************************************************
846  *           X11DRV_PALETTE_ToPhysical
847  *
848  * Return the physical color closest to 'color'.
849  */
850 int X11DRV_PALETTE_ToPhysical( X11DRV_PDEVICE *physDev, COLORREF color )
851 {
852     WORD                 index = 0;
853     HPALETTE hPal = physDev ? GetCurrentObject(physDev->hdc, OBJ_PAL ) : GetStockObject(DEFAULT_PALETTE);
854     unsigned char        spec_type = color >> 24;
855     PALETTEOBJ*          palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hPal, PALETTE_MAGIC );
856
857     /* palPtr can be NULL when DC is being destroyed */
858     if( !palPtr ) return 0;
859
860     if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED )
861     {
862         /* there is no colormap limitation; we are going to have to compute
863          * the pixel value from the visual information stored earlier
864          */
865
866         unsigned        long red, green, blue;
867         unsigned        idx = 0;
868
869         switch(spec_type)
870         {
871           case 1: /* PALETTEINDEX */
872
873             if( (idx = color & 0xffff) >= palPtr->logpalette.palNumEntries)
874             {
875                 WARN("RGB(%lx) : idx %d is out of bounds, assuming black\n", color, idx);
876                 GDI_ReleaseObj( hPal );
877                 return 0;
878             }
879
880             if( palPtr->mapping )
881             {
882                 int ret = palPtr->mapping[idx];
883                 GDI_ReleaseObj( hPal );
884                 return ret;
885             }
886             color = *(COLORREF*)(palPtr->logpalette.palPalEntry + idx);
887             break;
888
889           default:
890             color &= 0xffffff;
891             /* fall through to RGB */
892
893           case 0: /* RGB */
894             if (physDev && (physDev->depth == 1) )
895             {
896                 GDI_ReleaseObj( hPal );
897                 return (((color >> 16) & 0xff) +
898                         ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
899             }
900
901         }
902
903         red = GetRValue(color); green = GetGValue(color); blue = GetBValue(color);
904
905         if (X11DRV_PALETTE_Graymax)
906         {
907             /* grayscale only; return scaled value */
908             GDI_ReleaseObj( hPal );
909             return ( (red * 30 + green * 59 + blue * 11) * X11DRV_PALETTE_Graymax) / 25500;
910         }
911         else
912         {
913             /* scale each individually and construct the TrueColor pixel value */
914             if (X11DRV_PALETTE_PRed.scale < 8)
915                 red = red >> (8-X11DRV_PALETTE_PRed.scale);
916             else if (X11DRV_PALETTE_PRed.scale > 8)
917                 red =   red   << (X11DRV_PALETTE_PRed.scale-8) |
918                         red   >> (16-X11DRV_PALETTE_PRed.scale);
919             if (X11DRV_PALETTE_PGreen.scale < 8)
920                 green = green >> (8-X11DRV_PALETTE_PGreen.scale);
921             else if (X11DRV_PALETTE_PGreen.scale > 8)
922                 green = green << (X11DRV_PALETTE_PGreen.scale-8) |
923                         green >> (16-X11DRV_PALETTE_PGreen.scale);
924             if (X11DRV_PALETTE_PBlue.scale < 8)
925                 blue =  blue  >> (8-X11DRV_PALETTE_PBlue.scale);
926             else if (X11DRV_PALETTE_PBlue.scale > 8)
927                 blue =  blue  << (X11DRV_PALETTE_PBlue.scale-8) |
928                         blue  >> (16-X11DRV_PALETTE_PBlue.scale);
929
930             GDI_ReleaseObj( hPal );
931             return (red << X11DRV_PALETTE_PRed.shift) | (green << X11DRV_PALETTE_PGreen.shift) | (blue << X11DRV_PALETTE_PBlue.shift);
932         }
933     }
934     else
935     {
936
937         if( !palPtr->mapping )
938             WARN("Palette %p is not realized\n", hPal);
939
940         switch(spec_type)       /* we have to peruse DC and system palette */
941         {
942             default:
943                 color &= 0xffffff;
944                 /* fall through to RGB */
945
946             case 0:  /* RGB */
947                 if (physDev && (physDev->depth == 1) )
948                 {
949                     GDI_ReleaseObj( hPal );
950                     return (((color >> 16) & 0xff) +
951                             ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
952                 }
953
954                 index = X11DRV_SysPaletteLookupPixel( color, FALSE);
955                 if (X11DRV_PALETTE_PaletteToXPixel) index = X11DRV_PALETTE_PaletteToXPixel[index];
956
957                 /* TRACE(palette,"RGB(%lx) -> pixel %i\n", color, index);
958                  */
959                 break;
960             case 1:  /* PALETTEINDEX */
961                 index = color & 0xffff;
962
963                 if( index >= palPtr->logpalette.palNumEntries )
964                     WARN("RGB(%lx) : index %i is out of bounds\n", color, index);
965                 else if( palPtr->mapping ) index = palPtr->mapping[index];
966
967                 /*  TRACE(palette,"PALETTEINDEX(%04x) -> pixel %i\n", (WORD)color, index);
968                  */
969                 break;
970             case 2:  /* PALETTERGB */
971                 index = GetNearestPaletteIndex( hPal, color );
972                 if (palPtr->mapping) index = palPtr->mapping[index];
973                 /* TRACE(palette,"PALETTERGB(%lx) -> pixel %i\n", color, index);
974                  */
975                 break;
976         }
977     }
978
979     GDI_ReleaseObj( hPal );
980     return index;
981 }
982
983 /***********************************************************************
984  *           X11DRV_PALETTE_LookupSystemXPixel
985  */
986 static int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col)
987 {
988  int            i, best = 0, diff = 0x7fffffff;
989  int            size = palette_size;
990  int            r,g,b;
991
992  for( i = 0; i < size && diff ; i++ )
993     {
994       if( i == NB_RESERVED_COLORS/2 )
995       {
996         int newi = size - NB_RESERVED_COLORS/2;
997         if (newi>i) i=newi;
998       }
999
1000       r = COLOR_sysPal[i].peRed - GetRValue(col);
1001       g = COLOR_sysPal[i].peGreen - GetGValue(col);
1002       b = COLOR_sysPal[i].peBlue - GetBValue(col);
1003
1004       r = r*r + g*g + b*b;
1005
1006       if( r < diff ) { best = i; diff = r; }
1007     }
1008
1009  return (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[best] : best;
1010 }
1011
1012 /***********************************************************************
1013  *           X11DRV_PALETTE_FormatSystemPalette
1014  */
1015 static void X11DRV_PALETTE_FormatSystemPalette(void)
1016 {
1017  /* Build free list so we'd have an easy way to find
1018   * out if there are any available colorcells.
1019   */
1020
1021   int i, j = X11DRV_PALETTE_firstFree = NB_RESERVED_COLORS/2;
1022
1023   COLOR_sysPal[j].peFlags = 0;
1024   for( i = NB_RESERVED_COLORS/2 + 1 ; i < 256 - NB_RESERVED_COLORS/2 ; i++ )
1025     if( i < COLOR_gapStart || i > COLOR_gapEnd )
1026       {
1027         COLOR_sysPal[i].peFlags = 0;  /* unused tag */
1028         X11DRV_PALETTE_freeList[j] = i;   /* next */
1029         j = i;
1030       }
1031   X11DRV_PALETTE_freeList[j] = 0;
1032 }
1033
1034 /***********************************************************************
1035  *           X11DRV_PALETTE_CheckSysColor
1036  */
1037 static BOOL X11DRV_PALETTE_CheckSysColor( const PALETTEENTRY *sys_pal_template, COLORREF c)
1038 {
1039   int i;
1040   for( i = 0; i < NB_RESERVED_COLORS; i++ )
1041        if( c == (*(COLORREF*)(sys_pal_template + i) & 0x00ffffff) )
1042            return 0;
1043   return 1;
1044 }
1045
1046
1047 /***********************************************************************
1048  *           X11DRV_LookupSysPaletteExact
1049  */
1050 static int X11DRV_LookupSysPaletteExact( COLORREF col )
1051 {
1052     int i;
1053     BYTE r = GetRValue(col), g = GetGValue(col), b = GetBValue(col);
1054     for( i = 0; i < palette_size; i++ )
1055     {
1056         if( COLOR_sysPal[i].peFlags & PC_SYS_USED )  /* skips gap */
1057             if( COLOR_sysPal[i].peRed == r &&
1058                 COLOR_sysPal[i].peGreen == g &&
1059                 COLOR_sysPal[i].peBlue == b )
1060                 return i;
1061     }
1062     return -1;
1063 }
1064
1065
1066 /***********************************************************************
1067  *           X11DRV_PALETTE_SetMapping
1068  *
1069  * Set the color-mapping table for selected palette.
1070  * Return number of entries which mapping has changed.
1071  */
1072 static UINT X11DRV_PALETTE_SetMapping( PALETTEOBJ* palPtr, UINT uStart, UINT uNum, BOOL mapOnly )
1073 {
1074     char flag;
1075     int  prevMapping = (palPtr->mapping) ? 1 : 0;
1076     int  index;
1077     UINT iRemapped = 0;
1078     int* mapping;
1079
1080     /* reset dynamic system palette entries */
1081
1082     if( !mapOnly && X11DRV_PALETTE_firstFree != -1)
1083          X11DRV_PALETTE_FormatSystemPalette();
1084
1085     /* initialize palette mapping table */
1086     if (palPtr->mapping) 
1087         mapping = HeapReAlloc( GetProcessHeap(), 0, palPtr->mapping,
1088                            sizeof(int)*palPtr->logpalette.palNumEntries);
1089     else 
1090         mapping = HeapAlloc( GetProcessHeap(), 0, 
1091                            sizeof(int)*palPtr->logpalette.palNumEntries);
1092
1093     if(mapping == NULL) {
1094         ERR("Can not allocate new mapping -- memory exausted!\n");
1095         return 0;
1096     }
1097     palPtr->mapping = mapping;
1098
1099     if (uStart >= palPtr->logpalette.palNumEntries) return 0;
1100
1101     if (uStart + uNum > palPtr->logpalette.palNumEntries)
1102         uNum = palPtr->logpalette.palNumEntries - uStart;
1103
1104     for( uNum += uStart; uStart < uNum; uStart++ )
1105     {
1106         index = -1;
1107         flag = PC_SYS_USED;
1108
1109         switch( palPtr->logpalette.palPalEntry[uStart].peFlags & 0x07 )
1110         {
1111         case PC_EXPLICIT:   /* palette entries are indices into system palette */
1112             index = *(WORD*)(palPtr->logpalette.palPalEntry + uStart);
1113             if( index > 255 || (index >= COLOR_gapStart && index <= COLOR_gapEnd) )
1114             {
1115                 WARN("PC_EXPLICIT: idx %d out of system palette, assuming black.\n", index);
1116                 index = 0;
1117             }
1118             break;
1119
1120         case PC_RESERVED:   /* forbid future mappings to this entry */
1121             flag |= PC_SYS_RESERVED;
1122
1123             /* fall through */
1124         default:            /* try to collapse identical colors */
1125             index = X11DRV_LookupSysPaletteExact(*(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
1126             /* fall through */
1127         case PC_NOCOLLAPSE:
1128             if( index < 0 )
1129             {
1130                 if( X11DRV_PALETTE_firstFree > 0 && !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
1131                 {
1132                     XColor color;
1133                     index = X11DRV_PALETTE_firstFree;  /* ought to be available */
1134                     X11DRV_PALETTE_firstFree = X11DRV_PALETTE_freeList[index];
1135
1136                     color.pixel = (X11DRV_PALETTE_PaletteToXPixel) ? X11DRV_PALETTE_PaletteToXPixel[index] : index;
1137                     color.red = palPtr->logpalette.palPalEntry[uStart].peRed << 8;
1138                     color.green = palPtr->logpalette.palPalEntry[uStart].peGreen << 8;
1139                     color.blue = palPtr->logpalette.palPalEntry[uStart].peBlue << 8;
1140                     color.flags = DoRed | DoGreen | DoBlue;
1141                     wine_tsx11_lock();
1142                     XStoreColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &color);
1143                     wine_tsx11_unlock();
1144
1145                     COLOR_sysPal[index] = palPtr->logpalette.palPalEntry[uStart];
1146                     COLOR_sysPal[index].peFlags = flag;
1147                     X11DRV_PALETTE_freeList[index] = 0;
1148
1149                     if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
1150                     break;
1151                 }
1152                 else if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
1153                 {
1154                     index = X11DRV_PALETTE_ToPhysical( NULL, 0x00ffffff &
1155                              *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
1156                     break;
1157                 }
1158
1159                 /* we have to map to existing entry in the system palette */
1160
1161                 index = X11DRV_SysPaletteLookupPixel( *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), TRUE);
1162             }
1163             palPtr->logpalette.palPalEntry[uStart].peFlags |= PC_SYS_USED;
1164
1165             if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
1166             break;
1167         }
1168
1169         if( !prevMapping || palPtr->mapping[uStart] != index ) iRemapped++;
1170         palPtr->mapping[uStart] = index;
1171
1172         TRACE("entry %i (%lx) -> pixel %i\n", uStart,
1173                                 *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), index);
1174
1175     }
1176     return iRemapped;
1177 }
1178
1179 /***********************************************************************
1180  *              GetSystemPaletteEntries   (X11DRV.@)
1181  */
1182 UINT X11DRV_GetSystemPaletteEntries( X11DRV_PDEVICE *physDev, UINT start, UINT count,
1183                                      LPPALETTEENTRY entries )
1184 {
1185     UINT i;
1186
1187     if (!entries) return palette_size;
1188     if (start >= palette_size) return 0;
1189     if (start + count >= palette_size) count = palette_size - start;
1190
1191     for (i = 0; i < count; i++)
1192     {
1193         entries[i].peRed   = COLOR_sysPal[start + i].peRed;
1194         entries[i].peGreen = COLOR_sysPal[start + i].peGreen;
1195         entries[i].peBlue  = COLOR_sysPal[start + i].peBlue;
1196         entries[i].peFlags = 0;
1197         TRACE("\tidx(%02x) -> RGB(%08lx)\n", start + i, *(COLORREF*)(entries + i) );
1198     }
1199     return count;
1200 }
1201
1202
1203 /***********************************************************************
1204  *              GetNearestColor   (X11DRV.@)
1205  */
1206 COLORREF X11DRV_GetNearestColor( X11DRV_PDEVICE *physDev, COLORREF color )
1207 {
1208     unsigned char spec_type = color >> 24;
1209     COLORREF nearest;
1210
1211     if (!palette_size) return color;
1212
1213     if (spec_type == 1 || spec_type == 2)
1214     {
1215         /* we need logical palette for PALETTERGB and PALETTEINDEX colorrefs */
1216
1217         UINT index;
1218         PALETTEENTRY entry;
1219         HPALETTE hpal = GetCurrentObject( physDev->hdc, OBJ_PAL );
1220
1221         if (!hpal) hpal = GetStockObject( DEFAULT_PALETTE );
1222
1223         if (spec_type == 2) /* PALETTERGB */
1224             index = GetNearestPaletteIndex( hpal, color );
1225         else  /* PALETTEINDEX */
1226             index = LOWORD(color);
1227
1228         if (!GetPaletteEntries( hpal, index, 1, &entry ))
1229         {
1230             WARN("RGB(%lx) : idx %d is out of bounds, assuming NULL\n", color, index );
1231             if (!GetPaletteEntries( hpal, 0, 1, &entry )) return CLR_INVALID;
1232         }
1233         color = RGB( entry.peRed,  entry.peGreen, entry.peBlue );
1234     }
1235     color &= 0x00ffffff;
1236     nearest = (0x00ffffff & *(COLORREF*)(COLOR_sysPal + X11DRV_SysPaletteLookupPixel(color, FALSE)));
1237
1238     TRACE("(%06lx): returning %06lx\n", color, nearest );
1239     return nearest;
1240 }
1241
1242
1243 /***********************************************************************
1244  *              RealizePalette    (X11DRV.@)
1245  */
1246 UINT X11DRV_RealizePalette( X11DRV_PDEVICE *physDev, HPALETTE hpal, BOOL primary )
1247 {
1248     UINT ret;
1249     PALETTEOBJ *palPtr;
1250
1251     if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL) return 0;
1252
1253     if (!(palPtr = GDI_GetObjPtr( hpal, PALETTE_MAGIC ))) return 0;
1254     ret = X11DRV_PALETTE_SetMapping( palPtr, 0, palPtr->logpalette.palNumEntries, !primary );
1255     GDI_ReleaseObj( hpal );
1256     return ret;
1257 }
1258
1259
1260 /***********************************************************************
1261  *              RealizeDefaultPalette    (X11DRV.@)
1262  */
1263 UINT X11DRV_RealizeDefaultPalette( X11DRV_PDEVICE *physDev )
1264 {
1265     UINT ret = 0;
1266
1267     if (palette_size && GetObjectType(physDev->hdc) != OBJ_MEMDC)
1268     {
1269         PALETTEOBJ*  palPtr = GDI_GetObjPtr( GetStockObject(DEFAULT_PALETTE), PALETTE_MAGIC );
1270         if (palPtr)
1271         {
1272             /* lookup is needed to account for SetSystemPaletteUse() stuff */
1273             int i, index;
1274
1275             for( i = 0; i < 20; i++ )
1276             {
1277                 index = X11DRV_PALETTE_LookupSystemXPixel(*(COLORREF*)(palPtr->logpalette.palPalEntry + i));
1278                 /* mapping is allocated in COLOR_InitPalette() */
1279                 if( index != palPtr->mapping[i] )
1280                 {
1281                     palPtr->mapping[i]=index;
1282                     ret++;
1283                 }
1284             }
1285             GDI_ReleaseObj( GetStockObject(DEFAULT_PALETTE) );
1286         }
1287     }
1288     return ret;
1289 }