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