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