Use GetStockObject() instead of the magic STOCK_* handles.
[wine] / graphics / x11drv / palette.c
1 /* 
2  * X11DRV OEM bitmap objects
3  *
4  * Copyright 1994, 1995 Alexandre Julliard
5  *
6  */
7
8 #include "config.h"
9
10 #include "ts_xlib.h"
11
12 #include <stdlib.h>
13 #include <string.h>
14
15 #include "color.h"
16 #include "debugtools.h"
17 #include "gdi.h"
18 #include "options.h"
19 #include "palette.h"
20 #include "windef.h"
21 #include "x11drv.h"
22
23 DEFAULT_DEBUG_CHANNEL(palette);
24
25 /* Palette indexed mode:
26  *      logical palette -> mapping -> pixel
27  *                                   
28  *
29  * Windows needs contiguous color space ( from 0 to n ) but 
30  * it is possible only with the private colormap. Otherwise we
31  * have to map DC palette indices to real pixel values. With 
32  * private colormaps it boils down to the identity mapping. The
33  * other special case is when we have a fixed color visual with 
34  * the screendepth > 8 - we abandon palette mappings altogether 
35  * because pixel values can be calculated without X server 
36  * assistance.
37  *
38  * Windows palette manager is described in the
39  * http://premium.microsoft.com/msdn/library/techart/f30/f34/f40/d4d/sa942.htm
40  */
41
42 extern PALETTEENTRY *COLOR_sysPal;
43 extern int COLOR_gapStart;
44 extern int COLOR_gapEnd;
45 extern int COLOR_gapFilled;
46 extern int COLOR_max;
47
48 extern const PALETTEENTRY COLOR_sysPalTemplate[NB_RESERVED_COLORS]; 
49
50 Colormap X11DRV_PALETTE_PaletteXColormap = 0;
51 UINT16   X11DRV_PALETTE_PaletteFlags     = 0;
52
53 static int X11DRV_PALETTE_Redshift   = 0; /* to handle abortive X11DRV_PALETTE_VIRTUAL visuals */
54 static int X11DRV_PALETTE_Redmax     = 0;
55 static int X11DRV_PALETTE_Greenshift = 0;
56 static int X11DRV_PALETTE_Greenmax   = 0;
57 static int X11DRV_PALETTE_Blueshift  = 0;
58 static int X11DRV_PALETTE_Bluemax    = 0;
59 static int X11DRV_PALETTE_Graymax    = 0;
60
61 /* First free dynamic color cell, 0 = full palette, -1 = fixed palette */
62 static int           X11DRV_PALETTE_firstFree = 0; 
63 static unsigned char X11DRV_PALETTE_freeList[256];
64
65 /**********************************************************************/
66
67    /* Map an EGA index (0..15) to a pixel value in the system color space.  */
68
69 int X11DRV_PALETTE_mapEGAPixel[16];
70
71 /**********************************************************************/
72
73 #define NB_COLORCUBE_START_INDEX        63
74
75 /* Maps entry in the system palette to X pixel value */
76 int *X11DRV_PALETTE_PaletteToXPixel = NULL;
77
78 /* Maps pixel to the entry in the system palette */
79 int *X11DRV_PALETTE_XPixelToPalette = NULL;
80
81 /**********************************************************************/
82
83 static BOOL X11DRV_PALETTE_BuildPrivateMap(void);
84 static BOOL X11DRV_PALETTE_BuildSharedMap(void);
85 static void X11DRV_PALETTE_ComputeShifts(unsigned long maskbits, int *shift, int *max);
86 static void X11DRV_PALETTE_FillDefaultColors(void);
87 static void X11DRV_PALETTE_FormatSystemPalette(void);
88 static BOOL X11DRV_PALETTE_CheckSysColor(COLORREF c);
89 static int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col);
90
91 /***********************************************************************
92  *           COLOR_Init
93  *
94  * Initialize color management.
95  */
96 BOOL X11DRV_PALETTE_Init(void)
97 {
98     int mask, white, black;
99     int monoPlane;
100
101     Visual *visual = X11DRV_GetVisual();
102
103     TRACE("initializing palette manager...\n");
104
105     white = WhitePixelOfScreen( X11DRV_GetXScreen() );
106     black = BlackPixelOfScreen( X11DRV_GetXScreen() );
107     monoPlane = 1;
108     for( mask = 1; !((white & mask)^(black & mask)); mask <<= 1 )
109          monoPlane++;
110     X11DRV_PALETTE_PaletteFlags = (white & mask) ? X11DRV_PALETTE_WHITESET : 0;
111     X11DRV_DevCaps.sizePalette = visual->map_entries;
112
113     switch(visual->class)
114     {
115     case DirectColor:
116         X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_VIRTUAL;
117     case GrayScale:
118     case PseudoColor:
119         if (PROFILE_GetWineIniBool( "x11drv", "PrivateColorMap", 0 ))
120         {
121             XSetWindowAttributes win_attr;
122
123             X11DRV_PALETTE_PaletteXColormap = TSXCreateColormap( display, X11DRV_GetXRootWindow(),
124                                                  visual, AllocAll );
125             if (X11DRV_PALETTE_PaletteXColormap)
126             {
127                 X11DRV_PALETTE_PaletteFlags |= (X11DRV_PALETTE_PRIVATE | X11DRV_PALETTE_WHITESET);
128
129                 monoPlane = 1;
130                 for( white = X11DRV_DevCaps.sizePalette - 1; !(white & 1); white >>= 1 )
131                      monoPlane++;
132
133                 if( X11DRV_GetXRootWindow() != DefaultRootWindow(display) )
134                 {
135                     win_attr.colormap = X11DRV_PALETTE_PaletteXColormap;
136                     TSXChangeWindowAttributes( display, X11DRV_GetXRootWindow(),
137                                          CWColormap, &win_attr );
138                 }
139                 break;
140             }
141         }
142         X11DRV_PALETTE_PaletteXColormap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
143         break;
144
145     case StaticGray:
146         X11DRV_PALETTE_PaletteXColormap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
147         X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_FIXED;
148         X11DRV_PALETTE_Graymax = (1 << X11DRV_GetDepth())-1;
149         break;
150
151     case TrueColor:
152         X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_VIRTUAL;
153     case StaticColor: {
154         int *depths,nrofdepths;
155         /* FIXME: hack to detect XFree32 XF_VGA16 ... We just have
156          * depths 1 and 4
157          */
158         depths=TSXListDepths(display,DefaultScreen(display),&nrofdepths);
159         if ((nrofdepths==2) && ((depths[0]==4) || depths[1]==4)) {
160             monoPlane = 1;
161             for( white = X11DRV_DevCaps.sizePalette - 1; !(white & 1); white >>= 1 )
162                 monoPlane++;
163             X11DRV_PALETTE_PaletteFlags = (white & mask) ? X11DRV_PALETTE_WHITESET : 0;
164             X11DRV_PALETTE_PaletteXColormap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
165             TSXFree(depths);
166             break;
167         }
168         TSXFree(depths);
169         X11DRV_PALETTE_PaletteXColormap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
170         X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_FIXED;
171         X11DRV_PALETTE_ComputeShifts(visual->red_mask, &X11DRV_PALETTE_Redshift, &X11DRV_PALETTE_Redmax);
172         X11DRV_PALETTE_ComputeShifts(visual->green_mask, &X11DRV_PALETTE_Greenshift, &X11DRV_PALETTE_Greenmax);
173         X11DRV_PALETTE_ComputeShifts(visual->blue_mask, &X11DRV_PALETTE_Blueshift, &X11DRV_PALETTE_Bluemax);
174         break;
175     }
176     }
177
178     TRACE(" visual class %i (%i)\n",  visual->class, monoPlane);
179
180     memset(X11DRV_PALETTE_freeList, 0, 256*sizeof(unsigned char));
181
182     if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
183         X11DRV_PALETTE_BuildPrivateMap();
184     else
185         X11DRV_PALETTE_BuildSharedMap();
186
187     /* Build free list */
188
189     if( X11DRV_PALETTE_firstFree != -1 )
190         X11DRV_PALETTE_FormatSystemPalette();
191
192     X11DRV_PALETTE_FillDefaultColors();
193
194     if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL ) 
195         X11DRV_DevCaps.sizePalette = 0;
196     else
197     {
198         X11DRV_DevCaps.rasterCaps |= RC_PALETTE;
199         X11DRV_DevCaps.sizePalette = visual->map_entries;
200     }
201
202     return TRUE;
203 }
204
205 /***********************************************************************
206  *           X11DRV_PALETTE_Cleanup
207  *
208  * Free external colors we grabbed in the FillDefaultPalette()
209  */
210 void X11DRV_PALETTE_Cleanup(void)
211 {
212   if( COLOR_gapFilled )
213     TSXFreeColors(display, X11DRV_PALETTE_PaletteXColormap, 
214                   (unsigned long*)(X11DRV_PALETTE_PaletteToXPixel + COLOR_gapStart), 
215                   COLOR_gapFilled, 0);
216 }
217
218 /***********************************************************************
219  *              X11DRV_PALETTE_ComputeShifts
220  *
221  * Calculate conversion parameters for direct mapped visuals
222  */
223 static void X11DRV_PALETTE_ComputeShifts(unsigned long maskbits, int *shift, int *max)
224 {
225     int i;
226
227     if (maskbits==0)
228     {
229         *shift=0;
230         *max=0;
231         return;
232     }
233
234     for(i=0;!(maskbits&1);i++)
235         maskbits >>= 1;
236
237     *shift = i;
238     *max = maskbits;
239 }
240
241 /***********************************************************************
242  *           X11DRV_PALETTE_BuildPrivateMap
243  *
244  * Allocate colorcells and initialize mapping tables.
245  */
246 static BOOL X11DRV_PALETTE_BuildPrivateMap(void)
247 {
248     /* Private colormap - identity mapping */
249
250     XColor color;
251     int i; 
252
253     if((COLOR_sysPal = (PALETTEENTRY*)HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY)*X11DRV_DevCaps.sizePalette)) == NULL) {
254         WARN("Can not allocate system palette\n");
255         return FALSE;
256     }
257
258     TRACE("Building private map - %i palette entries\n", X11DRV_DevCaps.sizePalette);
259
260       /* Allocate system palette colors */ 
261
262     for( i=0; i < X11DRV_DevCaps.sizePalette; i++ )
263     {
264        if( i < NB_RESERVED_COLORS/2 )
265        {
266          color.red   = COLOR_sysPalTemplate[i].peRed * 65535 / 255;
267          color.green = COLOR_sysPalTemplate[i].peGreen * 65535 / 255;
268          color.blue  = COLOR_sysPalTemplate[i].peBlue * 65535 / 255;
269          COLOR_sysPal[i] = COLOR_sysPalTemplate[i];
270        }
271        else if( i >= X11DRV_DevCaps.sizePalette - NB_RESERVED_COLORS/2 )
272        {
273          int j = NB_RESERVED_COLORS + i - X11DRV_DevCaps.sizePalette;
274          color.red   = COLOR_sysPalTemplate[j].peRed * 65535 / 255;
275          color.green = COLOR_sysPalTemplate[j].peGreen * 65535 / 255;
276          color.blue  = COLOR_sysPalTemplate[j].peBlue * 65535 / 255;
277          COLOR_sysPal[i] = COLOR_sysPalTemplate[j];
278        }
279
280        color.flags = DoRed | DoGreen | DoBlue;
281        color.pixel = i;
282        TSXStoreColor(display, X11DRV_PALETTE_PaletteXColormap, &color);
283
284        /* Set EGA mapping if color is from the first or last eight */
285
286        if (i < 8)
287            X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
288        else if (i >= X11DRV_DevCaps.sizePalette - 8 )
289            X11DRV_PALETTE_mapEGAPixel[i - (X11DRV_DevCaps.sizePalette - 16)] = color.pixel;
290     }
291
292     X11DRV_PALETTE_XPixelToPalette = X11DRV_PALETTE_PaletteToXPixel = NULL;
293
294     COLOR_gapStart = 256; COLOR_gapEnd = -1;
295
296     X11DRV_PALETTE_firstFree = (X11DRV_DevCaps.sizePalette > NB_RESERVED_COLORS)?NB_RESERVED_COLORS/2 : -1;
297
298     return FALSE;
299 }
300
301 /***********************************************************************
302  *           X11DRV_PALETTE_BuildSharedMap
303  *
304  * Allocate colorcells and initialize mapping tables.
305  */
306 static BOOL X11DRV_PALETTE_BuildSharedMap(void)
307 {
308    XColor               color;
309    unsigned long        sysPixel[NB_RESERVED_COLORS];
310    unsigned long*       pixDynMapping = NULL;
311    unsigned long        plane_masks[1];
312    int                  i, j, warn = 0;
313    int                  diff, r, g, b, max = 256, bp = 0, wp = 1;
314    int                  step = 1;
315
316    /* read "AllocSystemColors" from wine.conf */
317
318    COLOR_max = PROFILE_GetWineIniInt( "x11drv", "AllocSystemColors", 256);
319    if (COLOR_max > 256) COLOR_max = 256;
320    else if (COLOR_max < 20) COLOR_max = 20;
321    TRACE("%d colors configured.\n", COLOR_max);
322    
323    TRACE("Building shared map - %i palette entries\n", X11DRV_DevCaps.sizePalette);
324
325    /* Be nice and allocate system colors as read-only */
326
327    for( i = 0; i < NB_RESERVED_COLORS; i++ )
328      { 
329         color.red   = COLOR_sysPalTemplate[i].peRed * 65535 / 255;
330         color.green = COLOR_sysPalTemplate[i].peGreen * 65535 / 255;
331         color.blue  = COLOR_sysPalTemplate[i].peBlue * 65535 / 255;
332         color.flags = DoRed | DoGreen | DoBlue;
333
334         if (!TSXAllocColor( display, X11DRV_PALETTE_PaletteXColormap, &color ))
335         { 
336              XColor     best, c;
337              
338              if( !warn++ ) 
339              {
340                   WARN("Not enough colors for the full system palette.\n");
341
342                   bp = BlackPixel(display, DefaultScreen(display));
343                   wp = WhitePixel(display, DefaultScreen(display));
344
345                   max = (0xffffffff)>>(32 - X11DRV_GetDepth());
346                   if( max > 256 ) 
347                   {
348                       step = max/256;
349                       max = 256;
350                   }
351              }
352
353              /* reinit color (XAllocColor() may change it)
354               * and map to the best shared colorcell */
355
356              color.red   = COLOR_sysPalTemplate[i].peRed * 65535 / 255;
357              color.green = COLOR_sysPalTemplate[i].peGreen * 65535 / 255;
358              color.blue  = COLOR_sysPalTemplate[i].peBlue * 65535 / 255;
359
360              best.pixel = best.red = best.green = best.blue = 0;
361              for( c.pixel = 0, diff = 0x7fffffff; c.pixel < max; c.pixel += step )
362              {
363                 TSXQueryColor(display, X11DRV_PALETTE_PaletteXColormap, &c);
364                 r = (c.red - color.red)>>8; 
365                 g = (c.green - color.green)>>8; 
366                 b = (c.blue - color.blue)>>8;
367                 r = r*r + g*g + b*b;
368                 if( r < diff ) { best = c; diff = r; }
369              }
370
371              if( TSXAllocColor(display, X11DRV_PALETTE_PaletteXColormap, &best) )
372                  color.pixel = best.pixel;
373              else color.pixel = (i < NB_RESERVED_COLORS/2)? bp : wp;
374         }
375
376         sysPixel[i] = color.pixel;
377
378         TRACE("syscolor(%lx) -> pixel %i\n",
379                       *(COLORREF*)(COLOR_sysPalTemplate+i), (int)color.pixel);
380
381         /* Set EGA mapping if color in the first or last eight */
382
383         if (i < 8)
384             X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
385         else if (i >= NB_RESERVED_COLORS - 8 )
386             X11DRV_PALETTE_mapEGAPixel[i - (NB_RESERVED_COLORS-16)] = color.pixel;
387      }
388
389    /* now allocate changeable set */
390
391    if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )  
392      {
393         int c_min = 0, c_max = X11DRV_DevCaps.sizePalette, c_val;
394
395         TRACE("Dynamic colormap... \n");
396
397         /* comment this out if you want to debug palette init */
398
399         TSXGrabServer(display);
400
401         /* let's become the first client that actually follows 
402          * X guidelines and does binary search...
403          */
404
405         if((pixDynMapping = (unsigned long*)HeapAlloc(GetProcessHeap(), 0, sizeof(long)*X11DRV_DevCaps.sizePalette)) == NULL) {
406             WARN("Out of memory while building system palette.\n");
407             return FALSE;
408         }
409         while( c_max - c_min > 0 )
410           {
411              c_val = (c_max + c_min)/2 + (c_max + c_min)%2;
412
413              if( !TSXAllocColorCells(display, X11DRV_PALETTE_PaletteXColormap, False,
414                                    plane_masks, 0, pixDynMapping, c_val) )
415                  c_max = c_val - 1;
416              else
417                {
418                  TSXFreeColors(display, X11DRV_PALETTE_PaletteXColormap, pixDynMapping, c_val, 0);
419                  c_min = c_val;
420                }
421           }
422
423         if( c_min > COLOR_max - NB_RESERVED_COLORS) 
424             c_min = COLOR_max - NB_RESERVED_COLORS;
425
426         c_min = (c_min/2) + (c_min/2);          /* need even set for split palette */
427
428         if( c_min > 0 )
429           if( !TSXAllocColorCells(display, X11DRV_PALETTE_PaletteXColormap, False,
430                                 plane_masks, 0, pixDynMapping, c_min) )
431             {
432               WARN("Inexplicable failure during colorcell allocation.\n");
433               c_min = 0;
434             }
435
436         X11DRV_DevCaps.sizePalette = c_min + NB_RESERVED_COLORS;
437
438         TSXUngrabServer(display);
439
440         TRACE("adjusted size %i colorcells\n", X11DRV_DevCaps.sizePalette);
441      }
442    else if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL ) 
443         {
444           /* virtual colorspace - ToPhysical takes care of 
445            * color translations but we have to allocate full palette 
446            * to maintain compatibility
447            */
448           X11DRV_DevCaps.sizePalette = 256;
449           TRACE("Virtual colorspace - screendepth %i\n", X11DRV_GetDepth());
450         }
451    else X11DRV_DevCaps.sizePalette = NB_RESERVED_COLORS;        /* system palette only - however we can alloc a bunch
452                                          * of colors and map to them */
453
454    TRACE("Shared system palette uses %i colors.\n", X11DRV_DevCaps.sizePalette);
455
456    /* set gap to account for pixel shortage. It has to be right in the center
457     * of the system palette because otherwise raster ops get screwed. */
458
459    if( X11DRV_DevCaps.sizePalette >= 256 )
460      { COLOR_gapStart = 256; COLOR_gapEnd = -1; }
461    else
462      { COLOR_gapStart = X11DRV_DevCaps.sizePalette/2; COLOR_gapEnd = 255 - X11DRV_DevCaps.sizePalette/2; }
463
464    X11DRV_PALETTE_firstFree = ( X11DRV_DevCaps.sizePalette > NB_RESERVED_COLORS && 
465                       (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL || !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED)) ) 
466                      ? NB_RESERVED_COLORS/2 : -1;
467
468    COLOR_sysPal = (PALETTEENTRY*)HeapAlloc(GetProcessHeap(),0,sizeof(PALETTEENTRY)*256);
469    if(COLOR_sysPal == NULL) {
470        ERR("Can not allocate system palette!\n");
471        return FALSE;
472    }
473
474    /* setup system palette entry <-> pixel mappings and fill in 20 fixed entries */
475
476    if (X11DRV_GetDepth() <= 8)
477    {
478        X11DRV_PALETTE_XPixelToPalette = (int*)calloc(256, sizeof(int));
479        if(X11DRV_PALETTE_XPixelToPalette == NULL) {
480            ERR("Out of memory: XPixelToPalette!\n");
481            return FALSE;
482        }
483    }
484
485    /* for hicolor visuals PaletteToPixel mapping is used to skip
486     * RGB->pixel calculation in X11DRV_PALETTE_ToPhysical(). 
487     */
488
489    X11DRV_PALETTE_PaletteToXPixel = (int*)HeapAlloc(GetProcessHeap(),0,sizeof(int)*256);
490    if(X11DRV_PALETTE_PaletteToXPixel == NULL) {
491        ERR("Out of memory: PaletteToXPixel!\n");
492        return FALSE;
493    }
494
495    for( i = j = 0; i < 256; i++ )
496    {
497       if( i >= COLOR_gapStart && i <= COLOR_gapEnd ) 
498       {
499          X11DRV_PALETTE_PaletteToXPixel[i] = 0;
500          COLOR_sysPal[i].peFlags = 0;   /* mark as unused */
501          continue;
502       }
503
504       if( i < NB_RESERVED_COLORS/2 )
505       {
506         X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[i];
507         COLOR_sysPal[i] = COLOR_sysPalTemplate[i];
508       }
509       else if( i >= 256 - NB_RESERVED_COLORS/2 )
510       {
511         X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[(i + NB_RESERVED_COLORS) - 256]; 
512         COLOR_sysPal[i] = COLOR_sysPalTemplate[(i + NB_RESERVED_COLORS) - 256];
513       }
514       else if( pixDynMapping )
515              X11DRV_PALETTE_PaletteToXPixel[i] = pixDynMapping[j++];
516            else
517              X11DRV_PALETTE_PaletteToXPixel[i] = i;
518
519       TRACE("index %i -> pixel %i\n", i, X11DRV_PALETTE_PaletteToXPixel[i]);
520
521       if( X11DRV_PALETTE_XPixelToPalette )
522           X11DRV_PALETTE_XPixelToPalette[X11DRV_PALETTE_PaletteToXPixel[i]] = i;
523    }
524
525    if( pixDynMapping ) HeapFree(GetProcessHeap(), 0, pixDynMapping);
526
527    return TRUE;
528 }
529
530 /***********************************************************************
531  *      Colormap Initialization
532  */
533 static void X11DRV_PALETTE_FillDefaultColors(void)
534 {
535  /* initialize unused entries to what Windows uses as a color 
536   * cube - based on Greg Kreider's code. 
537   */
538
539   int i = 0, idx = 0;
540   int red, no_r, inc_r;
541   int green, no_g, inc_g; 
542   int blue, no_b, inc_b;
543   
544   if (X11DRV_DevCaps.sizePalette <= NB_RESERVED_COLORS)
545         return;
546   while (i*i*i < (X11DRV_DevCaps.sizePalette - NB_RESERVED_COLORS)) i++;
547   no_r = no_g = no_b = --i;
548   if ((no_r * (no_g+1) * no_b) < (X11DRV_DevCaps.sizePalette - NB_RESERVED_COLORS)) no_g++;
549   if ((no_r * no_g * (no_b+1)) < (X11DRV_DevCaps.sizePalette - NB_RESERVED_COLORS)) no_b++;
550   inc_r = (255 - NB_COLORCUBE_START_INDEX)/no_r;
551   inc_g = (255 - NB_COLORCUBE_START_INDEX)/no_g;
552   inc_b = (255 - NB_COLORCUBE_START_INDEX)/no_b;
553
554   idx = X11DRV_PALETTE_firstFree;
555
556   if( idx != -1 )
557     for (blue = NB_COLORCUBE_START_INDEX; blue < 256 && idx; blue += inc_b )
558      for (green = NB_COLORCUBE_START_INDEX; green < 256 && idx; green += inc_g )
559       for (red = NB_COLORCUBE_START_INDEX; red < 256 && idx; red += inc_r )
560       {
561          /* weird but true */
562
563          if( red == NB_COLORCUBE_START_INDEX && green == red && blue == green ) continue;
564
565          COLOR_sysPal[idx].peRed = red;
566          COLOR_sysPal[idx].peGreen = green;
567          COLOR_sysPal[idx].peBlue = blue;
568          
569          /* set X color */
570
571          if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
572          {
573             if (X11DRV_PALETTE_Redmax != 255) no_r = (red * X11DRV_PALETTE_Redmax) / 255;
574             if (X11DRV_PALETTE_Greenmax != 255) no_g = (green * X11DRV_PALETTE_Greenmax) / 255;
575             if (X11DRV_PALETTE_Bluemax != 255) no_b = (blue * X11DRV_PALETTE_Bluemax) / 255;
576
577             X11DRV_PALETTE_PaletteToXPixel[idx] = (no_r << X11DRV_PALETTE_Redshift) | (no_g << X11DRV_PALETTE_Greenshift) | (no_b << X11DRV_PALETTE_Blueshift);
578          }
579          else if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
580          {
581            XColor color;
582            color.pixel = (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[idx] : idx;
583            color.red = COLOR_sysPal[idx].peRed << 8;
584            color.green = COLOR_sysPal[idx].peGreen << 8;
585            color.blue =  COLOR_sysPal[idx].peBlue << 8;
586            color.flags = DoRed | DoGreen | DoBlue;
587            TSXStoreColor(display, X11DRV_PALETTE_PaletteXColormap, &color);
588          }
589          idx = X11DRV_PALETTE_freeList[idx];
590       }
591
592   /* try to fill some entries in the "gap" with
593    * what's already in the colormap - they will be
594    * mappable to but not changeable. */
595
596   if( COLOR_gapStart < COLOR_gapEnd && X11DRV_PALETTE_XPixelToPalette )
597   {
598     XColor      xc;
599     int         r, g, b, max;
600
601     max = COLOR_max - (256 - (COLOR_gapEnd - COLOR_gapStart));
602     for ( i = 0, idx = COLOR_gapStart; i < 256 && idx <= COLOR_gapEnd; i++ )
603       if( X11DRV_PALETTE_XPixelToPalette[i] == 0 )
604         {
605           xc.pixel = i;
606
607           TSXQueryColor(display, X11DRV_PALETTE_PaletteXColormap, &xc);
608           r = xc.red>>8; g = xc.green>>8; b = xc.blue>>8;
609
610           if( xc.pixel < 256 && X11DRV_PALETTE_CheckSysColor(RGB(r, g, b)) &&
611               TSXAllocColor(display, X11DRV_PALETTE_PaletteXColormap, &xc) )
612           {
613              X11DRV_PALETTE_XPixelToPalette[xc.pixel] = idx;
614              X11DRV_PALETTE_PaletteToXPixel[idx] = xc.pixel;
615            *(COLORREF*)(COLOR_sysPal + idx) = RGB(r, g, b);
616              COLOR_sysPal[idx++].peFlags |= PC_SYS_USED;
617              if( --max <= 0 ) break;
618           }
619         }
620     COLOR_gapFilled = idx - COLOR_gapStart;    
621   }
622 }
623
624
625 /***********************************************************************
626  *           X11DRV_PALETTE_ToLogical
627  *
628  * Return RGB color for given X pixel.
629  */
630 COLORREF X11DRV_PALETTE_ToLogical(int pixel)
631 {
632     XColor color;
633
634 #if 0
635     /* truecolor visual */
636
637     if (X11DRV_GetDepth() >= 24) return pixel;
638 #endif
639
640     /* check for hicolor visuals first */
641
642     if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED && !X11DRV_PALETTE_Graymax )
643     {
644          color.red = (pixel >> X11DRV_PALETTE_Redshift) & X11DRV_PALETTE_Redmax;
645          color.green = (pixel >> X11DRV_PALETTE_Greenshift) & X11DRV_PALETTE_Greenmax;
646          color.blue = (pixel >> X11DRV_PALETTE_Blueshift) & X11DRV_PALETTE_Bluemax;
647          return RGB(MulDiv(color.red, 255, X11DRV_PALETTE_Redmax),
648                     MulDiv(color.green, 255, X11DRV_PALETTE_Greenmax),
649                     MulDiv(color.blue, 255, X11DRV_PALETTE_Bluemax));
650     }
651
652     /* check if we can bypass X */
653
654     if ((X11DRV_GetDepth() <= 8) && (pixel < 256) && 
655        !(X11DRV_PALETTE_PaletteFlags & (X11DRV_PALETTE_VIRTUAL | X11DRV_PALETTE_FIXED)) )
656          return  ( *(COLORREF*)(COLOR_sysPal + 
657                    ((X11DRV_PALETTE_XPixelToPalette)?X11DRV_PALETTE_XPixelToPalette[pixel]:pixel)) ) & 0x00ffffff;
658
659     color.pixel = pixel;
660     TSXQueryColor(display, X11DRV_PALETTE_PaletteXColormap, &color);
661     return RGB(color.red >> 8, color.green >> 8, color.blue >> 8);
662 }
663
664 /***********************************************************************
665  *           X11DRV_PALETTE_ToPhysical
666  *
667  * Return the physical color closest to 'color'.
668  */
669 int X11DRV_PALETTE_ToPhysical( DC *dc, COLORREF color )
670 {
671     WORD                 index = 0;
672     HPALETTE16           hPal = (dc)? dc->w.hPalette: GetStockObject(DEFAULT_PALETTE);
673     unsigned char        spec_type = color >> 24;
674     PALETTEOBJ*          palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hPal, PALETTE_MAGIC );
675
676     /* palPtr can be NULL when DC is being destroyed */
677     if( !palPtr ) return 0;
678
679     if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED )
680     {
681         /* there is no colormap limitation; we are going to have to compute
682          * the pixel value from the visual information stored earlier 
683          */
684
685         unsigned        long red, green, blue;
686         unsigned        idx = 0;
687
688         switch(spec_type)
689         {
690           case 1: /* PALETTEINDEX */
691
692             if( (idx = color & 0xffff) >= palPtr->logpalette.palNumEntries)
693             {
694                 WARN("RGB(%lx) : idx %d is out of bounds, assuming black\n", color, idx);
695                 GDI_ReleaseObj( hPal );
696                 return 0;
697             }
698
699             if( palPtr->mapping ) 
700             {
701                 int ret = palPtr->mapping[idx];
702                 GDI_ReleaseObj( hPal );
703                 return ret;
704             }
705             color = *(COLORREF*)(palPtr->logpalette.palPalEntry + idx);
706             break;
707
708           default:
709             color &= 0xffffff;
710             /* fall through to RGB */
711
712           case 0: /* RGB */
713             if( dc && (dc->w.bitsPerPixel == 1) )
714             {
715                 GDI_ReleaseObj( hPal );
716                 return (((color >> 16) & 0xff) +
717                         ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
718             }
719
720         }
721
722         red = GetRValue(color); green = GetGValue(color); blue = GetBValue(color);
723
724         if (X11DRV_PALETTE_Graymax)
725         {
726             /* grayscale only; return scaled value */
727             GDI_ReleaseObj( hPal );
728             return ( (red * 30 + green * 69 + blue * 11) * X11DRV_PALETTE_Graymax) / 25500;
729         }
730         else
731         {
732             /* scale each individually and construct the TrueColor pixel value */
733             if (X11DRV_PALETTE_Redmax != 255)
734                 red = MulDiv(red, X11DRV_PALETTE_Redmax, 255);
735             if (X11DRV_PALETTE_Greenmax != 255)
736                 green = MulDiv(green, X11DRV_PALETTE_Greenmax, 255);
737             if (X11DRV_PALETTE_Bluemax != 255)
738                 blue = MulDiv(blue, X11DRV_PALETTE_Bluemax, 255);
739
740             GDI_ReleaseObj( hPal );
741             return (red << X11DRV_PALETTE_Redshift) | (green << X11DRV_PALETTE_Greenshift) | (blue << X11DRV_PALETTE_Blueshift);
742         }
743     }
744     else 
745     {
746
747         if( !palPtr->mapping ) 
748             WARN("Palette %04x is not realized\n", dc->w.hPalette);
749
750         switch(spec_type)       /* we have to peruse DC and system palette */
751         {
752             default:
753                 color &= 0xffffff;
754                 /* fall through to RGB */
755
756             case 0:  /* RGB */
757                 if( dc && (dc->w.bitsPerPixel == 1) )
758                 {
759                     GDI_ReleaseObj( hPal );
760                     return (((color >> 16) & 0xff) +
761                             ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
762                 }
763
764                 index = COLOR_PaletteLookupPixel( COLOR_sysPal, 256, 
765                                                   X11DRV_PALETTE_PaletteToXPixel, color, FALSE);
766
767                 /* TRACE(palette,"RGB(%lx) -> pixel %i\n", color, index);
768                  */
769                 break;
770             case 1:  /* PALETTEINDEX */
771                 index = color & 0xffff;
772
773                 if( index >= palPtr->logpalette.palNumEntries )
774                     WARN("RGB(%lx) : index %i is out of bounds\n", color, index); 
775                 else if( palPtr->mapping ) index = palPtr->mapping[index];
776
777                 /*  TRACE(palette,"PALETTEINDEX(%04x) -> pixel %i\n", (WORD)color, index);
778                  */
779                 break;
780             case 2:  /* PALETTERGB */
781                 index = COLOR_PaletteLookupPixel( palPtr->logpalette.palPalEntry, 
782                                              palPtr->logpalette.palNumEntries,
783                                              palPtr->mapping, color, FALSE);
784                 /* TRACE(palette,"PALETTERGB(%lx) -> pixel %i\n", color, index);
785                  */
786                 break;
787         }
788     }
789
790     GDI_ReleaseObj( hPal );
791     return index;
792 }
793
794 /***********************************************************************
795  *           X11DRV_PALETTE_LookupSystemXPixel
796  */
797 static int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col)
798 {
799  int            i, best = 0, diff = 0x7fffffff;
800  int            size = X11DRV_DevCaps.sizePalette;
801  int            r,g,b;
802
803  for( i = 0; i < size && diff ; i++ )
804     {
805       if( i == NB_RESERVED_COLORS/2 )
806       {
807         int newi = size - NB_RESERVED_COLORS/2;
808         if (newi>i) i=newi;
809       }
810
811       r = COLOR_sysPal[i].peRed - GetRValue(col);
812       g = COLOR_sysPal[i].peGreen - GetGValue(col);
813       b = COLOR_sysPal[i].peBlue - GetBValue(col);
814
815       r = r*r + g*g + b*b;
816
817       if( r < diff ) { best = i; diff = r; }
818     }
819  
820  return (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[best] : best;
821 }
822
823 /***********************************************************************
824  *           X11DRV_PALETTE_FormatSystemPalette
825  */
826 static void X11DRV_PALETTE_FormatSystemPalette(void)
827 {
828  /* Build free list so we'd have an easy way to find
829   * out if there are any available colorcells. 
830   */
831
832   int i, j = X11DRV_PALETTE_firstFree = NB_RESERVED_COLORS/2;
833
834   COLOR_sysPal[j].peFlags = 0;
835   for( i = NB_RESERVED_COLORS/2 + 1 ; i < 256 - NB_RESERVED_COLORS/2 ; i++ )
836     if( i < COLOR_gapStart || i > COLOR_gapEnd )
837       {
838         COLOR_sysPal[i].peFlags = 0;  /* unused tag */
839         X11DRV_PALETTE_freeList[j] = i;   /* next */
840         j = i;
841       }
842   X11DRV_PALETTE_freeList[j] = 0;
843 }
844
845 /***********************************************************************
846  *           X11DRV_PALETTE_CheckSysColor
847  */
848 static BOOL X11DRV_PALETTE_CheckSysColor(COLORREF c)
849 {
850   int i;
851   for( i = 0; i < NB_RESERVED_COLORS; i++ )
852        if( c == (*(COLORREF*)(COLOR_sysPalTemplate + i) & 0x00ffffff) )
853            return 0;
854   return 1;
855 }
856
857 /***********************************************************************
858  *           X11DRV_PALETTE_SetMapping
859  *
860  * Set the color-mapping table for selected palette. 
861  * Return number of entries which mapping has changed.
862  */
863 int X11DRV_PALETTE_SetMapping( PALETTEOBJ* palPtr, UINT uStart, UINT uNum, BOOL mapOnly )
864 {
865     char flag;
866     int  prevMapping = (palPtr->mapping) ? 1 : 0;
867     int  index, iRemapped = 0;
868     int* mapping;
869
870     /* reset dynamic system palette entries */
871
872     if( !mapOnly && X11DRV_PALETTE_firstFree != -1)
873          X11DRV_PALETTE_FormatSystemPalette();
874
875     /* initialize palette mapping table */
876  
877     mapping = HeapReAlloc( GetProcessHeap(), 0, palPtr->mapping,
878                            sizeof(int)*palPtr->logpalette.palNumEntries);
879     if(mapping == NULL) {
880         ERR("Can not allocate new mapping -- memory exausted!");
881         return 0;
882     }
883     palPtr->mapping = mapping;
884
885     for( uNum += uStart; uStart < uNum; uStart++ )
886     {
887         index = -1;
888         flag = PC_SYS_USED;
889
890         switch( palPtr->logpalette.palPalEntry[uStart].peFlags & 0x07 )
891         {
892         case PC_EXPLICIT:   /* palette entries are indices into system palette */
893             index = *(WORD*)(palPtr->logpalette.palPalEntry + uStart);
894             if( index > 255 || (index >= COLOR_gapStart && index <= COLOR_gapEnd) ) 
895             {
896                 WARN("PC_EXPLICIT: idx %d out of system palette, assuming black.\n", index); 
897                 index = 0;
898             }
899             break;
900
901         case PC_RESERVED:   /* forbid future mappings to this entry */
902             flag |= PC_SYS_RESERVED;
903
904             /* fall through */
905         default:            /* try to collapse identical colors */
906             index = COLOR_PaletteLookupExactIndex(COLOR_sysPal, 256,  
907                              *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
908             /* fall through */
909         case PC_NOCOLLAPSE: 
910             if( index < 0 )
911             {
912                 if( X11DRV_PALETTE_firstFree > 0 && !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
913                 {
914                     XColor color;
915                     index = X11DRV_PALETTE_firstFree;  /* ought to be available */
916                     X11DRV_PALETTE_firstFree = X11DRV_PALETTE_freeList[index];
917
918                     color.pixel = (X11DRV_PALETTE_PaletteToXPixel) ? X11DRV_PALETTE_PaletteToXPixel[index] : index;
919                     color.red = palPtr->logpalette.palPalEntry[uStart].peRed << 8;
920                     color.green = palPtr->logpalette.palPalEntry[uStart].peGreen << 8;
921                     color.blue = palPtr->logpalette.palPalEntry[uStart].peBlue << 8;
922                     color.flags = DoRed | DoGreen | DoBlue;
923                     TSXStoreColor(display, X11DRV_PALETTE_PaletteXColormap, &color);
924
925                     COLOR_sysPal[index] = palPtr->logpalette.palPalEntry[uStart];
926                     COLOR_sysPal[index].peFlags = flag;
927                     X11DRV_PALETTE_freeList[index] = 0;
928
929                     if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
930                     break;
931                 }
932                 else if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL ) 
933                 {
934                     index = X11DRV_PALETTE_ToPhysical( NULL, 0x00ffffff &
935                              *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
936                     break;     
937                 }
938
939                 /* we have to map to existing entry in the system palette */
940
941                 index = COLOR_PaletteLookupPixel(COLOR_sysPal, 256, NULL, 
942                        *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), TRUE);
943             }
944             palPtr->logpalette.palPalEntry[uStart].peFlags |= PC_SYS_USED;
945
946             if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
947             break;
948         }
949
950         if( !prevMapping || palPtr->mapping[uStart] != index ) iRemapped++;
951         palPtr->mapping[uStart] = index;
952
953         TRACE("entry %i (%lx) -> pixel %i\n", uStart, 
954                                 *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), index);
955         
956     }
957     return iRemapped;
958 }
959
960 /***********************************************************************
961  *           X11DRV_PALETTE_UpdateMapping
962  *
963  * Update the color-mapping table for selected palette. 
964  * Return number of entries which mapping has changed.
965  */
966 int X11DRV_PALETTE_UpdateMapping(PALETTEOBJ *palPtr)
967 {
968   int i, index, realized = 0;    
969   
970   if (!X11DRV_DevCaps.sizePalette)
971     return 0;
972
973   for( i = 0; i < 20; i++ )
974     {
975       index = X11DRV_PALETTE_LookupSystemXPixel(*(COLORREF*)(palPtr->logpalette.palPalEntry + i));
976       
977       /* mapping is allocated in COLOR_InitPalette() */
978       
979       if( index != palPtr->mapping[i] ) { palPtr->mapping[i]=index; realized++; }
980     }
981   
982     return realized;
983 }
984
985 /**************************************************************************
986  *              X11DRV_PALETTE_IsDark
987  */
988 BOOL X11DRV_PALETTE_IsDark(int pixel)
989 {
990   COLORREF col = X11DRV_PALETTE_ToLogical(pixel);
991   return (GetRValue(col) + GetGValue(col) + GetBValue(col)) <= 0x180;
992 }
993