palette.c 42.3 KB
Newer Older
1
/*
2 3 4 5
 * X11DRV OEM bitmap objects
 *
 * Copyright 1994, 1995 Alexandre Julliard
 *
6 7 8 9 10 11 12 13 14 15 16 17 18
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 20 21 22 23 24 25 26 27 28
 */

#include "config.h"

#include <stdlib.h>
#include <string.h>

#include "gdi.h"
#include "palette.h"
#include "windef.h"
29
#include "winreg.h"
30
#include "x11drv.h"
31
#include "wine/debug.h"
32

33
WINE_DEFAULT_DEBUG_CHANNEL(palette);
34

35 36 37
/* Palette indexed mode:
 *	logical palette -> mapping -> pixel
 *
38 39
 *
 * Windows needs contiguous color space ( from 0 to n ) but
40
 * it is possible only with the private colormap. Otherwise we
41
 * have to map DC palette indices to real pixel values. With
42
 * private colormaps it boils down to the identity mapping. The
43 44 45
 * other special case is when we have a fixed color visual with
 * the screendepth > 8 - we abandon palette mappings altogether
 * because pixel values can be calculated without X server
46 47 48 49 50 51
 * assistance.
 *
 * Windows palette manager is described in the
 * http://premium.microsoft.com/msdn/library/techart/f30/f34/f40/d4d/sa942.htm
 */

52
static PALETTEENTRY *COLOR_sysPal; /* current system palette */
53

54 55 56 57
static int COLOR_gapStart = 256;
static int COLOR_gapEnd = -1;
static int COLOR_gapFilled = 0;
static int COLOR_max = 256;
58 59 60 61

Colormap X11DRV_PALETTE_PaletteXColormap = 0;
UINT16   X11DRV_PALETTE_PaletteFlags     = 0;

62 63 64 65 66 67 68 69 70 71 72 73 74 75
typedef struct {
    int shift;
    int scale;
    int max;
} ColorShifts;

/* initialize to zero to handle abortive X11DRV_PALETTE_VIRTUAL visuals */
static ColorShifts X11DRV_PALETTE_PRed   = {0,0,0};
static ColorShifts X11DRV_PALETTE_LRed   = {0,0,0};
static ColorShifts X11DRV_PALETTE_PGreen = {0,0,0};
static ColorShifts X11DRV_PALETTE_LGreen = {0,0,0};
static ColorShifts X11DRV_PALETTE_PBlue  = {0,0,0};
static ColorShifts X11DRV_PALETTE_LBlue  = {0,0,0};
static int X11DRV_PALETTE_Graymax        = 0;
76

77 78
static int palette_size;

79
/* First free dynamic color cell, 0 = full palette, -1 = fixed palette */
80
static int           X11DRV_PALETTE_firstFree = 0;
81 82 83 84 85 86 87 88 89 90 91
static unsigned char X11DRV_PALETTE_freeList[256];

/**********************************************************************/

   /* Map an EGA index (0..15) to a pixel value in the system color space.  */

int X11DRV_PALETTE_mapEGAPixel[16];

/**********************************************************************/

#define NB_COLORCUBE_START_INDEX	63
92
#define NB_PALETTE_EMPTY_VALUE          -1
93 94 95 96 97 98 99 100 101

/* Maps entry in the system palette to X pixel value */
int *X11DRV_PALETTE_PaletteToXPixel = NULL;

/* Maps pixel to the entry in the system palette */
int *X11DRV_PALETTE_XPixelToPalette = NULL;

/**********************************************************************/

102 103
static BOOL X11DRV_PALETTE_BuildPrivateMap( const PALETTEENTRY *sys_pal_template );
static BOOL X11DRV_PALETTE_BuildSharedMap( const PALETTEENTRY *sys_pal_template );
104
static void X11DRV_PALETTE_ComputeShifts(unsigned long maskbits, ColorShifts *physical, ColorShifts *to_logical);
105
static void X11DRV_PALETTE_FillDefaultColors( const PALETTEENTRY *sys_pal_template );
106
static void X11DRV_PALETTE_FormatSystemPalette(void);
107
static BOOL X11DRV_PALETTE_CheckSysColor( const PALETTEENTRY *sys_pal_template, COLORREF c);
108
static int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col);
109

110

111 112 113 114 115
/***********************************************************************
 *           COLOR_Init
 *
 * Initialize color management.
 */
116
int X11DRV_PALETTE_Init(void)
117 118 119
{
    int	mask, white, black;
    int monoPlane;
120
    PALETTEENTRY sys_pal_template[NB_RESERVED_COLORS];
121

122
    TRACE("initializing palette manager...\n");
123

124 125
    white = WhitePixel( gdi_display, DefaultScreen(gdi_display) );
    black = BlackPixel( gdi_display, DefaultScreen(gdi_display) );
126 127 128 129
    monoPlane = 1;
    for( mask = 1; !((white & mask)^(black & mask)); mask <<= 1 )
	 monoPlane++;
    X11DRV_PALETTE_PaletteFlags = (white & mask) ? X11DRV_PALETTE_WHITESET : 0;
130
    palette_size = visual->map_entries;
131 132 133 134 135 136 137

    switch(visual->class)
    {
    case DirectColor:
	X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_VIRTUAL;
    case GrayScale:
    case PseudoColor:
138 139 140 141 142 143 144 145
    {
	HKEY hkey;
	BOOL private_color_map = FALSE;
	if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", &hkey))
	{
	    char buffer[20];
	    DWORD type, count = sizeof(buffer);
	    if(!RegQueryValueExA(hkey, "PrivateColorMap", 0, &type, buffer, &count))
146 147 148 149
            {
                char ch = buffer[0];
                private_color_map = (ch == 'y' || ch == 'Y' || ch == 't' || ch == 'T' || ch == '1');
            }
150 151 152
	    RegCloseKey(hkey);
	}

153
        wine_tsx11_lock();
154
	if (private_color_map)
155 156 157
	{
	    XSetWindowAttributes win_attr;

158 159
	    X11DRV_PALETTE_PaletteXColormap = XCreateColormap( gdi_display, root_window,
                                                               visual, AllocAll );
160 161 162 163 164
	    if (X11DRV_PALETTE_PaletteXColormap)
	    {
	        X11DRV_PALETTE_PaletteFlags |= (X11DRV_PALETTE_PRIVATE | X11DRV_PALETTE_WHITESET);

		monoPlane = 1;
165
		for( white = palette_size - 1; !(white & 1); white >>= 1 )
166 167
		     monoPlane++;

168
	        if( root_window != DefaultRootWindow(gdi_display) )
169 170
	        {
		    win_attr.colormap = X11DRV_PALETTE_PaletteXColormap;
171
		    XChangeWindowAttributes( gdi_display, root_window, CWColormap, &win_attr );
172 173 174 175
		}
		break;
	    }
	}
176 177 178
        X11DRV_PALETTE_PaletteXColormap = XCreateColormap(gdi_display, root_window,
                                                          visual, AllocNone);
        wine_tsx11_unlock();
179
        break;
180
    }
181 182

    case StaticGray:
183 184 185
        wine_tsx11_lock();
        X11DRV_PALETTE_PaletteXColormap = XCreateColormap(gdi_display, root_window,
                                                          visual, AllocNone);
186
	X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_FIXED;
187
        X11DRV_PALETTE_Graymax = (1 << screen_depth)-1;
188
        wine_tsx11_unlock();
189 190 191 192 193 194 195 196 197
        break;

    case TrueColor:
	X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_VIRTUAL;
    case StaticColor: {
    	int *depths,nrofdepths;
	/* FIXME: hack to detect XFree32 XF_VGA16 ... We just have
	 * depths 1 and 4
	 */
198 199
        wine_tsx11_lock();
        depths = XListDepths(gdi_display,DefaultScreen(gdi_display),&nrofdepths);
200 201
	if ((nrofdepths==2) && ((depths[0]==4) || depths[1]==4)) {
	    monoPlane = 1;
202
	    for( white = palette_size - 1; !(white & 1); white >>= 1 )
203 204
	        monoPlane++;
    	    X11DRV_PALETTE_PaletteFlags = (white & mask) ? X11DRV_PALETTE_WHITESET : 0;
205 206
            X11DRV_PALETTE_PaletteXColormap = XCreateColormap(gdi_display, root_window,
                                                              visual, AllocNone);
207
	}
208 209 210 211 212 213 214 215 216 217 218
        else
        {
            X11DRV_PALETTE_PaletteXColormap = XCreateColormap(gdi_display, root_window,
                                                              visual, AllocNone);
            X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_FIXED;
            X11DRV_PALETTE_ComputeShifts(visual->red_mask, &X11DRV_PALETTE_PRed, &X11DRV_PALETTE_LRed);
            X11DRV_PALETTE_ComputeShifts(visual->green_mask, &X11DRV_PALETTE_PGreen, &X11DRV_PALETTE_LGreen);
            X11DRV_PALETTE_ComputeShifts(visual->blue_mask, &X11DRV_PALETTE_PBlue, &X11DRV_PALETTE_LBlue);
        }
        XFree(depths);
        wine_tsx11_unlock();
219
        break;
220
      }
221 222
    }

223
    TRACE(" visual class %i (%i)\n",  visual->class, monoPlane);
224

225 226
    GetPaletteEntries( GetStockObject(DEFAULT_PALETTE), 0, NB_RESERVED_COLORS, sys_pal_template );

227 228 229 230
    if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
    {
        palette_size = 0;
    }
231
    else
232 233 234 235 236
    {
        if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
            X11DRV_PALETTE_BuildPrivateMap( sys_pal_template );
        else
            X11DRV_PALETTE_BuildSharedMap( sys_pal_template );
237

238
        /* Build free list */
239

240 241
        if( X11DRV_PALETTE_firstFree != -1 )
            X11DRV_PALETTE_FormatSystemPalette();
242

243
        X11DRV_PALETTE_FillDefaultColors( sys_pal_template );
244
        palette_size = visual->map_entries;
245
    }
246

247
    return palette_size;
248 249 250 251 252 253 254 255 256 257
}

/***********************************************************************
 *           X11DRV_PALETTE_Cleanup
 *
 * Free external colors we grabbed in the FillDefaultPalette()
 */
void X11DRV_PALETTE_Cleanup(void)
{
  if( COLOR_gapFilled )
258 259 260
  {
      wine_tsx11_lock();
      XFreeColors(gdi_display, X11DRV_PALETTE_PaletteXColormap,
261
		  (unsigned long*)(X11DRV_PALETTE_PaletteToXPixel + COLOR_gapStart),
262
		  COLOR_gapFilled, 0);
263 264
      wine_tsx11_unlock();
  }
265 266 267 268 269 270 271
}

/***********************************************************************
 *		X11DRV_PALETTE_ComputeShifts
 *
 * Calculate conversion parameters for direct mapped visuals
 */
272
static void X11DRV_PALETTE_ComputeShifts(unsigned long maskbits, ColorShifts *physical, ColorShifts *to_logical)
273 274 275 276 277
{
    int i;

    if (maskbits==0)
    {
278 279 280 281 282 283
        physical->shift=0;
        physical->scale=0;
        physical->max=0;
        to_logical->shift=0;
        to_logical->scale=0;
        to_logical->max=0;
284 285 286 287 288 289
        return;
    }

    for(i=0;!(maskbits&1);i++)
        maskbits >>= 1;

290 291
    physical->shift = i;
    physical->max = maskbits;
292 293 294

    for(i=0;maskbits!=0;i++)
        maskbits >>= 1;
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    physical->scale = i;

    if (physical->scale>8)
    {
        /* On FreeBSD, VNC's default 32bpp mode is bgrabb (ffc00000,3ff800,7ff)!
         * So we adjust the shifts to also normalize the color fields to
         * the Win32 standard of 8 bits per color.
         */
        to_logical->shift=physical->shift+(physical->scale-8);
        to_logical->scale=8;
        to_logical->max=0xff;
    } else {
        to_logical->shift=physical->shift;
        to_logical->scale=physical->scale;
        to_logical->max=physical->max;
    }
311 312 313 314 315 316 317
}

/***********************************************************************
 *           X11DRV_PALETTE_BuildPrivateMap
 *
 * Allocate colorcells and initialize mapping tables.
 */
318
static BOOL X11DRV_PALETTE_BuildPrivateMap( const PALETTEENTRY *sys_pal_template )
319 320 321 322
{
    /* Private colormap - identity mapping */

    XColor color;
323
    int i;
324

325
    if((COLOR_sysPal = (PALETTEENTRY*)HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY)*palette_size)) == NULL) {
326 327 328
        WARN("Can not allocate system palette\n");
        return FALSE;
    }
329

330
    TRACE("Building private map - %i palette entries\n", palette_size);
331

332
      /* Allocate system palette colors */
333

334
    wine_tsx11_lock();
335
    for( i=0; i < palette_size; i++ )
336 337 338
    {
       if( i < NB_RESERVED_COLORS/2 )
       {
339 340 341 342 343
         color.red   = sys_pal_template[i].peRed * 65535 / 255;
         color.green = sys_pal_template[i].peGreen * 65535 / 255;
         color.blue  = sys_pal_template[i].peBlue * 65535 / 255;
	 COLOR_sysPal[i] = sys_pal_template[i];
         COLOR_sysPal[i].peFlags |= PC_SYS_USED;
344
       }
345
       else if( i >= palette_size - NB_RESERVED_COLORS/2 )
346
       {
347
	 int j = NB_RESERVED_COLORS + i - palette_size;
348 349 350 351 352
         color.red   = sys_pal_template[j].peRed * 65535 / 255;
         color.green = sys_pal_template[j].peGreen * 65535 / 255;
         color.blue  = sys_pal_template[j].peBlue * 65535 / 255;
	 COLOR_sysPal[i] = sys_pal_template[j];
         COLOR_sysPal[i].peFlags |= PC_SYS_USED;
353 354 355 356
       }

       color.flags = DoRed | DoGreen | DoBlue;
       color.pixel = i;
357
       XStoreColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &color);
358 359 360 361 362

       /* Set EGA mapping if color is from the first or last eight */

       if (i < 8)
           X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
363 364
       else if (i >= palette_size - 8 )
           X11DRV_PALETTE_mapEGAPixel[i - (palette_size - 16)] = color.pixel;
365
    }
366
    wine_tsx11_unlock();
367 368 369 370 371

    X11DRV_PALETTE_XPixelToPalette = X11DRV_PALETTE_PaletteToXPixel = NULL;

    COLOR_gapStart = 256; COLOR_gapEnd = -1;

372
    X11DRV_PALETTE_firstFree = (palette_size > NB_RESERVED_COLORS)?NB_RESERVED_COLORS/2 : -1;
373 374 375 376 377 378 379 380 381

    return FALSE;
}

/***********************************************************************
 *           X11DRV_PALETTE_BuildSharedMap
 *
 * Allocate colorcells and initialize mapping tables.
 */
382
static BOOL X11DRV_PALETTE_BuildSharedMap( const PALETTEENTRY *sys_pal_template )
383 384 385 386 387 388 389 390
{
   XColor		color;
   unsigned long        sysPixel[NB_RESERVED_COLORS];
   unsigned long*	pixDynMapping = NULL;
   unsigned long	plane_masks[1];
   int			i, j, warn = 0;
   int			diff, r, g, b, max = 256, bp = 0, wp = 1;
   int			step = 1;
391 392 393
   int			defaultCM_max_copy;
   Colormap		defaultCM;
   XColor		defaultColors[256];
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
   HKEY hkey;

   defaultCM_max_copy = 128;
   COLOR_max = 256;

   if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", &hkey))
   {
	char buffer[20];
	DWORD type, count;

	count = sizeof(buffer);
	if(!RegQueryValueExA(hkey, "CopyDefaultColors", 0, &type, buffer, &count))
	    defaultCM_max_copy = atoi(buffer);

	count = sizeof(buffer);
	if(!RegQueryValueExA(hkey, "AllocSystemColors", 0, &type, buffer, &count))
	    COLOR_max = atoi(buffer);
411

412 413
	RegCloseKey(hkey);
   }
414

415
   /* Copy the first bunch of colors out of the default colormap to prevent
416 417
    * colormap flashing as much as possible.  We're likely to get the most
    * important Window Manager colors, etc in the first 128 colors */
418
   defaultCM = DefaultColormap( gdi_display, DefaultScreen(gdi_display) );
419

420 421
   for (i = 0; i < defaultCM_max_copy; i++)
       defaultColors[i].pixel = (long) i;
422 423
   wine_tsx11_lock();
   XQueryColors(gdi_display, defaultCM, &defaultColors[0], defaultCM_max_copy);
424
   for (i = 0; i < defaultCM_max_copy; i++)
425
       XAllocColor( gdi_display, X11DRV_PALETTE_PaletteXColormap, &defaultColors[i] );
426

427 428
   if (COLOR_max > 256) COLOR_max = 256;
   else if (COLOR_max < 20) COLOR_max = 20;
429
   TRACE("%d colors configured.\n", COLOR_max);
430

431
   TRACE("Building shared map - %i palette entries\n", palette_size);
432 433 434 435

   /* Be nice and allocate system colors as read-only */

   for( i = 0; i < NB_RESERVED_COLORS; i++ )
436
     {
437 438 439
        color.red   = sys_pal_template[i].peRed * 65535 / 255;
        color.green = sys_pal_template[i].peGreen * 65535 / 255;
        color.blue  = sys_pal_template[i].peBlue * 65535 / 255;
440 441
        color.flags = DoRed | DoGreen | DoBlue;

442
        if (!XAllocColor( gdi_display, X11DRV_PALETTE_PaletteXColormap, &color ))
443
        {
444
	     XColor	best, c;
445 446

             if( !warn++ )
447
	     {
448
		  WARN("Not enough colors for the full system palette.\n");
449

450 451
	          bp = BlackPixel(gdi_display, DefaultScreen(gdi_display));
	          wp = WhitePixel(gdi_display, DefaultScreen(gdi_display));
452

453
	          max = (0xffffffff)>>(32 - screen_depth);
454
	          if( max > 256 )
455 456 457 458 459 460 461 462 463
	          {
	  	      step = max/256;
		      max = 256;
	          }
	     }

	     /* reinit color (XAllocColor() may change it)
	      * and map to the best shared colorcell */

464 465 466
             color.red   = sys_pal_template[i].peRed * 65535 / 255;
             color.green = sys_pal_template[i].peGreen * 65535 / 255;
             color.blue  = sys_pal_template[i].peBlue * 65535 / 255;
467 468 469 470

	     best.pixel = best.red = best.green = best.blue = 0;
	     for( c.pixel = 0, diff = 0x7fffffff; c.pixel < max; c.pixel += step )
	     {
471
		XQueryColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &c);
472 473
		r = (c.red - color.red)>>8;
		g = (c.green - color.green)>>8;
474 475 476 477 478
		b = (c.blue - color.blue)>>8;
		r = r*r + g*g + b*b;
		if( r < diff ) { best = c; diff = r; }
	     }

479
	     if( XAllocColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &best) )
480 481 482 483 484 485
		 color.pixel = best.pixel;
	     else color.pixel = (i < NB_RESERVED_COLORS/2)? bp : wp;
        }

        sysPixel[i] = color.pixel;

486
        TRACE("syscolor(%lx) -> pixel %i\n",
487
		      *(COLORREF*)(sys_pal_template+i), (int)color.pixel);
488 489 490 491 492 493 494 495

        /* Set EGA mapping if color in the first or last eight */

        if (i < 8)
            X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
        else if (i >= NB_RESERVED_COLORS - 8 )
            X11DRV_PALETTE_mapEGAPixel[i - (NB_RESERVED_COLORS-16)] = color.pixel;
     }
496
   wine_tsx11_unlock();
497 498 499

   /* now allocate changeable set */

500
   if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
501
     {
502
	int c_min = 0, c_max = palette_size, c_val;
503

504
	TRACE("Dynamic colormap... \n");
505

506
	/* let's become the first client that actually follows
507 508 509
	 * X guidelines and does binary search...
	 */

510
	if((pixDynMapping = (unsigned long*)HeapAlloc(GetProcessHeap(), 0, sizeof(long)*palette_size)) == NULL) {
511 512 513
	    WARN("Out of memory while building system palette.\n");
	    return FALSE;
        }
514

515
        wine_tsx11_lock();
516
	/* comment this out if you want to debug palette init */
517
	XGrabServer(gdi_display);
518

519 520 521 522
        while( c_max - c_min > 0 )
          {
             c_val = (c_max + c_min)/2 + (c_max + c_min)%2;

523
             if( !XAllocColorCells(gdi_display, X11DRV_PALETTE_PaletteXColormap, False,
524 525 526 527
                                   plane_masks, 0, pixDynMapping, c_val) )
                 c_max = c_val - 1;
             else
               {
528
                 XFreeColors(gdi_display, X11DRV_PALETTE_PaletteXColormap, pixDynMapping, c_val, 0);
529 530 531 532
                 c_min = c_val;
               }
          }

533
	if( c_min > COLOR_max - NB_RESERVED_COLORS)
534 535 536 537 538
	    c_min = COLOR_max - NB_RESERVED_COLORS;

	c_min = (c_min/2) + (c_min/2);		/* need even set for split palette */

	if( c_min > 0 )
539
	  if( !XAllocColorCells(gdi_display, X11DRV_PALETTE_PaletteXColormap, False,
540 541
                                plane_masks, 0, pixDynMapping, c_min) )
	    {
542
	      WARN("Inexplicable failure during colorcell allocation.\n");
543 544 545
	      c_min = 0;
	    }

546
        palette_size = c_min + NB_RESERVED_COLORS;
547

548 549
	XUngrabServer(gdi_display);
        wine_tsx11_unlock();
550

551
	TRACE("adjusted size %i colorcells\n", palette_size);
552
     }
553
   else if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
554
	{
555 556
          /* virtual colorspace - ToPhysical takes care of
           * color translations but we have to allocate full palette
557 558
	   * to maintain compatibility
	   */
559
	  palette_size = 256;
560
	  TRACE("Virtual colorspace - screendepth %i\n", screen_depth);
561
	}
562
   else palette_size = NB_RESERVED_COLORS;	/* system palette only - however we can alloc a bunch
563 564
			                 * of colors and map to them */

565
   TRACE("Shared system palette uses %i colors.\n", palette_size);
566 567 568 569

   /* set gap to account for pixel shortage. It has to be right in the center
    * of the system palette because otherwise raster ops get screwed. */

570
   if( palette_size >= 256 )
571 572
     { COLOR_gapStart = 256; COLOR_gapEnd = -1; }
   else
573
     { COLOR_gapStart = palette_size/2; COLOR_gapEnd = 255 - palette_size/2; }
574

575 576
   X11DRV_PALETTE_firstFree = ( palette_size > NB_RESERVED_COLORS &&
		      (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL || !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED)) )
577 578
		     ? NB_RESERVED_COLORS/2 : -1;

579
   COLOR_sysPal = (PALETTEENTRY*)HeapAlloc(GetProcessHeap(),0,sizeof(PALETTEENTRY)*256);
580 581 582 583
   if(COLOR_sysPal == NULL) {
       ERR("Can not allocate system palette!\n");
       return FALSE;
   }
584 585 586

   /* setup system palette entry <-> pixel mappings and fill in 20 fixed entries */

587
   if (screen_depth <= 8)
588
   {
589
       X11DRV_PALETTE_XPixelToPalette = HeapAlloc( GetProcessHeap(), 0, 256 * sizeof(int) );
590 591 592 593
       if(X11DRV_PALETTE_XPixelToPalette == NULL) {
           ERR("Out of memory: XPixelToPalette!\n");
           return FALSE;
       }
594 595
       for( i = 0; i < 256; i++ )
           X11DRV_PALETTE_XPixelToPalette[i] = NB_PALETTE_EMPTY_VALUE;
596
   }
597 598

   /* for hicolor visuals PaletteToPixel mapping is used to skip
599
    * RGB->pixel calculation in X11DRV_PALETTE_ToPhysical().
600 601
    */

602
   X11DRV_PALETTE_PaletteToXPixel = (int*)HeapAlloc(GetProcessHeap(),0,sizeof(int)*256);
603 604 605 606
   if(X11DRV_PALETTE_PaletteToXPixel == NULL) {
       ERR("Out of memory: PaletteToXPixel!\n");
       return FALSE;
   }
607 608 609

   for( i = j = 0; i < 256; i++ )
   {
610
      if( i >= COLOR_gapStart && i <= COLOR_gapEnd )
611
      {
612
         X11DRV_PALETTE_PaletteToXPixel[i] = NB_PALETTE_EMPTY_VALUE;
613 614 615 616 617 618 619
         COLOR_sysPal[i].peFlags = 0;	/* mark as unused */
         continue;
      }

      if( i < NB_RESERVED_COLORS/2 )
      {
        X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[i];
620 621
        COLOR_sysPal[i] = sys_pal_template[i];
        COLOR_sysPal[i].peFlags |= PC_SYS_USED;
622 623 624
      }
      else if( i >= 256 - NB_RESERVED_COLORS/2 )
      {
625
        X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[(i + NB_RESERVED_COLORS) - 256];
626 627
        COLOR_sysPal[i] = sys_pal_template[(i + NB_RESERVED_COLORS) - 256];
        COLOR_sysPal[i].peFlags |= PC_SYS_USED;
628 629 630 631 632 633
      }
      else if( pixDynMapping )
             X11DRV_PALETTE_PaletteToXPixel[i] = pixDynMapping[j++];
           else
             X11DRV_PALETTE_PaletteToXPixel[i] = i;

634
      TRACE("index %i -> pixel %i\n", i, X11DRV_PALETTE_PaletteToXPixel[i]);
635 636 637 638 639

      if( X11DRV_PALETTE_XPixelToPalette )
          X11DRV_PALETTE_XPixelToPalette[X11DRV_PALETTE_PaletteToXPixel[i]] = i;
   }

640
   if( pixDynMapping ) HeapFree(GetProcessHeap(), 0, pixDynMapping);
641 642 643 644 645 646 647

   return TRUE;
}

/***********************************************************************
 *      Colormap Initialization
 */
648
static void X11DRV_PALETTE_FillDefaultColors( const PALETTEENTRY *sys_pal_template )
649
{
650 651
 /* initialize unused entries to what Windows uses as a color
  * cube - based on Greg Kreider's code.
652 653 654 655
  */

  int i = 0, idx = 0;
  int red, no_r, inc_r;
656
  int green, no_g, inc_g;
657
  int blue, no_b, inc_b;
658

659
  if (palette_size <= NB_RESERVED_COLORS)
660
  	return;
661
  while (i*i*i < (palette_size - NB_RESERVED_COLORS)) i++;
662
  no_r = no_g = no_b = --i;
663 664
  if ((no_r * (no_g+1) * no_b) < (palette_size - NB_RESERVED_COLORS)) no_g++;
  if ((no_r * no_g * (no_b+1)) < (palette_size - NB_RESERVED_COLORS)) no_b++;
665 666 667 668
  inc_r = (255 - NB_COLORCUBE_START_INDEX)/no_r;
  inc_g = (255 - NB_COLORCUBE_START_INDEX)/no_g;
  inc_b = (255 - NB_COLORCUBE_START_INDEX)/no_b;

669 670
  wine_tsx11_lock();

671 672 673 674 675 676 677 678 679 680 681 682 683 684
  idx = X11DRV_PALETTE_firstFree;

  if( idx != -1 )
    for (blue = NB_COLORCUBE_START_INDEX; blue < 256 && idx; blue += inc_b )
     for (green = NB_COLORCUBE_START_INDEX; green < 256 && idx; green += inc_g )
      for (red = NB_COLORCUBE_START_INDEX; red < 256 && idx; red += inc_r )
      {
	 /* weird but true */

	 if( red == NB_COLORCUBE_START_INDEX && green == red && blue == green ) continue;

         COLOR_sysPal[idx].peRed = red;
         COLOR_sysPal[idx].peGreen = green;
         COLOR_sysPal[idx].peBlue = blue;
685

686 687 688 689
	 /* set X color */

	 if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
	 {
690 691 692
            if (X11DRV_PALETTE_PRed.max != 255) no_r = (red * X11DRV_PALETTE_PRed.max) / 255;
            if (X11DRV_PALETTE_PGreen.max != 255) no_g = (green * X11DRV_PALETTE_PGreen.max) / 255;
            if (X11DRV_PALETTE_PBlue.max != 255) no_b = (blue * X11DRV_PALETTE_PBlue.max) / 255;
693

694
            X11DRV_PALETTE_PaletteToXPixel[idx] = (no_r << X11DRV_PALETTE_PRed.shift) | (no_g << X11DRV_PALETTE_PGreen.shift) | (no_b << X11DRV_PALETTE_PBlue.shift);
695 696 697
	 }
	 else if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
	 {
698 699 700 701 702 703
	   XColor color;
	   color.pixel = (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[idx] : idx;
	   color.red = COLOR_sysPal[idx].peRed << 8;
	   color.green = COLOR_sysPal[idx].peGreen << 8;
	   color.blue =  COLOR_sysPal[idx].peBlue << 8;
	   color.flags = DoRed | DoGreen | DoBlue;
704
	   XStoreColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &color);
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
	 }
	 idx = X11DRV_PALETTE_freeList[idx];
      }

  /* try to fill some entries in the "gap" with
   * what's already in the colormap - they will be
   * mappable to but not changeable. */

  if( COLOR_gapStart < COLOR_gapEnd && X11DRV_PALETTE_XPixelToPalette )
  {
    XColor	xc;
    int		r, g, b, max;

    max = COLOR_max - (256 - (COLOR_gapEnd - COLOR_gapStart));
    for ( i = 0, idx = COLOR_gapStart; i < 256 && idx <= COLOR_gapEnd; i++ )
720
      if( X11DRV_PALETTE_XPixelToPalette[i] == NB_PALETTE_EMPTY_VALUE )
721 722 723
	{
	  xc.pixel = i;

724
	  XQueryColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &xc);
725 726
	  r = xc.red>>8; g = xc.green>>8; b = xc.blue>>8;

727
	  if( xc.pixel < 256 && X11DRV_PALETTE_CheckSysColor( sys_pal_template, RGB(r, g, b)) &&
728
	      XAllocColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &xc) )
729 730 731 732 733 734 735 736
	  {
	     X11DRV_PALETTE_XPixelToPalette[xc.pixel] = idx;
	     X11DRV_PALETTE_PaletteToXPixel[idx] = xc.pixel;
           *(COLORREF*)(COLOR_sysPal + idx) = RGB(r, g, b);
	     COLOR_sysPal[idx++].peFlags |= PC_SYS_USED;
	     if( --max <= 0 ) break;
	  }
	}
737
    COLOR_gapFilled = idx - COLOR_gapStart;
738
  }
739
  wine_tsx11_unlock();
740 741 742
}


743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
/***********************************************************************
 *           X11DRV_IsSolidColor
 *
 * Check whether 'color' can be represented with a solid color.
 */
BOOL X11DRV_IsSolidColor( COLORREF color )
{
    int i;
    const PALETTEENTRY *pEntry = COLOR_sysPal;

    if (color & 0xff000000) return TRUE;  /* indexed color */

    if (!color || (color == 0xffffff)) return TRUE;  /* black or white */

    for (i = 0; i < 256 ; i++, pEntry++)
    {
        if( i < COLOR_gapStart || i > COLOR_gapEnd )
            if ((GetRValue(color) == pEntry->peRed) &&
                (GetGValue(color) == pEntry->peGreen) &&
                (GetBValue(color) == pEntry->peBlue)) return TRUE;
    }
    return FALSE;
}


768 769 770 771 772 773 774 775 776 777 778 779
/***********************************************************************
 *           X11DRV_PALETTE_ToLogical
 *
 * Return RGB color for given X pixel.
 */
COLORREF X11DRV_PALETTE_ToLogical(int pixel)
{
    XColor color;

#if 0
    /* truecolor visual */

780
    if (screen_depth >= 24) return pixel;
781 782 783 784
#endif

    /* check for hicolor visuals first */

785
    if ( (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) && !X11DRV_PALETTE_Graymax )
786
    {
787 788 789 790 791 792 793 794 795 796 797 798 799
         color.red = (pixel >> X11DRV_PALETTE_LRed.shift) & X11DRV_PALETTE_LRed.max;
         if (X11DRV_PALETTE_LRed.scale<8)
             color.red=  color.red   << (8-X11DRV_PALETTE_LRed.scale) |
                         color.red   >> (2*X11DRV_PALETTE_LRed.scale-8);
         color.green = (pixel >> X11DRV_PALETTE_LGreen.shift) & X11DRV_PALETTE_LGreen.max;
         if (X11DRV_PALETTE_LGreen.scale<8)
             color.green=color.green << (8-X11DRV_PALETTE_LGreen.scale) |
                         color.green >> (2*X11DRV_PALETTE_LGreen.scale-8);
         color.blue = (pixel >> X11DRV_PALETTE_LBlue.shift) & X11DRV_PALETTE_LBlue.max;
         if (X11DRV_PALETTE_LBlue.scale<8)
             color.blue= color.blue  << (8-X11DRV_PALETTE_LBlue.scale)  |
                         color.blue  >> (2*X11DRV_PALETTE_LBlue.scale-8);
                 return RGB(color.red,color.green,color.blue);
800 801 802 803
    }

    /* check if we can bypass X */

804
    if ((screen_depth <= 8) && (pixel < 256) &&
805
        !(X11DRV_PALETTE_PaletteFlags & (X11DRV_PALETTE_VIRTUAL | X11DRV_PALETTE_FIXED)) ) {
806
         return  ( *(COLORREF*)(COLOR_sysPal +
807
		   ((X11DRV_PALETTE_XPixelToPalette)?X11DRV_PALETTE_XPixelToPalette[pixel]:pixel)) ) & 0x00ffffff;
808
    }
809

810
    wine_tsx11_lock();
811
    color.pixel = pixel;
812 813
    XQueryColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &color);
    wine_tsx11_unlock();
814 815 816
    return RGB(color.red >> 8, color.green >> 8, color.blue >> 8);
}

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843

/***********************************************************************
 *	     X11DRV_SysPaletteLookupPixel
 */
static int X11DRV_SysPaletteLookupPixel( COLORREF col, BOOL skipReserved )
{
    int i, best = 0, diff = 0x7fffffff;
    int r,g,b;

    for( i = 0; i < palette_size && diff ; i++ )
    {
        if( !(COLOR_sysPal[i].peFlags & PC_SYS_USED) ||
            (skipReserved && COLOR_sysPal[i].peFlags  & PC_SYS_RESERVED) )
            continue;

        r = COLOR_sysPal[i].peRed - GetRValue(col);
        g = COLOR_sysPal[i].peGreen - GetGValue(col);
        b = COLOR_sysPal[i].peBlue - GetBValue(col);

        r = r*r + g*g + b*b;

        if( r < diff ) { best = i; diff = r; }
    }
    return best;
}


844 845 846 847 848
/***********************************************************************
 *           X11DRV_PALETTE_ToPhysical
 *
 * Return the physical color closest to 'color'.
 */
849
int X11DRV_PALETTE_ToPhysical( X11DRV_PDEVICE *physDev, COLORREF color )
850
{
851
    DC *dc = physDev ? physDev->dc : NULL;
852
    WORD 		 index = 0;
853
    HPALETTE		 hPal = (dc)? dc->hPalette: GetStockObject(DEFAULT_PALETTE);
854 855 856
    unsigned char	 spec_type = color >> 24;
    PALETTEOBJ* 	 palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hPal, PALETTE_MAGIC );

857 858 859
    /* palPtr can be NULL when DC is being destroyed */
    if( !palPtr ) return 0;

860 861 862
    if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED )
    {
        /* there is no colormap limitation; we are going to have to compute
863
         * the pixel value from the visual information stored earlier
864 865 866 867 868 869 870 871 872 873 874
	 */

	unsigned 	long red, green, blue;
	unsigned 	idx = 0;

	switch(spec_type)
        {
          case 1: /* PALETTEINDEX */

            if( (idx = color & 0xffff) >= palPtr->logpalette.palNumEntries)
            {
875
                WARN("RGB(%lx) : idx %d is out of bounds, assuming black\n", color, idx);
876
		GDI_ReleaseObj( hPal );
877 878 879
                return 0;
            }

880
            if( palPtr->mapping )
881
	    {
882 883 884
                int ret = palPtr->mapping[idx];
		GDI_ReleaseObj( hPal );
		return ret;
885 886 887 888 889 890 891 892 893
	    }
	    color = *(COLORREF*)(palPtr->logpalette.palPalEntry + idx);
	    break;

	  default:
	    color &= 0xffffff;
	    /* fall through to RGB */

	  case 0: /* RGB */
894
	    if( dc && (dc->bitsPerPixel == 1) )
895
	    {
896
		GDI_ReleaseObj( hPal );
897 898 899 900 901 902 903 904 905 906 907
		return (((color >> 16) & 0xff) +
			((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
	    }

	}

        red = GetRValue(color); green = GetGValue(color); blue = GetBValue(color);

	if (X11DRV_PALETTE_Graymax)
        {
	    /* grayscale only; return scaled value */
908
	    GDI_ReleaseObj( hPal );
909
            return ( (red * 30 + green * 59 + blue * 11) * X11DRV_PALETTE_Graymax) / 25500;
910 911 912 913
	}
	else
        {
	    /* scale each individually and construct the TrueColor pixel value */
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
	    if (X11DRV_PALETTE_PRed.scale < 8)
		red = red >> (8-X11DRV_PALETTE_PRed.scale);
	    else if (X11DRV_PALETTE_PRed.scale > 8)
		red =   red   << (X11DRV_PALETTE_PRed.scale-8) |
                        red   >> (16-X11DRV_PALETTE_PRed.scale);
	    if (X11DRV_PALETTE_PGreen.scale < 8)
		green = green >> (8-X11DRV_PALETTE_PGreen.scale);
	    else if (X11DRV_PALETTE_PGreen.scale > 8)
		green = green << (X11DRV_PALETTE_PGreen.scale-8) |
                        green >> (16-X11DRV_PALETTE_PGreen.scale);
	    if (X11DRV_PALETTE_PBlue.scale < 8)
		blue =  blue  >> (8-X11DRV_PALETTE_PBlue.scale);
	    else if (X11DRV_PALETTE_PBlue.scale > 8)
		blue =  blue  << (X11DRV_PALETTE_PBlue.scale-8) |
                        blue  >> (16-X11DRV_PALETTE_PBlue.scale);
929

930
	    GDI_ReleaseObj( hPal );
931
            return (red << X11DRV_PALETTE_PRed.shift) | (green << X11DRV_PALETTE_PGreen.shift) | (blue << X11DRV_PALETTE_PBlue.shift);
932 933
        }
    }
934
    else
935 936
    {

937
	if( !palPtr->mapping )
938
            WARN("Palette %p is not realized\n", dc->hPalette);
939 940 941 942 943 944 945 946

	switch(spec_type)	/* we have to peruse DC and system palette */
    	{
	    default:
		color &= 0xffffff;
		/* fall through to RGB */

       	    case 0:  /* RGB */
947
		if( dc && (dc->bitsPerPixel == 1) )
948
		{
949
		    GDI_ReleaseObj( hPal );
950 951 952 953
		    return (((color >> 16) & 0xff) +
			    ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
		}

954 955
	    	index = X11DRV_SysPaletteLookupPixel( color, FALSE);
                if (X11DRV_PALETTE_PaletteToXPixel) index = X11DRV_PALETTE_PaletteToXPixel[index];
956 957 958 959 960 961 962 963

		/* TRACE(palette,"RGB(%lx) -> pixel %i\n", color, index);
		 */
	    	break;
       	    case 1:  /* PALETTEINDEX */
		index = color & 0xffff;

	        if( index >= palPtr->logpalette.palNumEntries )
964
		    WARN("RGB(%lx) : index %i is out of bounds\n", color, index);
965 966 967 968 969 970
		else if( palPtr->mapping ) index = palPtr->mapping[index];

		/*  TRACE(palette,"PALETTEINDEX(%04x) -> pixel %i\n", (WORD)color, index);
		 */
		break;
            case 2:  /* PALETTERGB */
971 972
                index = GetNearestPaletteIndex( hPal, color );
                if (palPtr->mapping) index = palPtr->mapping[index];
973 974 975 976 977 978
		/* TRACE(palette,"PALETTERGB(%lx) -> pixel %i\n", color, index);
		 */
		break;
	}
    }

979
    GDI_ReleaseObj( hPal );
980 981 982 983 984 985
    return index;
}

/***********************************************************************
 *           X11DRV_PALETTE_LookupSystemXPixel
 */
986
static int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col)
987 988
{
 int            i, best = 0, diff = 0x7fffffff;
989
 int            size = palette_size;
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
 int            r,g,b;

 for( i = 0; i < size && diff ; i++ )
    {
      if( i == NB_RESERVED_COLORS/2 )
      {
      	int newi = size - NB_RESERVED_COLORS/2;
	if (newi>i) i=newi;
      }

      r = COLOR_sysPal[i].peRed - GetRValue(col);
      g = COLOR_sysPal[i].peGreen - GetGValue(col);
      b = COLOR_sysPal[i].peBlue - GetBValue(col);

      r = r*r + g*g + b*b;

      if( r < diff ) { best = i; diff = r; }
    }
1008

1009 1010 1011 1012 1013 1014 1015 1016 1017
 return (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[best] : best;
}

/***********************************************************************
 *           X11DRV_PALETTE_FormatSystemPalette
 */
static void X11DRV_PALETTE_FormatSystemPalette(void)
{
 /* Build free list so we'd have an easy way to find
1018
  * out if there are any available colorcells.
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  */

  int i, j = X11DRV_PALETTE_firstFree = NB_RESERVED_COLORS/2;

  COLOR_sysPal[j].peFlags = 0;
  for( i = NB_RESERVED_COLORS/2 + 1 ; i < 256 - NB_RESERVED_COLORS/2 ; i++ )
    if( i < COLOR_gapStart || i > COLOR_gapEnd )
      {
	COLOR_sysPal[i].peFlags = 0;  /* unused tag */
	X11DRV_PALETTE_freeList[j] = i;	  /* next */
        j = i;
      }
  X11DRV_PALETTE_freeList[j] = 0;
}

/***********************************************************************
 *           X11DRV_PALETTE_CheckSysColor
 */
1037
static BOOL X11DRV_PALETTE_CheckSysColor( const PALETTEENTRY *sys_pal_template, COLORREF c)
1038 1039 1040
{
  int i;
  for( i = 0; i < NB_RESERVED_COLORS; i++ )
1041
       if( c == (*(COLORREF*)(sys_pal_template + i) & 0x00ffffff) )
1042 1043 1044 1045
	   return 0;
  return 1;
}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

/***********************************************************************
 *	     X11DRV_LookupSysPaletteExact
 */
static int X11DRV_LookupSysPaletteExact( COLORREF col )
{
    int i;
    BYTE r = GetRValue(col), g = GetGValue(col), b = GetBValue(col);
    for( i = 0; i < palette_size; i++ )
    {
        if( COLOR_sysPal[i].peFlags & PC_SYS_USED )  /* skips gap */
            if( COLOR_sysPal[i].peRed == r &&
                COLOR_sysPal[i].peGreen == g &&
                COLOR_sysPal[i].peBlue == b )
                return i;
    }
    return -1;
}


1066 1067 1068
/***********************************************************************
 *           X11DRV_PALETTE_SetMapping
 *
1069
 * Set the color-mapping table for selected palette.
1070 1071
 * Return number of entries which mapping has changed.
 */
1072
static UINT X11DRV_PALETTE_SetMapping( PALETTEOBJ* palPtr, UINT uStart, UINT uNum, BOOL mapOnly )
1073 1074 1075
{
    char flag;
    int  prevMapping = (palPtr->mapping) ? 1 : 0;
1076 1077
    int  index;
    UINT iRemapped = 0;
1078
    int* mapping;
1079 1080 1081 1082 1083 1084 1085

    /* reset dynamic system palette entries */

    if( !mapOnly && X11DRV_PALETTE_firstFree != -1)
         X11DRV_PALETTE_FormatSystemPalette();

    /* initialize palette mapping table */
1086 1087 1088 1089 1090
    if (palPtr->mapping) 
	mapping = HeapReAlloc( GetProcessHeap(), 0, palPtr->mapping,
                           sizeof(int)*palPtr->logpalette.palNumEntries);
    else 
	mapping = HeapAlloc( GetProcessHeap(), 0, 
1091
                           sizeof(int)*palPtr->logpalette.palNumEntries);
1092

1093
    if(mapping == NULL) {
1094
        ERR("Can not allocate new mapping -- memory exausted!\n");
1095 1096 1097
        return 0;
    }
    palPtr->mapping = mapping;
1098

1099 1100 1101 1102 1103
    if (uStart >= palPtr->logpalette.palNumEntries) return 0;

    if (uStart + uNum > palPtr->logpalette.palNumEntries)
        uNum = palPtr->logpalette.palNumEntries - uStart;

1104 1105 1106 1107 1108 1109 1110 1111 1112
    for( uNum += uStart; uStart < uNum; uStart++ )
    {
        index = -1;
        flag = PC_SYS_USED;

        switch( palPtr->logpalette.palPalEntry[uStart].peFlags & 0x07 )
        {
	case PC_EXPLICIT:   /* palette entries are indices into system palette */
            index = *(WORD*)(palPtr->logpalette.palPalEntry + uStart);
1113
            if( index > 255 || (index >= COLOR_gapStart && index <= COLOR_gapEnd) )
1114
            {
1115
                WARN("PC_EXPLICIT: idx %d out of system palette, assuming black.\n", index);
1116 1117 1118 1119 1120 1121 1122 1123 1124
                index = 0;
            }
            break;

	case PC_RESERVED:   /* forbid future mappings to this entry */
            flag |= PC_SYS_RESERVED;

            /* fall through */
	default:	    /* try to collapse identical colors */
1125
            index = X11DRV_LookupSysPaletteExact(*(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
1126
            /* fall through */
1127
	case PC_NOCOLLAPSE:
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
            if( index < 0 )
            {
                if( X11DRV_PALETTE_firstFree > 0 && !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
                {
                    XColor color;
                    index = X11DRV_PALETTE_firstFree;  /* ought to be available */
                    X11DRV_PALETTE_firstFree = X11DRV_PALETTE_freeList[index];

                    color.pixel = (X11DRV_PALETTE_PaletteToXPixel) ? X11DRV_PALETTE_PaletteToXPixel[index] : index;
                    color.red = palPtr->logpalette.palPalEntry[uStart].peRed << 8;
                    color.green = palPtr->logpalette.palPalEntry[uStart].peGreen << 8;
                    color.blue = palPtr->logpalette.palPalEntry[uStart].peBlue << 8;
                    color.flags = DoRed | DoGreen | DoBlue;
1141 1142 1143
                    wine_tsx11_lock();
                    XStoreColor(gdi_display, X11DRV_PALETTE_PaletteXColormap, &color);
                    wine_tsx11_unlock();
1144 1145 1146 1147 1148 1149 1150 1151

                    COLOR_sysPal[index] = palPtr->logpalette.palPalEntry[uStart];
                    COLOR_sysPal[index].peFlags = flag;
		    X11DRV_PALETTE_freeList[index] = 0;

                    if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
                    break;
                }
1152
                else if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
1153 1154 1155
                {
                    index = X11DRV_PALETTE_ToPhysical( NULL, 0x00ffffff &
                             *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
1156
                    break;
1157 1158 1159 1160
                }

                /* we have to map to existing entry in the system palette */

1161
                index = X11DRV_SysPaletteLookupPixel( *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), TRUE);
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
            }
	    palPtr->logpalette.palPalEntry[uStart].peFlags |= PC_SYS_USED;

            if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
            break;
        }

        if( !prevMapping || palPtr->mapping[uStart] != index ) iRemapped++;
        palPtr->mapping[uStart] = index;

1172
        TRACE("entry %i (%lx) -> pixel %i\n", uStart,
1173
				*(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), index);
1174

1175 1176 1177 1178 1179
    }
    return iRemapped;
}

/***********************************************************************
1180
 *              GetSystemPaletteEntries   (X11DRV.@)
1181
 */
1182 1183
UINT X11DRV_GetSystemPaletteEntries( X11DRV_PDEVICE *physDev, UINT start, UINT count,
                                     LPPALETTEENTRY entries )
1184
{
1185
    UINT i;
1186

1187 1188 1189
    if (!entries) return palette_size;
    if (start >= palette_size) return 0;
    if (start + count >= palette_size) count = palette_size - start;
1190

1191
    for (i = 0; i < count; i++)
1192
    {
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
        entries[i].peRed   = COLOR_sysPal[start + i].peRed;
        entries[i].peGreen = COLOR_sysPal[start + i].peGreen;
        entries[i].peBlue  = COLOR_sysPal[start + i].peBlue;
        entries[i].peFlags = 0;
        TRACE("\tidx(%02x) -> RGB(%08lx)\n", start + i, *(COLORREF*)(entries + i) );
    }
    return count;
}


/***********************************************************************
 *              GetNearestColor   (X11DRV.@)
 */
COLORREF X11DRV_GetNearestColor( X11DRV_PDEVICE *physDev, COLORREF color )
{
    unsigned char spec_type = color >> 24;
    COLORREF nearest;

    if (!palette_size) return color;

    if (spec_type == 1 || spec_type == 2)
    {
        /* we need logical palette for PALETTERGB and PALETTEINDEX colorrefs */

        UINT index;
        PALETTEENTRY entry;
        HPALETTE hpal = GetCurrentObject( physDev->hdc, OBJ_PAL );
1220

1221
        if (!hpal) hpal = GetStockObject( DEFAULT_PALETTE );
1222

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
        if (spec_type == 2) /* PALETTERGB */
            index = GetNearestPaletteIndex( hpal, color );
        else  /* PALETTEINDEX */
            index = LOWORD(color);

        if (!GetPaletteEntries( hpal, index, 1, &entry ))
        {
            WARN("RGB(%lx) : idx %d is out of bounds, assuming NULL\n", color, index );
            if (!GetPaletteEntries( hpal, 0, 1, &entry )) return CLR_INVALID;
        }
        color = RGB( entry.peRed,  entry.peGreen, entry.peBlue );
1234
    }
1235 1236
    color &= 0x00ffffff;
    nearest = (0x00ffffff & *(COLORREF*)(COLOR_sysPal + X11DRV_SysPaletteLookupPixel(color, FALSE)));
1237

1238 1239
    TRACE("(%06lx): returning %06lx\n", color, nearest );
    return nearest;
1240 1241
}

1242 1243 1244

/***********************************************************************
 *              RealizePalette    (X11DRV.@)
1245
 */
1246
UINT X11DRV_RealizePalette( X11DRV_PDEVICE *physDev, HPALETTE hpal, BOOL primary )
1247
{
1248 1249 1250
    UINT ret;
    PALETTEOBJ *palPtr;

1251 1252
    if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL) return 0;

1253 1254 1255 1256
    if (!(palPtr = GDI_GetObjPtr( hpal, PALETTE_MAGIC ))) return 0;
    ret = X11DRV_PALETTE_SetMapping( palPtr, 0, palPtr->logpalette.palNumEntries, !primary );
    GDI_ReleaseObj( hpal );
    return ret;
1257 1258
}

1259 1260 1261 1262 1263 1264 1265 1266

/***********************************************************************
 *              RealizeDefaultPalette    (X11DRV.@)
 */
UINT X11DRV_RealizeDefaultPalette( X11DRV_PDEVICE *physDev )
{
    UINT ret = 0;

1267
    if (palette_size && GetObjectType(physDev->hdc) != OBJ_MEMDC)
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    {
        PALETTEOBJ*  palPtr = GDI_GetObjPtr( GetStockObject(DEFAULT_PALETTE), PALETTE_MAGIC );
        if (palPtr)
        {
            /* lookup is needed to account for SetSystemPaletteUse() stuff */
            int i, index;

            for( i = 0; i < 20; i++ )
            {
                index = X11DRV_PALETTE_LookupSystemXPixel(*(COLORREF*)(palPtr->logpalette.palPalEntry + i));
                /* mapping is allocated in COLOR_InitPalette() */
                if( index != palPtr->mapping[i] )
                {
                    palPtr->mapping[i]=index;
                    ret++;
                }
            }
            GDI_ReleaseObj( GetStockObject(DEFAULT_PALETTE) );
        }
    }
    return ret;
}