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