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