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