1 /* Copyright (C) 2001-2006 Artifex Software, Inc.
2    All Rights Reserved.
3 
4    This software is provided AS-IS with no warranty, either express or
5    implied.
6 
7    This software is distributed under license and may not be copied, modified
8    or distributed except as expressly authorized under the terms of that
9    license.  Refer to licensing information at http://www.artifex.com/
10    or contact Artifex Software, Inc.,  7 Mt. Lassen Drive - Suite A-134,
11    San Rafael, CA  94903, U.S.A., +1(415)492-9861, for further information.
12 */
13 
14 /* $Id: gdevxcmp.c 8250 2007-09-25 13:31:24Z giles $ */
15 /* X Windows color mapping */
16 #include "math_.h"
17 #include "x_.h"
18 #include "gx.h"			/* for gx_bitmap; includes std.h */
19 #include "gserrors.h"
20 #include "gxdevice.h"
21 #include "gdevx.h"
22 
23 /* ---------------- Utilities ---------------- */
24 
25 static void
gs_x_free(gs_memory_t * mem,void * obj,client_name_t cname)26 gs_x_free(gs_memory_t *mem, void *obj, client_name_t cname)
27 {
28     gs_free(mem, obj, 0 /*ignored*/, 0 /*ignored*/, cname);
29 }
30 
31 /* ---------------- Color mapping setup / cleanup ---------------- */
32 
33 #if HaveStdCMap
34 
35 /* Install a standard color map in the device. */
36 /* Sets std_cmap.* except for free_map. */
37 static bool
set_cmap_values(x11_cmap_values_t * values,int maxv,int mult)38 set_cmap_values(x11_cmap_values_t *values, int maxv, int mult)
39 {
40     int i;
41 
42     if (maxv < 1 || maxv > 63 || (maxv & (maxv + 1)) ||
43 	(mult & (mult - 1))
44 	)
45 	return false;
46     values->cv_shift = 16 - small_exact_log2(maxv + 1);
47     for (i = 0; i <= maxv; ++i)
48 	values->nearest[i] = X_max_color_value * i / maxv;
49     for (i = 0; mult != (1 << i); ++i)
50 	DO_NOTHING;
51     values->pixel_shift = i;
52     return true;
53 }
54 static void
set_std_cmap(gx_device_X * xdev,XStandardColormap * map)55 set_std_cmap(gx_device_X *xdev, XStandardColormap *map)
56 {
57     xdev->cman.std_cmap.map = map;
58     xdev->cman.std_cmap.fast =
59 	set_cmap_values(&xdev->cman.std_cmap.red, map->red_max, map->red_mult) &&
60 	set_cmap_values(&xdev->cman.std_cmap.green, map->green_max, map->green_mult) &&
61 	set_cmap_values(&xdev->cman.std_cmap.blue, map->blue_max, map->blue_mult);
62 }
63 
64 /* Get the Standard colormap if available. */
65 /* Uses: dpy, scr, cmap. */
66 static XStandardColormap *
x_get_std_cmap(gx_device_X * xdev,Atom prop)67 x_get_std_cmap(gx_device_X * xdev, Atom prop)
68 {
69     int i;
70     XStandardColormap *scmap, *sp;
71     int nitems;
72 
73     if (XGetRGBColormaps(xdev->dpy, RootWindowOfScreen(xdev->scr),
74 			 &scmap, &nitems, prop))
75 	for (i = 0, sp = scmap; i < nitems; i++, sp++)
76 	    if (xdev->cmap == sp->colormap)
77 		return sp;
78 
79     return NULL;
80 }
81 
82 /* Create a Standard colormap for a TrueColor or StaticGray display. */
83 /* Return true if the allocation was successful. */
84 /* Uses: vinfo.  Sets: std_cmap.*. */
85 static bool
alloc_std_cmap(gx_device_X * xdev,bool colored)86 alloc_std_cmap(gx_device_X *xdev, bool colored)
87 {
88     XStandardColormap *cmap = XAllocStandardColormap();
89 
90     if (cmap == 0)
91 	return false;		/* can't allocate */
92     /*
93      * Some buggy X servers (including XFree86) don't set any of the
94      * _mask values for StaticGray visuals.  Compensate for that here.
95      */
96     if ((cmap->red_max = xdev->vinfo->red_mask) == 0) {
97 	cmap->red_max = (1 << xdev->vinfo->depth) - 1;
98 	cmap->red_mult = 1;
99     } else {
100 	for (cmap->red_mult = 1; (cmap->red_max & 1) == 0;) {
101 	    cmap->red_max >>= 1;
102 	    cmap->red_mult <<= 1;
103 	}
104     }
105     if (colored) {
106 	for (cmap->green_max = xdev->vinfo->green_mask, cmap->green_mult = 1;
107 	     (cmap->green_max & 1) == 0;
108 	     ) {
109 	    cmap->green_max >>= 1;
110 	    cmap->green_mult <<= 1;
111 	}
112 	for (cmap->blue_max = xdev->vinfo->blue_mask, cmap->blue_mult = 1;
113 	     (cmap->blue_max & 1) == 0;
114 	     ) {
115 	    cmap->blue_max >>= 1;
116 	    cmap->blue_mult <<= 1;
117 	}
118     } else {
119         cmap->green_max = cmap->blue_max = cmap->red_max;
120         cmap->green_mult = cmap->blue_mult = cmap->red_mult;
121     }
122     set_std_cmap(xdev, cmap);
123     xdev->cman.std_cmap.free_map = true;
124     return true;
125 }
126 
127 #endif
128 
129 /* Allocate the dynamic color table, if needed and possible. */
130 /* Uses: vinfo, cman.num_rgb.  Sets: cman.dynamic.*. */
131 static void
alloc_dynamic_colors(gx_device_X * xdev,int num_colors)132 alloc_dynamic_colors(gx_device_X * xdev, int num_colors)
133 {
134     if (num_colors > 0) {
135 	xdev->cman.dynamic.colors = (x11_color_t **)
136 	    gs_malloc(xdev->memory, sizeof(x11_color_t *), xdev->cman.num_rgb,
137 		      "x11 cman.dynamic.colors");
138 	if (xdev->cman.dynamic.colors) {
139 	    int i;
140 
141 	    xdev->cman.dynamic.size = xdev->cman.num_rgb;
142 	    xdev->cman.dynamic.shift = 16 - xdev->vinfo->bits_per_rgb;
143 	    for (i = 0; i < xdev->cman.num_rgb; i++)
144 		xdev->cman.dynamic.colors[i] = NULL;
145 	    xdev->cman.dynamic.max_used = min(256, num_colors);
146 	    xdev->cman.dynamic.used = 0;
147 	}
148     }
149 }
150 
151 /* Allocate an X color, updating the reverse map. */
152 /* Return true if the allocation was successful. */
153 static bool
x_alloc_color(gx_device_X * xdev,XColor * xcolor)154 x_alloc_color(gx_device_X *xdev, XColor *xcolor)
155 {
156     x11_rgb_t rgb;
157 
158     rgb.rgb[0] = xcolor->red;
159     rgb.rgb[1] = xcolor->green;
160     rgb.rgb[2] = xcolor->blue;
161     if (!XAllocColor(xdev->dpy, xdev->cmap, xcolor))
162 	return false;
163     if (xcolor->pixel < xdev->cman.color_to_rgb.size) {
164 	x11_rgb_t *pxrgb = &xdev->cman.color_to_rgb.values[xcolor->pixel];
165 
166 	memcpy(pxrgb->rgb, rgb.rgb, sizeof(rgb.rgb));
167 	pxrgb->defined = true;
168     }
169     return true;
170 }
171 
172 /* Free X colors, updating the reverse map. */
173 static void
x_free_colors(gx_device_X * xdev,x_pixel * pixels,int count)174 x_free_colors(gx_device_X *xdev, x_pixel *pixels /*[count]*/, int count)
175 {
176     int i;
177     x_pixel pixel;
178 
179     XFreeColors(xdev->dpy, xdev->cmap, pixels, count, 0);
180     for (i = 0; i < count; ++i)
181 	if ((pixel = pixels[i]) < xdev->cman.color_to_rgb.size)
182 	    xdev->cman.color_to_rgb.values[pixel].defined = false;
183 }
184 
185 /* Free a partially filled color cube or ramp. */
186 /* Uses: dpy, cmap.  Uses and sets: cman.dither_ramp. */
187 static void
free_ramp(gx_device_X * xdev,int num_used,int size)188 free_ramp(gx_device_X * xdev, int num_used, int size)
189 {
190     if (num_used - 1 > 0)
191 	x_free_colors(xdev, xdev->cman.dither_ramp + 1, num_used - 1);
192     gs_x_free(xdev->memory, xdev->cman.dither_ramp, "x11_setup_colors");
193     xdev->cman.dither_ramp = NULL;
194 }
195 
196 /* Allocate and fill in a color cube or ramp. */
197 /* Return true if the operation succeeded. */
198 /* Uses: dpy, cmap, foreground, background, cman.color_mask. */
199 /* Sets: cman.dither_ramp. */
200 static bool
setup_cube(gx_device_X * xdev,int ramp_size,bool colors)201 setup_cube(gx_device_X * xdev, int ramp_size, bool colors)
202 {
203     int step, num_entries;
204     int max_rgb = ramp_size - 1;
205     int index;
206 
207     if (colors) {
208 	num_entries = ramp_size * ramp_size * ramp_size;
209 	step = 1;		/* all colors */
210     } else {
211 	num_entries = ramp_size;
212 	step = (ramp_size + 1) * ramp_size + 1;		/* gray only */
213     }
214 
215     xdev->cman.dither_ramp =
216 	(x_pixel *) gs_malloc(xdev->memory, sizeof(x_pixel), num_entries,
217 			      "gdevx setup_cube");
218     if (xdev->cman.dither_ramp == NULL)
219 	return false;
220 
221     xdev->cman.dither_ramp[0] = xdev->foreground;
222     xdev->cman.dither_ramp[num_entries - 1] = xdev->background;
223     for (index = 1; index < num_entries - 1; index++) {
224 	int rgb_index = index * step;
225 	int q = rgb_index / ramp_size,
226 	    r = q / ramp_size,
227 	    g = q % ramp_size,
228 	    b = rgb_index % ramp_size;
229 	XColor xc;
230 
231 	xc.red = (X_max_color_value * r / max_rgb) & xdev->cman.color_mask.red;
232 	xc.green = (X_max_color_value * g / max_rgb) & xdev->cman.color_mask.green;
233 	xc.blue = (X_max_color_value * b / max_rgb) & xdev->cman.color_mask.blue;
234 	if (!x_alloc_color(xdev, &xc)) {
235 	    free_ramp(xdev, index, num_entries);
236 	    return false;
237 	}
238 	xdev->cman.dither_ramp[index] = xc.pixel;
239     }
240 
241     return true;
242 }
243 
244 /* Setup color mapping. */
245 int
gdev_x_setup_colors(gx_device_X * xdev)246 gdev_x_setup_colors(gx_device_X * xdev)
247 {
248     char palette =
249 	((xdev->vinfo->class != StaticGray) &&
250 	 (xdev->vinfo->class != GrayScale) ? 'C' :	/* Color */
251 	 (xdev->vinfo->colormap_size > 2) ? 'G' :		/* GrayScale */
252 	 'M');		/* MonoChrome */
253 
254     if (xdev->ghostview) {
255 	Atom gv_colors = XInternAtom(xdev->dpy, "GHOSTVIEW_COLORS", False);
256 	Atom type;
257 	int format;
258 	unsigned long nitems, bytes_after;
259 	char *buf;
260 
261 	/* Delete property if explicit dest is given */
262 	if (XGetWindowProperty(xdev->dpy, xdev->win, gv_colors, 0,
263 			       256, (xdev->dest != 0), XA_STRING,
264 			       &type, &format, &nitems, &bytes_after,
265 			       (unsigned char **)&buf) == 0 &&
266 	    type == XA_STRING) {
267 	    nitems = sscanf(buf, "%*s %ld %ld", &(xdev->foreground),
268 			    &(xdev->background));
269 	    if (nitems != 2 || (*buf != 'M' && *buf != 'G' && *buf != 'C')) {
270 		eprintf("Malformed GHOSTVIEW_COLOR property.\n");
271 		return_error(gs_error_rangecheck);
272 	    }
273 	    palette = max(palette, *buf);
274 	}
275     } else {
276 	if (xdev->palette[0] == 'c')
277 	    xdev->palette[0] = 'C';
278 	else if (xdev->palette[0] == 'g')
279 	    xdev->palette[0] = 'G';
280 	else if (xdev->palette[0] == 'm')
281 	    xdev->palette[0] = 'M';
282 	palette = max(palette, xdev->palette[0]);
283     }
284 
285     /* set up color mappings here */
286     xdev->cman.color_mask.red = xdev->cman.color_mask.green =
287 	xdev->cman.color_mask.blue = X_max_color_value -
288 	  (X_max_color_value >> xdev->vinfo->bits_per_rgb);
289     xdev->cman.match_mask = xdev->cman.color_mask; /* default */
290     xdev->cman.num_rgb = 1 << xdev->vinfo->bits_per_rgb;
291 
292 #if HaveStdCMap
293     xdev->cman.std_cmap.map = NULL;
294     xdev->cman.std_cmap.free_map = false;
295 #endif
296     xdev->cman.dither_ramp = NULL;
297     xdev->cman.dynamic.colors = NULL;
298     xdev->cman.dynamic.size = 0;
299     xdev->cman.dynamic.used = 0;
300     switch (xdev->vinfo->depth) {
301     case 1: case 2: case 4: case 8: case 16: case 24: case 32:
302 	xdev->color_info.depth = xdev->vinfo->depth;
303 	break;
304     case 15:
305 	xdev->color_info.depth = 16;
306 	break;
307     default:
308 	eprintf1("Unsupported X visual depth: %d\n", xdev->vinfo->depth);
309 	return_error(gs_error_rangecheck);
310     }
311     {	/* Set up the reverse map from pixel values to RGB. */
312 	int count = 1 << min(xdev->color_info.depth, 8);
313 
314 	xdev->cman.color_to_rgb.values =
315 	    (x11_rgb_t *)gs_malloc(xdev->memory, sizeof(x11_rgb_t), count,
316 				   "gdevx color_to_rgb");
317 	if (xdev->cman.color_to_rgb.values) {
318 	    int i;
319 
320 	    for (i = 0; i < count; ++i)
321 		xdev->cman.color_to_rgb.values[i].defined = false;
322 	    xdev->cman.color_to_rgb.size = count;
323 	} else
324 	    xdev->cman.color_to_rgb.size = 0;
325     }
326     switch ((int)palette) {
327     case 'C':
328 	xdev->color_info.num_components = 3;
329 	xdev->color_info.max_gray =
330 	    xdev->color_info.max_color = xdev->cman.num_rgb - 1;
331 #if HaveStdCMap
332 	/* Get a standard color map if available */
333 	if (xdev->vinfo->visual == DefaultVisualOfScreen(xdev->scr)) {
334 	    xdev->cman.std_cmap.map = x_get_std_cmap(xdev, XA_RGB_DEFAULT_MAP);
335 	} else {
336 	    xdev->cman.std_cmap.map = x_get_std_cmap(xdev, XA_RGB_BEST_MAP);
337 	}
338 	if (xdev->cman.std_cmap.map ||
339 	    (xdev->vinfo->class == TrueColor && alloc_std_cmap(xdev, true))
340 	    ) {
341 	    xdev->color_info.dither_grays = xdev->color_info.dither_colors =
342 		min(xdev->cman.std_cmap.map->red_max,
343 		    min(xdev->cman.std_cmap.map->green_max,
344 			xdev->cman.std_cmap.map->blue_max)) + 1;
345 	    if (xdev->cman.std_cmap.map)
346 		set_std_cmap(xdev, xdev->cman.std_cmap.map);
347 	} else
348 #endif
349 	    /* Otherwise set up a rgb cube of our own */
350 	    /* The color cube is limited to about 1/2 of the available */
351 	    /* colormap, the user specified maxRGBRamp (usually 5), */
352 	    /* or the number of representable colors */
353 #define CUBE(r) (r*r*r)
354 #define CBRT(r) pow(r, 1.0/3.0)
355 	{
356 	    int ramp_size =
357 		min((int)CBRT(xdev->vinfo->colormap_size / 2.0),
358 		    min(xdev->maxRGBRamp, xdev->cman.num_rgb));
359 
360 	    while (!xdev->cman.dither_ramp && ramp_size >= 2) {
361 		xdev->color_info.dither_grays =
362 		    xdev->color_info.dither_colors = ramp_size;
363 		if (!setup_cube(xdev, ramp_size, true)) {
364 #ifdef DEBUG
365 		    eprintf3("Warning: failed to allocate %dx%dx%d RGB cube.\n",
366 			     ramp_size, ramp_size, ramp_size);
367 #endif
368 		    ramp_size--;
369 		    continue;
370 		}
371 	    }
372 
373 	    if (!xdev->cman.dither_ramp) {
374 		goto grayscale;
375 	    }
376 	}
377 
378 	/* Allocate the dynamic color table. */
379 	alloc_dynamic_colors(xdev, CUBE(xdev->cman.num_rgb) -
380 			     CUBE(xdev->color_info.dither_colors));
381 #undef CUBE
382 #undef CBRT
383 	break;
384     case 'G':
385 grayscale:
386 	xdev->color_info.num_components = 1;
387 	xdev->color_info.max_gray = xdev->cman.num_rgb - 1;
388 #if HaveStdCMap
389 	/* Get a standard color map if available */
390 	xdev->cman.std_cmap.map = x_get_std_cmap(xdev, XA_RGB_GRAY_MAP);
391 	if (xdev->cman.std_cmap.map ||
392 	    (xdev->vinfo->class == StaticGray && alloc_std_cmap(xdev, false))
393 	    ) {
394 	    xdev->color_info.dither_grays =
395 		xdev->cman.std_cmap.map->red_max + 1;
396 	    if (xdev->cman.std_cmap.map)
397 		set_std_cmap(xdev, xdev->cman.std_cmap.map);
398 	} else
399 #endif
400 	    /* Otherwise set up a gray ramp of our own */
401 	    /* The gray ramp is limited to about 1/2 of the available */
402 	    /* colormap, the user specified maxGrayRamp (usually 128), */
403 	    /* or the number of representable grays */
404 	{
405 	    int ramp_size = min(xdev->vinfo->colormap_size / 2,
406 				min(xdev->maxGrayRamp, xdev->cman.num_rgb));
407 
408 	    while (!xdev->cman.dither_ramp && ramp_size >= 3) {
409 		xdev->color_info.dither_grays = ramp_size;
410 		if (!setup_cube(xdev, ramp_size, false)) {
411 #ifdef DEBUG
412 		    eprintf1("Warning: failed to allocate %d level gray ramp.\n",
413 			     ramp_size);
414 #endif
415 		    ramp_size /= 2;
416 		    continue;
417 		}
418 	    }
419 	    if (!xdev->cman.dither_ramp) {
420 		goto monochrome;
421 	    }
422 	}
423 
424 	/* Allocate the dynamic color table. */
425 	alloc_dynamic_colors(xdev, xdev->cman.num_rgb -
426 			     xdev->color_info.dither_grays);
427 	break;
428     case 'M':
429 monochrome:
430 	xdev->color_info.num_components = 1;
431 	xdev->color_info.max_gray = 1;
432 	xdev->color_info.dither_grays = 2;
433 	break;
434     default:
435 	eprintf1("Unknown palette: %s\n", xdev->palette);
436 	if (xdev->cman.color_to_rgb.values) {
437 	    gs_x_free(xdev->memory, xdev->cman.color_to_rgb.values, "gdevx color_to_rgb");
438 	    xdev->cman.color_to_rgb.values = 0;
439 	}
440 	return_error(gs_error_rangecheck);
441     }
442 
443 #if HaveStdCMap
444     /*
445      * When comparing colors, if not halftoning, we must only compare as
446      * many bits as actually fit in a pixel, even if the hardware has more.
447      */
448     if (!gx_device_must_halftone(xdev)) {
449 	if (xdev->cman.std_cmap.map) {
450 	    xdev->cman.match_mask.red &=
451 		X_max_color_value << xdev->cman.std_cmap.red.cv_shift;
452 	    xdev->cman.match_mask.green &=
453 		X_max_color_value << xdev->cman.std_cmap.green.cv_shift;
454 	    xdev->cman.match_mask.blue &=
455 		X_max_color_value << xdev->cman.std_cmap.blue.cv_shift;
456 	}
457     }
458 #endif
459 
460     return 0;
461 }
462 
463 /* Free the dynamic colors when doing an erasepage. */
464 /* Uses: cman.dynamic.*.  Sets: cman.dynamic.used. */
465 void
gdev_x_free_dynamic_colors(gx_device_X * xdev)466 gdev_x_free_dynamic_colors(gx_device_X *xdev)
467 {
468     if (xdev->cman.dynamic.colors) {
469 	int i;
470 	x11_color_t *xcp;
471 	x11_color_t *next;
472 
473 	for (i = 0; i < xdev->cman.dynamic.size; i++) {
474 	    for (xcp = xdev->cman.dynamic.colors[i]; xcp; xcp = next) {
475 		next = xcp->next;
476 		if (xcp->color.pad)
477 		    x_free_colors(xdev, &xcp->color.pixel, 1);
478 		gs_x_free(xdev->memory, xcp, "x11_dynamic_color");
479 	    }
480 	    xdev->cman.dynamic.colors[i] = NULL;
481 	}
482 	xdev->cman.dynamic.used = 0;
483     }
484 }
485 
486 /*
487  * Free storage and color map entries when closing the device.
488  * Uses and sets: cman.{std_cmap.map, dither_ramp, dynamic.colors,
489  * color_to_rgb}.  Uses: cman.std_cmap.free_map.
490  */
491 void
gdev_x_free_colors(gx_device_X * xdev)492 gdev_x_free_colors(gx_device_X *xdev)
493 {
494     if (xdev->cman.std_cmap.free_map) {
495 	/* XFree is declared as taking a char *, not a void *! */
496 	XFree((void *)xdev->cman.std_cmap.map);
497 	xdev->cman.std_cmap.free_map = false;
498     }
499     xdev->cman.std_cmap.map = 0;
500     if (xdev->cman.dither_ramp)
501 	gs_x_free(xdev->memory, xdev->cman.dither_ramp, "x11 dither_colors");
502     if (xdev->cman.dynamic.colors) {
503 	gdev_x_free_dynamic_colors(xdev);
504 	gs_x_free(xdev->memory, xdev->cman.dynamic.colors, "x11 cman.dynamic.colors");
505 	xdev->cman.dynamic.colors = NULL;
506     }
507     if (xdev->cman.color_to_rgb.values) {
508 	gs_x_free(xdev->memory, xdev->cman.color_to_rgb.values, "x11 color_to_rgb");
509 	xdev->cman.color_to_rgb.values = NULL;
510 	xdev->cman.color_to_rgb.size = 0;
511     }
512 }
513 
514 /* ---------------- Driver color mapping calls ---------------- */
515 
516 /* Define a table for computing N * X_max_color_value / D for 0 <= N <= D, */
517 /* 1 <= D <= 7. */
518 /* This requires a multiply and a divide otherwise; */
519 /* integer multiply and divide are slow on all platforms. */
520 #define CV_FRACTION(n, d) ((X_color_value)(X_max_color_value * (n) / (d)))
521 #define ND(n, d) CV_FRACTION(n, d)
522 static const X_color_value cv_tab1[] = {
523     ND(0,1), ND(1,1)
524 };
525 static const X_color_value cv_tab2[] = {
526     ND(0,2), ND(1,2), ND(2,2)
527 };
528 static const X_color_value cv_tab3[] = {
529     ND(0,3), ND(1,3), ND(2,3), ND(3,3)
530 };
531 static const X_color_value cv_tab4[] = {
532     ND(0,4), ND(1,4), ND(2,4), ND(3,4), ND(4,4)
533 };
534 static const X_color_value cv_tab5[] = {
535     ND(0,5), ND(1,5), ND(2,5), ND(3,5), ND(4,5), ND(5,5)
536 };
537 static const X_color_value cv_tab6[] = {
538     ND(0,6), ND(1,6), ND(2,6), ND(3,6), ND(4,6), ND(5,6), ND(6,6)
539 };
540 static const X_color_value cv_tab7[] = {
541     ND(0,7), ND(1,7), ND(2,7), ND(3,7), ND(4,7), ND(5,7), ND(6,7), ND(7,7)
542 };
543 #undef ND
544 static const X_color_value *const cv_tables[] =
545 {
546     0, cv_tab1, cv_tab2, cv_tab3, cv_tab4, cv_tab5, cv_tab6, cv_tab7
547 };
548 
549 /* Some C compilers don't declare the abs function in math.h. */
550 /* Provide one of our own. */
551 static inline int
iabs(int x)552 iabs(int x)
553 {
554     return (x < 0 ? -x : x);
555 }
556 
557 /* Map RGB values to a pixel value. */
558 gx_color_index
gdev_x_map_rgb_color(gx_device * dev,const gx_color_value cv[])559 gdev_x_map_rgb_color(gx_device * dev, const gx_color_value cv[])
560 {
561     gx_device_X *const xdev = (gx_device_X *) dev;
562     gx_color_value r = cv[0];
563     gx_color_value g = cv[1];
564     gx_color_value b = cv[2];
565 
566     /* X and ghostscript both use shorts for color values. */
567     /* Set drgb to the nearest color that the device can represent. */
568     X_color_value dr = r & xdev->cman.color_mask.red;
569     X_color_value dg = g & xdev->cman.color_mask.green;
570     X_color_value db = b & xdev->cman.color_mask.blue;
571 
572     {
573 	/* Foreground and background get special treatment: */
574 	/* They may be mapped to other colors. */
575 	/* Set mrgb to the color to be used for match testing. */
576 	X_color_value mr = r & xdev->cman.match_mask.red;
577 	X_color_value mg = g & xdev->cman.match_mask.green;
578 	X_color_value mb = b & xdev->cman.match_mask.blue;
579 
580 	if ((mr | mg | mb) == 0) {	/* i.e., all 0 */
581 	    if_debug4('C', "[cX]%u,%u,%u => foreground = %lu\n",
582 		      r, g, b, (ulong) xdev->foreground);
583 	    return xdev->foreground;
584 	}
585 	if (mr == xdev->cman.match_mask.red &&
586 	    mg == xdev->cman.match_mask.green &&
587 	    mb == xdev->cman.match_mask.blue
588 	    ) {
589 	    if_debug4('C', "[cX]%u,%u,%u => background = %lu\n",
590 		      r, g, b, (ulong) xdev->background);
591 	    return xdev->background;
592 	}
593     }
594 
595 #define CV_DENOM (gx_max_color_value + 1)
596 
597 #if HaveStdCMap
598     /* check the standard colormap first */
599     if (xdev->cman.std_cmap.map) {
600 	const XStandardColormap *cmap = xdev->cman.std_cmap.map;
601 
602 	if (gx_device_has_color(xdev)) {
603 	    uint cr, cg, cb;	/* rgb cube indices */
604 	    X_color_value cvr, cvg, cvb;	/* color value on cube */
605 
606 	    if (xdev->cman.std_cmap.fast) {
607 		cr = r >> xdev->cman.std_cmap.red.cv_shift;
608 		cvr = xdev->cman.std_cmap.red.nearest[cr];
609 		cg = g >> xdev->cman.std_cmap.green.cv_shift;
610 		cvg = xdev->cman.std_cmap.green.nearest[cg];
611 		cb = b >> xdev->cman.std_cmap.blue.cv_shift;
612 		cvb = xdev->cman.std_cmap.blue.nearest[cb];
613 	    } else {
614 		cr = r * (cmap->red_max + 1) / CV_DENOM;
615 		cg = g * (cmap->green_max + 1) / CV_DENOM;
616 		cb = b * (cmap->blue_max + 1) / CV_DENOM;
617 		cvr = X_max_color_value * cr / cmap->red_max;
618 		cvg = X_max_color_value * cg / cmap->green_max;
619 		cvb = X_max_color_value * cb / cmap->blue_max;
620 	    }
621 	    if ((iabs((int)r - (int)cvr) & xdev->cman.match_mask.red) == 0 &&
622 		(iabs((int)g - (int)cvg) & xdev->cman.match_mask.green) == 0 &&
623 		(iabs((int)b - (int)cvb) & xdev->cman.match_mask.blue) == 0) {
624 		gx_color_index pixel =
625 		    (xdev->cman.std_cmap.fast ?
626 		     (cr << xdev->cman.std_cmap.red.pixel_shift) +
627 		     (cg << xdev->cman.std_cmap.green.pixel_shift) +
628 		     (cb << xdev->cman.std_cmap.blue.pixel_shift) :
629 		     cr * cmap->red_mult + cg * cmap->green_mult +
630 		     cb * cmap->blue_mult) + cmap->base_pixel;
631 
632 		if_debug4('C', "[cX]%u,%u,%u (std cmap) => %lu\n",
633 			  r, g, b, pixel);  /* NB: gx_color_index size is 4 or 8 */
634 		return pixel;
635 	    }
636 	    if_debug3('C', "[cX]%u,%u,%u (std cmap fails)\n", r, g, b);
637 	} else {
638 	    uint cr;
639 	    X_color_value cvr;
640 
641 	    cr = r * (cmap->red_max + 1) / CV_DENOM;
642 	    cvr = X_max_color_value * cr / cmap->red_max;
643 	    if ((iabs((int)r - (int)cvr) & xdev->cman.match_mask.red) == 0) {
644 		gx_color_index pixel = cr * cmap->red_mult + cmap->base_pixel;
645 
646 		if_debug2('C', "[cX]%u (std cmap) => %lu\n", r, pixel);
647 		return pixel;
648 	    }
649 	    if_debug1('C', "[cX]%u (std cmap fails)\n", r);
650 	}
651     } else
652 #endif
653 
654 	/* If there is no standard colormap, check the dither cube/ramp */
655     if (xdev->cman.dither_ramp) {
656 	if (gx_device_has_color(xdev)) {
657 	    uint cr, cg, cb;	/* rgb cube indices */
658 	    X_color_value cvr, cvg, cvb;	/* color value on cube */
659 	    int dither_rgb = xdev->color_info.dither_colors;
660 	    uint max_rgb = dither_rgb - 1;
661 
662 	    cr = r * dither_rgb / CV_DENOM;
663 	    cg = g * dither_rgb / CV_DENOM;
664 	    cb = b * dither_rgb / CV_DENOM;
665 	    if (max_rgb < countof(cv_tables)) {
666 		const ushort *cv_tab = cv_tables[max_rgb];
667 
668 		cvr = cv_tab[cr];
669 		cvg = cv_tab[cg];
670 		cvb = cv_tab[cb];
671 	    } else {
672 		cvr = CV_FRACTION(cr, max_rgb);
673 		cvg = CV_FRACTION(cg, max_rgb);
674 		cvb = CV_FRACTION(cb, max_rgb);
675 	    }
676 	    if ((iabs((int)r - (int)cvr) & xdev->cman.match_mask.red) == 0 &&
677 		(iabs((int)g - (int)cvg) & xdev->cman.match_mask.green) == 0 &&
678 		(iabs((int)b - (int)cvb) & xdev->cman.match_mask.blue) == 0) {
679 		gx_color_index pixel =
680 		    xdev->cman.dither_ramp[CUBE_INDEX(cr, cg, cb)];
681 
682 		if_debug4('C', "[cX]%u,%u,%u (dither cube) => %lu\n",
683 			  r, g, b, pixel);
684 		return pixel;
685 	    }
686 	    if_debug3('C', "[cX]%u,%u,%u (dither cube fails)\n", r, g, b);
687 	} else {
688 	    uint cr;
689 	    X_color_value cvr;
690 	    int dither_grays = xdev->color_info.dither_grays;
691 	    uint max_gray = dither_grays - 1;
692 
693 	    cr = r * dither_grays / CV_DENOM;
694 	    cvr = (X_max_color_value * cr / max_gray);
695 	    if ((iabs((int)r - (int)cvr) & xdev->cman.match_mask.red) == 0) {
696 		gx_color_index pixel = xdev->cman.dither_ramp[cr];
697 
698 		if_debug2('C', "[cX]%u (dither ramp) => %lu\n", r, pixel);
699 		return pixel;
700 	    }
701 	    if_debug1('C', "[cX]%u (dither ramp fails)\n", r);
702 	}
703     }
704 
705     /* Finally look through the list of dynamic colors */
706     if (xdev->cman.dynamic.colors) {
707 	int i = (dr ^ dg ^ db) >> xdev->cman.dynamic.shift;
708 	x11_color_t *xcp = xdev->cman.dynamic.colors[i];
709 	x11_color_t *prev = NULL;
710 	XColor xc;
711 
712 	for (; xcp; prev = xcp, xcp = xcp->next)
713 	    if (xcp->color.red == dr && xcp->color.green == dg &&
714 		xcp->color.blue == db) {
715 		/* Promote the found entry to the front of the list. */
716 		if (prev) {
717 		    prev->next = xcp->next;
718 		    xcp->next = xdev->cman.dynamic.colors[i];
719 		    xdev->cman.dynamic.colors[i] = xcp;
720 		}
721 		if (xcp->color.pad) {
722 		    if_debug4('C', "[cX]%u,%u,%u (dynamic) => %lu\n",
723 			      r, g, b, (ulong) xcp->color.pixel);
724 		    return xcp->color.pixel;
725 		} else {
726 		    if_debug3('C', "[cX]%u,%u,%u (dynamic) => missing\n",
727 			      r, g, b);
728 		    return gx_no_color_index;
729 		}
730 	    }
731 
732 	/* If not in our list of dynamic colors, */
733 	/* ask the X server and add an entry. */
734 	/* First check if dynamic table is exhausted */
735 	if (xdev->cman.dynamic.used > xdev->cman.dynamic.max_used) {
736 	    if_debug3('C', "[cX]%u,%u,%u (dynamic) => full\n", r, g, b);
737 	    return gx_no_color_index;
738 	}
739 	xcp = (x11_color_t *)
740 	    gs_malloc(xdev->memory, sizeof(x11_color_t), 1, "x11_dynamic_color");
741 	if (!xcp)
742 	    return gx_no_color_index;
743 	xc.red = xcp->color.red = dr;
744 	xc.green = xcp->color.green = dg;
745 	xc.blue = xcp->color.blue = db;
746 	xcp->next = xdev->cman.dynamic.colors[i];
747 	xdev->cman.dynamic.colors[i] = xcp;
748 	xdev->cman.dynamic.used++;
749 	if (x_alloc_color(xdev, &xc)) {
750 	    xcp->color.pixel = xc.pixel;
751 	    xcp->color.pad = true;
752 	    if_debug5('c', "[cX]0x%x,0x%x,0x%x (dynamic) => added [%d]%lu\n",
753 		      dr, dg, db, xdev->cman.dynamic.used - 1,
754 		      (ulong)xc.pixel);
755 	    return xc.pixel;
756 	} else {
757 	    xcp->color.pad = false;
758 	    if_debug3('c', "[cX]0x%x,0x%x,0x%x (dynamic) => can't alloc\n",
759 		      dr, dg, db);
760 	    return gx_no_color_index;
761 	}
762     }
763     if_debug3('C', "[cX]%u,%u,%u fails\n", r, g, b);
764     return gx_no_color_index;
765 #undef CV_DENOM
766 }
767 
768 
769 /* Map a pixel value back to r-g-b. */
770 int
gdev_x_map_color_rgb(gx_device * dev,gx_color_index color,gx_color_value prgb[3])771 gdev_x_map_color_rgb(gx_device * dev, gx_color_index color,
772 		     gx_color_value prgb[3])
773 {
774     const gx_device_X *const xdev = (const gx_device_X *) dev;
775 #if HaveStdCMap
776     const XStandardColormap *cmap = xdev->cman.std_cmap.map;
777 #endif
778 
779     if (color == xdev->foreground) {
780 	prgb[0] = prgb[1] = prgb[2] = 0;
781 	return 0;
782     }
783     if (color == xdev->background) {
784 	prgb[0] = prgb[1] = prgb[2] = gx_max_color_value;
785 	return 0;
786     }
787     if (color < xdev->cman.color_to_rgb.size) {
788 	const x11_rgb_t *pxrgb = &xdev->cman.color_to_rgb.values[color];
789 
790 	if (pxrgb->defined) {
791 	    prgb[0] = pxrgb->rgb[0];
792 	    prgb[1] = pxrgb->rgb[1];
793 	    prgb[2] = pxrgb->rgb[2];
794 	    return 0;
795 	}
796 #if HaveStdCMap
797     }
798 
799     /* Check the standard colormap. */
800     if (cmap) {
801 	if (color >= cmap->base_pixel) {
802 	    x_pixel value = color - cmap->base_pixel;
803 	    uint r = (value / cmap->red_mult) % (cmap->red_max + 1);
804 	    uint g = (value / cmap->green_mult) % (cmap->green_max + 1);
805 	    uint b = (value / cmap->blue_mult) % (cmap->blue_max + 1);
806 
807 	    if (value == r * cmap->red_mult + g * cmap->green_mult +
808 		b * cmap->blue_mult) {
809 		/* When mapping color buckets back to specific colors,
810 		 * we can choose to map them to the darkest shades
811 		 * (e.g., 0, 1/3, 2/3), to the lightest shades (e.g.,
812 		 * 1/3-epsilon, 2/3-epsilon, 1-epsilon), to the middle
813 		 * shades (e.g., 1/6, 1/2, 5/6), or for maximum range
814 		 * (e.g., 0, 1/2, 1).  The last of these matches the
815 		 * assumptions of the halftoning code, so that is what
816 		 * we choose.
817 		 */
818 		prgb[0] = r * gx_max_color_value / cmap->red_max;
819 		prgb[1] = g * gx_max_color_value / cmap->green_max;
820 		prgb[2] = b * gx_max_color_value / cmap->blue_max;
821 		return 0;
822 	    }
823 	}
824     }
825     if (color < xdev->cman.color_to_rgb.size) {
826 #endif
827 	/* Error -- undefined pixel value. */
828 	return_error(gs_error_unknownerror);
829     }
830     /*
831      * Check the dither cube/ramp.  This is hardly ever used, since if
832      * there are few enough colors to require dithering, the pixel values
833      * are likely to be small enough to index color_to_rgb.
834      */
835     if (xdev->cman.dither_ramp) {
836 	if (gx_device_has_color(xdev)) {
837 	    int size = xdev->color_info.dither_colors;
838 	    int size3 = size * size * size;
839 	    int i;
840 
841 	    for (i = 0; i < size3; ++i)
842 		if (xdev->cman.dither_ramp[i] == color) {
843 		    uint max_rgb = size - 1;
844 		    uint q = i / size,
845 			r = q / size,
846 			g = q % size,
847 			b = i % size;
848 
849 		    /*
850 		     * See above regarding the choice of color mapping
851 		     * algorithm.
852 		     */
853 		    prgb[0] = r * gx_max_color_value / max_rgb;
854 		    prgb[1] = g * gx_max_color_value / max_rgb;
855 		    prgb[2] = b * gx_max_color_value / max_rgb;
856 		    return 0;
857 		}
858 	} else {
859 	    int size = xdev->color_info.dither_grays;
860 	    int i;
861 
862 	    for (i = 0; i < size; ++i)
863 		if (xdev->cman.dither_ramp[i] == color) {
864 		    prgb[0] = prgb[1] = prgb[2] =
865 			i * gx_max_color_value / (size - 1);
866 		    return 0;
867 		}
868 	}
869     }
870 
871     /* Finally, search the list of dynamic colors. */
872     if (xdev->cman.dynamic.colors) {
873 	int i;
874 	const x11_color_t *xcp;
875 
876 	for (i = xdev->cman.dynamic.size; --i >= 0;)
877 	    for (xcp = xdev->cman.dynamic.colors[i]; xcp; xcp = xcp->next)
878 		if (xcp->color.pixel == color && xcp->color.pad) {
879 		    prgb[0] = xcp->color.red;
880 		    prgb[1] = xcp->color.green;
881 		    prgb[2] = xcp->color.blue;
882 		    return 0;
883 		}
884     }
885 
886     /* Not found -- not possible! */
887     return_error(gs_error_unknownerror);
888 }
889