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