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