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