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