xref: /plan9/sys/src/cmd/gs/src/gsht.c (revision 593dc095aefb2a85c828727bbfa9da139a49bdf4)
1 /* Copyright (C) 1989, 1996, 1997, 1998, 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: gsht.c,v 1.23 2005/03/14 18:08:36 dan Exp $ */
18 /* setscreen operator for Ghostscript library */
19 #include "memory_.h"
20 #include "string_.h"
21 #include <stdlib.h>		/* for qsort */
22 #include "gx.h"
23 #include "gserrors.h"
24 #include "gsstruct.h"
25 #include "gsutil.h"		/* for gs_next_ids */
26 #include "gxarith.h"		/* for igcd */
27 #include "gzstate.h"
28 #include "gxdevice.h"		/* for gzht.h */
29 #include "gzht.h"
30 #include "gswts.h"
31 
32 /* Forward declarations */
33 void gx_set_effective_transfer(gs_state *);
34 
35 /*
36  * *HACK ALERT*
37  *
38  * Value stored in the width field of a well-tempered screen halftone
39  * order, to indicate that the wts field of this order points to the
40  * same structure as an earlier order. This is used to suppress
41  * multiple realeases of shared wts_screen_t orders.
42  *
43  * The width field is available for this purpose at it is nominally
44  * unused in a well-tempered screening halftone.
45  */
46 private const ushort    ht_wts_suppress_release = (ushort)(-1);
47 
48 
49 /* Structure types */
50 public_st_ht_order();
51 private_st_ht_order_component();
52 public_st_ht_order_comp_element();
53 public_st_halftone();
54 public_st_device_halftone();
55 
56 /* GC procedures */
57 
58 private
59 ENUM_PTRS_WITH(ht_order_enum_ptrs, gx_ht_order *porder) return 0;
60 case 0: ENUM_RETURN((porder->data_memory ? porder->levels : 0));
61 case 1: ENUM_RETURN((porder->data_memory ? porder->bit_data : 0));
62 case 2: ENUM_RETURN(porder->cache);
63 case 3: ENUM_RETURN(porder->transfer);
64 ENUM_PTRS_END
65 private
RELOC_PTRS_WITH(ht_order_reloc_ptrs,gx_ht_order * porder)66 RELOC_PTRS_WITH(ht_order_reloc_ptrs, gx_ht_order *porder)
67 {
68     if (porder->data_memory) {
69 	RELOC_VAR(porder->levels);
70 	RELOC_VAR(porder->bit_data);
71     }
72     RELOC_VAR(porder->cache);
73     RELOC_VAR(porder->transfer);
74 }
75 RELOC_PTRS_END
76 
77 private
78 ENUM_PTRS_WITH(halftone_enum_ptrs, gs_halftone *hptr) return 0;
79 case 0:
80 switch (hptr->type)
81 {
82     case ht_type_spot:
83 	ENUM_RETURN((hptr->params.spot.transfer == 0 ?
84 		     hptr->params.spot.transfer_closure.data :
85 		     0));
86     case ht_type_threshold:
87 	ENUM_RETURN_CONST_STRING_PTR(gs_halftone, params.threshold.thresholds);
88     case ht_type_threshold2:
89 	return ENUM_CONST_BYTESTRING(&hptr->params.threshold2.thresholds);
90     case ht_type_client_order:
91 	ENUM_RETURN(hptr->params.client_order.client_data);
92     case ht_type_multiple:
93     case ht_type_multiple_colorscreen:
94 	ENUM_RETURN(hptr->params.multiple.components);
95     case ht_type_none:
96     case ht_type_screen:
97     case ht_type_colorscreen:
98 	return 0;
99 }
100 case 1:
101 switch (hptr->type) {
102     case ht_type_threshold:
103 	ENUM_RETURN((hptr->params.threshold.transfer == 0 ?
104 		     hptr->params.threshold.transfer_closure.data :
105 		     0));
106     case ht_type_threshold2:
107 	ENUM_RETURN(hptr->params.threshold2.transfer_closure.data);
108     case ht_type_client_order:
109 	ENUM_RETURN(hptr->params.client_order.transfer_closure.data);
110     default:
111 	return 0;
112 }
113 ENUM_PTRS_END
114 
RELOC_PTRS_WITH(halftone_reloc_ptrs,gs_halftone * hptr)115 private RELOC_PTRS_WITH(halftone_reloc_ptrs, gs_halftone *hptr)
116 {
117     switch (hptr->type) {
118 	case ht_type_spot:
119 	    if (hptr->params.spot.transfer == 0)
120 		RELOC_PTR(gs_halftone, params.spot.transfer_closure.data);
121 	    break;
122 	case ht_type_threshold:
123 	    RELOC_CONST_STRING_PTR(gs_halftone, params.threshold.thresholds);
124 	    if (hptr->params.threshold.transfer == 0)
125 		RELOC_PTR(gs_halftone, params.threshold.transfer_closure.data);
126 	    break;
127 	case ht_type_threshold2:
128 	    RELOC_CONST_BYTESTRING_VAR(hptr->params.threshold2.thresholds);
129 	    RELOC_OBJ_VAR(hptr->params.threshold2.transfer_closure.data);
130 	    break;
131 	case ht_type_client_order:
132 	    RELOC_PTR(gs_halftone, params.client_order.client_data);
133 	    RELOC_PTR(gs_halftone, params.client_order.transfer_closure.data);
134 	    break;
135 	case ht_type_multiple:
136 	case ht_type_multiple_colorscreen:
137 	    RELOC_PTR(gs_halftone, params.multiple.components);
138 	    break;
139 	case ht_type_none:
140 	case ht_type_screen:
141 	case ht_type_colorscreen:
142 	    break;
143     }
144 }
145 RELOC_PTRS_END
146 
147 /* setscreen */
148 int
gs_setscreen(gs_state * pgs,gs_screen_halftone * phsp)149 gs_setscreen(gs_state * pgs, gs_screen_halftone * phsp)
150 {
151     gs_screen_enum senum;
152     int code = gx_ht_process_screen(&senum, pgs, phsp,
153 				    gs_currentaccuratescreens());
154 
155     if (code < 0)
156 	return code;
157     return gs_screen_install(&senum);
158 }
159 
160 /* currentscreen */
161 int
gs_currentscreen(const gs_state * pgs,gs_screen_halftone * phsp)162 gs_currentscreen(const gs_state * pgs, gs_screen_halftone * phsp)
163 {
164     switch (pgs->halftone->type) {
165 	case ht_type_screen:
166 	    *phsp = pgs->halftone->params.screen;
167 	    return 0;
168 	case ht_type_colorscreen:
169 	    *phsp = pgs->halftone->params.colorscreen.screens.colored.gray;
170 	    return 0;
171 	default:
172 	    return_error(gs_error_undefined);
173     }
174 }
175 
176 /* .currentscreenlevels */
177 int
gs_currentscreenlevels(const gs_state * pgs)178 gs_currentscreenlevels(const gs_state * pgs)
179 {
180     int gi = 0;
181 
182     if (pgs->device != 0)
183         gi = pgs->device->color_info.gray_index;
184     if (gi != GX_CINFO_COMP_NO_INDEX)
185         return pgs->dev_ht->components[gi].corder.num_levels;
186     else
187         return pgs->dev_ht->components[0].corder.num_levels;
188 }
189 
190 /* .setscreenphase */
191 int
gx_imager_setscreenphase(gs_imager_state * pis,int x,int y,gs_color_select_t select)192 gx_imager_setscreenphase(gs_imager_state * pis, int x, int y,
193 			 gs_color_select_t select)
194 {
195     if (select == gs_color_select_all) {
196 	int i;
197 
198 	for (i = 0; i < gs_color_select_count; ++i)
199 	    gx_imager_setscreenphase(pis, x, y, (gs_color_select_t) i);
200 	return 0;
201     } else if (select < 0 || select >= gs_color_select_count)
202 	return_error(gs_error_rangecheck);
203     pis->screen_phase[select].x = x;
204     pis->screen_phase[select].y = y;
205     return 0;
206 }
207 int
gs_setscreenphase(gs_state * pgs,int x,int y,gs_color_select_t select)208 gs_setscreenphase(gs_state * pgs, int x, int y, gs_color_select_t select)
209 {
210     int code = gx_imager_setscreenphase((gs_imager_state *) pgs, x, y,
211 					select);
212 
213     /*
214      * If we're only setting the source phase, we don't need to do
215      * unset_dev_color, because the source phase doesn't affect painting
216      * with the current color.
217      */
218     if (code >= 0 && (select == gs_color_select_texture ||
219 		      select == gs_color_select_all)
220 	)
221 	gx_unset_dev_color(pgs);
222     return code;
223 }
224 
225 int
gs_currentscreenphase_pis(const gs_imager_state * pis,gs_int_point * pphase,gs_color_select_t select)226 gs_currentscreenphase_pis(const gs_imager_state * pis, gs_int_point * pphase,
227 		      gs_color_select_t select)
228 {
229     if (select < 0 || select >= gs_color_select_count)
230 	return_error(gs_error_rangecheck);
231     *pphase = pis->screen_phase[select];
232     return 0;
233 }
234 
235 /* .currentscreenphase */
236 int
gs_currentscreenphase(const gs_state * pgs,gs_int_point * pphase,gs_color_select_t select)237 gs_currentscreenphase(const gs_state * pgs, gs_int_point * pphase,
238 		      gs_color_select_t select)
239 {
240     return gs_currentscreenphase_pis((const gs_imager_state *)pgs, pphase, select);
241 }
242 
243 /* currenthalftone */
244 int
gs_currenthalftone(gs_state * pgs,gs_halftone * pht)245 gs_currenthalftone(gs_state * pgs, gs_halftone * pht)
246 {
247     *pht = *pgs->halftone;
248     return 0;
249 }
250 
251 /* ------ Internal routines ------ */
252 
253 /* Process one screen plane. */
254 int
gx_ht_process_screen_memory(gs_screen_enum * penum,gs_state * pgs,gs_screen_halftone * phsp,bool accurate,gs_memory_t * mem)255 gx_ht_process_screen_memory(gs_screen_enum * penum, gs_state * pgs,
256 		gs_screen_halftone * phsp, bool accurate, gs_memory_t * mem)
257 {
258     gs_point pt;
259     int code = gs_screen_init_memory(penum, pgs, phsp, accurate, mem);
260 
261     if (code < 0)
262 	return code;
263     while ((code = gs_screen_currentpoint(penum, &pt)) == 0)
264 	if ((code = gs_screen_next(penum, (*phsp->spot_function) (pt.x, pt.y))) < 0)
265 	    return code;
266     return 0;
267 }
268 
269 /*
270  * Internal procedure to allocate and initialize either an internally
271  * generated or a client-defined halftone order.  For spot halftones,
272  * the client is responsible for calling gx_compute_cell_values.
273  *
274  * Note: this function is used for old-style halftones only. WTS
275  * halftones are allocated in gs_sethalftone_try_wts().
276  */
277 int
gx_ht_alloc_ht_order(gx_ht_order * porder,uint width,uint height,uint num_levels,uint num_bits,uint strip_shift,const gx_ht_order_procs_t * procs,gs_memory_t * mem)278 gx_ht_alloc_ht_order(gx_ht_order * porder, uint width, uint height,
279 		     uint num_levels, uint num_bits, uint strip_shift,
280 		     const gx_ht_order_procs_t *procs, gs_memory_t * mem)
281 {
282     porder->wse = NULL;
283     porder->wts = NULL;
284     porder->width = width;
285     porder->height = height;
286     porder->raster = bitmap_raster(width);
287     porder->shift = strip_shift;
288     porder->orig_height = porder->height;
289     porder->orig_shift = porder->shift;
290     porder->full_height = ht_order_full_height(porder);
291     porder->num_levels = num_levels;
292     porder->num_bits = num_bits;
293     porder->procs = procs;
294     porder->data_memory = mem;
295 
296     if (num_levels > 0) {
297         porder->levels =
298 	    (uint *)gs_alloc_byte_array(mem, porder->num_levels, sizeof(uint),
299 				        "alloc_ht_order_data(levels)");
300 	if (porder->levels == 0)
301 	    return_error(gs_error_VMerror);
302     } else
303 	porder->levels = 0;
304 
305     if (num_bits > 0) {
306 	porder->bit_data =
307 	    gs_alloc_byte_array(mem, porder->num_bits,
308 			        porder->procs->bit_data_elt_size,
309 			        "alloc_ht_order_data(bit_data)");
310 	if (porder->bit_data == 0) {
311 	    gs_free_object(mem, porder->levels, "alloc_ht_order_data(levels)");
312 	    porder->levels = 0;
313 	    return_error(gs_error_VMerror);
314 	}
315     } else
316 	porder->bit_data = 0;
317 
318     porder->cache = 0;
319     porder->transfer = 0;
320     return 0;
321 }
322 
323 /*
324  * Procedure to copy a halftone order.
325  */
326 private int
gx_ht_copy_ht_order(gx_ht_order * pdest,gx_ht_order * psrc,gs_memory_t * mem)327 gx_ht_copy_ht_order(gx_ht_order * pdest, gx_ht_order * psrc, gs_memory_t * mem)
328 {
329     int code;
330 
331     *pdest = *psrc;
332 
333     code = gx_ht_alloc_ht_order(pdest, psrc->width, psrc->height,
334 		     psrc->num_levels, psrc->num_bits, psrc->shift,
335 		     psrc->procs, mem);
336     if (code < 0)
337 	return code;
338     if (pdest->levels != 0)
339         memcpy(pdest->levels, psrc->levels, psrc->num_levels * sizeof(uint));
340     if (pdest->bit_data != 0)
341         memcpy(pdest->bit_data, psrc->bit_data,
342 		psrc->num_bits * psrc->procs->bit_data_elt_size);
343     pdest->wse = psrc->wse;
344     pdest->transfer = psrc->transfer;
345     rc_increment(pdest->transfer);
346     return 0;
347 }
348 
349 /*
350  * Set the destination component to match the source component, and
351  * "assume ownership" of all of the refrernced data structures.
352  */
353 private void
gx_ht_move_ht_order(gx_ht_order * pdest,gx_ht_order * psrc)354 gx_ht_move_ht_order(gx_ht_order * pdest, gx_ht_order * psrc)
355 {
356     uint    width = psrc->width, height = psrc->height, shift = psrc->shift;
357 
358     pdest->params = psrc->params;
359     pdest->wse = psrc->wse;
360     pdest->wts = 0;
361     pdest->width = width;
362     pdest->height = height;
363     pdest->raster = bitmap_raster(width);
364     pdest->shift = shift;
365     pdest->orig_height = height;
366     pdest->orig_shift = shift;
367     pdest->full_height = ht_order_full_height(pdest);
368     pdest->num_levels = psrc->num_levels;
369     pdest->num_bits = psrc->num_bits;
370     pdest->procs = psrc->procs;
371     pdest->data_memory = psrc->data_memory;
372     pdest->levels = psrc->levels;
373     pdest->bit_data = psrc->bit_data;
374     pdest->cache = psrc->cache;    /* should be 0 */
375     pdest->transfer = psrc->transfer;
376 }
377 
378 
379 /* Allocate and initialize the contents of a halftone order. */
380 /* The client must have set the defining values in porder->params. */
381 int
gx_ht_alloc_order(gx_ht_order * porder,uint width,uint height,uint strip_shift,uint num_levels,gs_memory_t * mem)382 gx_ht_alloc_order(gx_ht_order * porder, uint width, uint height,
383 		  uint strip_shift, uint num_levels, gs_memory_t * mem)
384 {
385     gx_ht_order order;
386     int code;
387 
388     order = *porder;
389     gx_compute_cell_values(&order.params);
390     code = gx_ht_alloc_ht_order(&order, width, height, num_levels,
391 				width * height, strip_shift,
392 				&ht_order_procs_default, mem);
393     if (code < 0)
394 	return code;
395     *porder = order;
396     return 0;
397 }
398 
399 /*
400  * Allocate and initialize a threshold order, which may use the short
401  * representation.
402  */
403 int
gx_ht_alloc_threshold_order(gx_ht_order * porder,uint width,uint height,uint num_levels,gs_memory_t * mem)404 gx_ht_alloc_threshold_order(gx_ht_order * porder, uint width, uint height,
405 			    uint num_levels, gs_memory_t * mem)
406 {
407     gx_ht_order order;
408     uint num_bits = width * height;
409     const gx_ht_order_procs_t *procs =
410 	(num_bits > 2000 && num_bits <= max_ushort ?
411 	 &ht_order_procs_short : &ht_order_procs_default);
412     int code;
413 
414     order = *porder;
415     gx_compute_cell_values(&order.params);
416     code = gx_ht_alloc_ht_order(&order, width, height, num_levels,
417 				width * height, 0, procs, mem);
418     if (code < 0)
419 	return code;
420     *porder = order;
421     return 0;
422 }
423 
424 /* Allocate and initialize the contents of a client-defined halftone order. */
425 int
gx_ht_alloc_client_order(gx_ht_order * porder,uint width,uint height,uint num_levels,uint num_bits,gs_memory_t * mem)426 gx_ht_alloc_client_order(gx_ht_order * porder, uint width, uint height,
427 			 uint num_levels, uint num_bits, gs_memory_t * mem)
428 {
429     gx_ht_order order;
430     int code;
431 
432     order = *porder;
433     order.params.M = width, order.params.N = 0;
434     order.params.R = 1;
435     order.params.M1 = height, order.params.N1 = 0;
436     order.params.R1 = 1;
437     gx_compute_cell_values(&order.params);
438     code = gx_ht_alloc_ht_order(&order, width, height, num_levels,
439 				num_bits, 0, &ht_order_procs_default, mem);
440     if (code < 0)
441 	return code;
442     *porder = order;
443     return 0;
444 }
445 
446 /* Compare keys ("masks", actually sample values) for qsort. */
447 private int
compare_samples(const void * p1,const void * p2)448 compare_samples(const void *p1, const void *p2)
449 {
450     ht_sample_t m1 = ((const gx_ht_bit *)p1)->mask;
451     ht_sample_t m2 = ((const gx_ht_bit *)p2)->mask;
452 
453     return (m1 < m2 ? -1 : m1 > m2 ? 1 : 0);
454 }
455 /* Sort the halftone order by sample value. */
456 void
gx_sort_ht_order(gx_ht_bit * recs,uint N)457 gx_sort_ht_order(gx_ht_bit * recs, uint N)
458 {
459     int i;
460 
461     /* Tag each sample with its index, for sorting. */
462     for (i = 0; i < N; i++)
463 	recs[i].offset = i;
464     qsort((void *)recs, N, sizeof(*recs), compare_samples);
465 #ifdef DEBUG
466     if (gs_debug_c('H')) {
467 	uint i;
468 
469 	dlputs("[H]Sorted samples:\n");
470 	for (i = 0; i < N; i++)
471 	    dlprintf3("%5u: %5u: %u\n",
472 		      i, recs[i].offset, recs[i].mask);
473     }
474 #endif
475 }
476 
477 /*
478  * Construct the halftone order from a sampled spot function.  Only width x
479  * strip samples have been filled in; we must replicate the resulting sorted
480  * order vertically, shifting it by shift each time.  See gxdht.h regarding
481  * the invariants that must be restored.
482  */
483 void
gx_ht_construct_spot_order(gx_ht_order * porder)484 gx_ht_construct_spot_order(gx_ht_order * porder)
485 {
486     uint width = porder->width;
487     uint num_levels = porder->num_levels;	/* = width x strip */
488     uint strip = num_levels / width;
489     gx_ht_bit *bits = (gx_ht_bit *)porder->bit_data;
490     uint *levels = porder->levels;
491     uint shift = porder->orig_shift;
492     uint full_height = porder->full_height;
493     uint num_bits = porder->num_bits;
494     uint copies = num_bits / (width * strip);
495     gx_ht_bit *bp = bits + num_bits - 1;
496     uint i;
497 
498     gx_sort_ht_order(bits, num_levels);
499     if_debug5('h',
500 	      "[h]spot order: num_levels=%u w=%u h=%u strip=%u shift=%u\n",
501 	      num_levels, width, porder->orig_height, strip, shift);
502     /* Fill in the levels array, replicating the bits vertically */
503     /* if needed. */
504     for (i = num_levels; i > 0;) {
505 	uint offset = bits[--i].offset;
506 	uint x = offset % width;
507 	uint hy = offset - x;
508 	uint k;
509 
510 	levels[i] = i * copies;
511 	for (k = 0; k < copies;
512 	     k++, bp--, hy += num_levels, x = (x + width - shift) % width
513 	    )
514 	    bp->offset = hy + x;
515     }
516     /* If we have a complete halftone, restore the invariant. */
517     if (num_bits == width * full_height) {
518 	porder->height = full_height;
519 	porder->shift = 0;
520     }
521     gx_ht_construct_bits(porder);
522 }
523 
524 /* Construct a single offset/mask. */
525 void
gx_ht_construct_bit(gx_ht_bit * bit,int width,int bit_num)526 gx_ht_construct_bit(gx_ht_bit * bit, int width, int bit_num)
527 {
528     uint padding = bitmap_raster(width) * 8 - width;
529     int pix = bit_num;
530     ht_mask_t mask;
531     byte *pb;
532 
533     pix += pix / width * padding;
534     bit->offset = (pix >> 3) & -size_of(mask);
535     mask = (ht_mask_t) 1 << (~pix & (ht_mask_bits - 1));
536     /* Replicate the mask bits. */
537     pix = ht_mask_bits - width;
538     while ((pix -= width) >= 0)
539 	mask |= mask >> width;
540     /* Store the mask, reversing bytes if necessary. */
541     bit->mask = 0;
542     for (pb = (byte *) & bit->mask + (sizeof(mask) - 1);
543 	 mask != 0;
544 	 mask >>= 8, pb--
545 	)
546 	*pb = (byte) mask;
547 }
548 
549 /* Construct offset/masks from the whitening order. */
550 /* porder->bits[i].offset contains the index of the bit position */
551 /* that is i'th in the whitening order. */
552 void
gx_ht_construct_bits(gx_ht_order * porder)553 gx_ht_construct_bits(gx_ht_order * porder)
554 {
555     uint i;
556     gx_ht_bit *phb;
557 
558     for (i = 0, phb = (gx_ht_bit *)porder->bit_data;
559 	 i < porder->num_bits;
560 	 i++, phb++)
561 	gx_ht_construct_bit(phb, porder->width, phb->offset);
562 #ifdef DEBUG
563     if (gs_debug_c('H')) {
564 	dlprintf1("[H]Halftone order bits 0x%lx:\n", (ulong)porder->bit_data);
565 	for (i = 0, phb = (gx_ht_bit *)porder->bit_data;
566 	     i < porder->num_bits;
567 	     i++, phb++)
568 	    dlprintf3("%4d: %u:0x%lx\n", i, phb->offset,
569 		      (ulong) phb->mask);
570     }
571 #endif
572 }
573 
574 /* Release a gx_device_halftone by freeing its components. */
575 /* (Don't free the gx_device_halftone itself.) */
576 void
gx_ht_order_release(gx_ht_order * porder,gs_memory_t * mem,bool free_cache)577 gx_ht_order_release(gx_ht_order * porder, gs_memory_t * mem, bool free_cache)
578 {
579     /* "free cache" is a proxy for "differs from default" */
580     if (free_cache) {
581         if (porder->cache != 0)
582             gx_ht_free_cache(mem, porder->cache);
583         else if (porder->wse != 0)
584             gs_wts_free_enum(porder->wse);
585     }
586     porder->cache = 0;
587     if (porder->wts != 0 && porder->width != ht_wts_suppress_release)
588         gs_wts_free_screen(porder->wts);
589     porder->wts = 0;
590     rc_decrement(porder->transfer, "gx_ht_order_release(transfer)");
591     porder->transfer = 0;
592     if (porder->data_memory != 0) {
593 	gs_free_object(porder->data_memory, porder->bit_data,
594 		       "gx_ht_order_release(bit_data)");
595 	gs_free_object(porder->data_memory, porder->levels,
596 		       "gx_ht_order_release(levels)");
597     }
598     porder->levels = 0;
599     porder->bit_data = 0;
600 }
601 
602 void
gx_device_halftone_release(gx_device_halftone * pdht,gs_memory_t * mem)603 gx_device_halftone_release(gx_device_halftone * pdht, gs_memory_t * mem)
604 {
605     if (pdht->components) {
606 	int i;
607 
608 	/* One of the components might be the same as the default */
609 	/* order, so check that we don't free it twice. */
610 	for (i = 0; i < pdht->num_comp; ++i)
611 	    if (pdht->components[i].corder.bit_data !=
612 		pdht->order.bit_data
613 		) {		/* Currently, all orders except the default one */
614 		/* own their caches. */
615 		gx_ht_order_release(&pdht->components[i].corder, mem, true);
616 	    }
617 	gs_free_object(mem, pdht->components,
618 		       "gx_dev_ht_release(components)");
619 	pdht->components = 0;
620 	pdht->num_comp = 0;
621     }
622     gx_ht_order_release(&pdht->order, mem, false);
623 }
624 
625 /*
626  * This routine will take a color name (defined by a ptr and size) and
627  * check if this is a valid colorant name for the current device.  If
628  * so then the device's colorant number is returned.
629  *
630  * Two other checks are also made.  If the name is "Default" then a value
631  * of GX_DEVICE_COLOR_MAX_COMPONENTS is returned.  This is done to
632  * simplify the handling of default halftones.  Note:  The device also
633  * uses GX_DEVICE_COLOR_MAX_COMPONENTS to indicate colorants which are
634  * known but not being used due to the SeparationOrder parameter.  In this
635  * case we return -1 since the colorant is not currently being used by the
636  * device.
637  *
638  * If the halftone type is colorscreen or multiple colorscreen, then we
639  * also check for Red/Cyan, Green/Magenta, Blue/Yellow, and Gray/Black
640  * component name pairs.  This is done since the setcolorscreen and
641  * sethalftone types 2 and 4 imply the dual name sets.
642  *
643  * A negative value is returned if the color name is not found.
644  */
645 int
gs_color_name_component_number(gx_device * dev,const char * pname,int name_size,int halftonetype)646 gs_color_name_component_number(gx_device * dev, const char * pname,
647 				int name_size, int halftonetype)
648 {
649     int num_colorant;
650 
651 #define check_colorant_name(dev, name) \
652     ((*dev_proc(dev, get_color_comp_index)) (dev, name, strlen(name), NO_COMP_NAME_TYPE))
653 
654 #define check_colorant_name_length(dev, name, length) \
655     ((*dev_proc(dev, get_color_comp_index)) (dev, name, length, NO_COMP_NAME_TYPE))
656 
657 #define check_name(str, pname, length) \
658     ((strlen(str) == length) && (strncmp(pname, str, length) == 0))
659 
660     /*
661      * Check if this is a device colorant.
662      */
663     num_colorant = check_colorant_name_length(dev, pname, name_size);
664     if (num_colorant >= 0) {
665 	/*
666 	 * The device will return GX_DEVICE_COLOR_MAX_COMPONENTS if the
667 	 * colorant is logically present in the device but not being used
668 	 * because a SeparationOrder parameter is specified.  Since we are
669 	 * using this value to indicate 'Default', we use -1 to indicate
670 	 * that the colorant is not really being used.
671 	 */
672 	if (num_colorant == GX_DEVICE_COLOR_MAX_COMPONENTS)
673 	    num_colorant = -1;
674 	return num_colorant;
675     }
676 
677     /*
678      * Check if this is the default component
679      */
680     if (check_name("Default", pname, name_size))
681 	return GX_DEVICE_COLOR_MAX_COMPONENTS;
682 
683     /* Halftones set by setcolorscreen, and (we think) */
684     /* Type 2 and Type 4 halftones, are supposed to work */
685     /* for both RGB and CMYK, so we need a special check here. */
686     if (halftonetype == ht_type_colorscreen ||
687 	halftonetype == ht_type_multiple_colorscreen) {
688 	if (check_name("Red", pname, name_size))
689 	    num_colorant = check_colorant_name(dev, "Cyan");
690 	else if (check_name("Green", pname, name_size))
691 	    num_colorant = check_colorant_name(dev, "Magenta");
692 	else if (check_name("Blue", pname, name_size))
693 	    num_colorant = check_colorant_name(dev, "Yellow");
694 	else if (check_name("Gray", pname, name_size))
695 	    num_colorant = check_colorant_name(dev, "Black");
696 
697 #undef check_colorant_name
698 #undef check_colorant_name_length
699 #undef check_name
700 
701     }
702     return num_colorant;
703 }
704 
705 /*
706  * See gs_color_name_component_number for main description.
707  *
708  * This version converts a name index value into a string and size and
709  * then call gs_color_name_component_number.
710  */
711 int
gs_cname_to_colorant_number(gs_state * pgs,byte * pname,uint name_size,int halftonetype)712 gs_cname_to_colorant_number(gs_state * pgs, byte * pname, uint name_size,
713 		int halftonetype)
714 {
715     gx_device * dev = pgs->device;
716 
717     return gs_color_name_component_number(dev, (char *)pname, name_size,
718 		    halftonetype);
719 }
720 
721 /*
722  * Install a device halftone into the imager state.
723  *
724  * To allow halftones to be shared between graphic states, the imager
725  * state contains a pointer to a device halftone structure. Thus, when
726  * we say a halftone is "in" the imager state, we are only claiming
727  * that the halftone pointer in the imager state points to that halftone.
728  *
729  * Though the operand halftone uses the same structure as the halftone
730  * "in" the imager state, not all of its fields are filled in, and the
731  * organization of components differs. Specifically, the following fields
732  * are not filled in:
733  *
734  *  rc          The operand device halftone has only a transient existence,
735  *              its reference count information is not initialized. In many
736  *              cases, the operand device halftone structure is allocated
737  *              on the stack by clients.
738  *
739  *  id          A halftone is not considered to have an identity until it
740  *              is installed in the imager state. This is a design error
741  *              which reflects the PostScript origins of this code. In
742  *              PostScript, it is impossible to check if two halftone
743  *              specifications (sets of operands to setscreen/setcolorscreen
744  *              or halftone dictionaries) are the same. Hence, the only way
745  *              a halftone could be identified was by the graphic state in
746  *              which it was included. In PCL it is possible to directly
747  *              identify a halftone specification, but currently there is
748  *              no way to use this knowledge in the graphic library.
749  *
750  *              (An altogether more reasonable approach would be to apply
751  *              id's to halftone orders.)
752  *
753  *  type        This is filled in by the type operand. It is used by
754  *              PostScript's currentscreen/currentcolorscreen operators to
755  *              determine if a sampling procedure or a halftone dictionary
756  *              should be pushed onto the stack. More importantly, it is
757  *              also used to determine if specific halftone components can
758  *              be used for either the additive or subtractive version of
759  *              that component in the process color model. For example, a
760  *              RedThreshold in a HalftoneType 4 dictionary can be applied
761  *              to either the component "Red" or the component "Cyan", but
762  *              the value of the key "Red" in a HalftoneType 5 dictionary
763  *              can only be used for a "Red" component (not a "Cyan"
764  *              component).
765  *
766  *  num_comp    For the operand halftone, this is the number of halftone
767  *              components included in the specification. For the device
768  *              halftone in the imager state, this is always the same as
769  *              the number of color model components (see num_dev_comp).
770  *
771  *  num_dev_comp The number of components in the device process color model
772  *		when the operand halftone was created.  With some compositor
773  *		devices (for example PDF 1.4) we can have differences in the
774  *		process color model of the compositor versus the output device.
775  *		These compositor devices do not halftone.
776  *
777  *  components  For the operand halftone, this field is non-null only if
778  *              multiple halftones are provided. In that case, the size
779  *              of the array pointed is the same as the number of
780  *              components provided. One of these components will usually
781  *              be the same as that identified by the "order" field.
782  *
783  *              For the device halftone in the imager state, this field is
784  *              always non-null, and the size of the array pointed to will
785  *              be the same as the number of components in the process
786  *              color model.
787  *
788  *  lcm_width,  These fields provide the least common multiple of the
789  *  lcm_height  halftone dimensions of the individual component orders.
790  *              They represent the dimensions of the smallest tile that
791  *              repeats for all color components (this is of interest
792  *              because Ghostscript uses a "chunky" raster format for all
793  *              drawing procedures). These fields cannot be set in the
794  *              operand device halftone as we do not yet know which of
795  *              the halftone components will actually be used.
796  *
797  * Conversely, the "order" field is significant only in the operand device
798  * halftone. There it represents the default halftone component, which will
799  * be used for all device color components for which a named halftone is
800  * not available. It is ignored (filled with 0's) in the device halftone
801  * in the imager state.
802  *
803  * The ordering of entries and the set of fields initialized in the
804  * components array also vary between the operand device halftone and
805  * the device halftone in the imager state.
806  *
807  * If the components array is present in the operand device halftone, the
808  * cname field in each entry of the array will contain a name index
809  * identifying the colorant name, and the comp_number field will provide the
810  * index of the corresponding component in the process color model. The
811  * order of entries in the components array is essentially arbitrary,
812  * but in some common cases will reflect the order in which the halftone
813  * specification is provided. By convention, if no explicit default order
814  * is provided (i.e.: via a HalftoneType 5 dictionary), the first
815  * entry of the array will be the same as the "order" (default) field.
816  *
817  * For the device halftone in the imager state, the components array is
818  * always present, but the cname and comp_number fields of individual
819  * entries are ignored. The order of the entries in the array always
820  * matches the order of components in the device color model.
821  *
822  * The distinction between the operand device halftone and the one in
823  * the graphic state extends even to the individual fields of the
824  * gx_ht_order structure incorporated in the order field of the halftone
825  * and the corder field of the elements of the components array. The
826  * fields of this structure that are handled differently in the operand
827  * and imager state device halftones are:
828  *
829  *  params          Provides a set of parameters that are required for
830  *                  converting a halftone specification to a single
831  *                  component order. This field is used only in the
832  *                  operand device halftone; it is not set in the device
833  *                  halftone in the imager state.
834  *
835  *  wse            Points to an "enumerator" instance, used to construct
836  *                 a well-tempered screen. This is only required while
837  *                 the well-tempered screen is being constructed. This
838  *                 field is always a null pointer in the device halftone
839  *                 in the imager state.
840  *
841  *  wts            Points to the "constructed" form of a well-tempered
842  *                 screen. The "construction" operation occurs as part
843  *                 of the installation process. Hence, this should
844  *                 always be a null pointer in the operand device
845  *                 halftone.
846  *
847  *  orig_height,   The height and shift values of the halftone cell,
848  *  orig_shift     prior to any replication. These fields are currently
849  *                 unused, and will always be the same as the height
850  *                 and width fields in the device halftone in the
851  *                 imager state.
852  *
853  *  full_height    The height of the smallest replicated tile whose shift
854  *                 value is 0. This is calculated as part of the
855  *                 installation process; it may be set in the operand
856  *                 device halftone, but its value is ignored.
857  *
858  *
859  *  data_memory    Points to the memory structure used to allocate the
860  *                 levels and bit_data arrays. The handling of this field
861  *                 is a bit complicated. For orders that are "taken over"
862  *                 by the installation process, this field will have the
863  *                 same value in the operand device halftone and the
864  *                 device halftone in the imager state. For halftones
865  *                 that are copied by the installation process, this
866  *                 field will have the same value as the memory field in
867  *                 the imager state (the two are usually the same).
868  *
869  *  cache          Pointer to a cache of tiles representing various
870  *                 levels of the halftone. This may or may not be
871  *                 provided in the operand device halftone (in principle
872  *                 this should always be a null pointer in the operand
873  *                 device halftone, but this is not the manner in which
874  *                 the cache was handled historically).
875  *
876  *  screen_params  This structure contains transformation information
877  *                 that is required when reading the sample data for a
878  *                 screen. It is no longer required once the halftone
879  *                 order has been constructed.
880  *
881  * In addition to what is noted above, this procedure is made somewhat
882  * more complex than expected due to memory management considerations. To
883  * clarify this, it is necessary to consider the properties of the pieces
884  * that constitute a device halftone.
885  *
886  *  The gx_device_halftone structure itself is shareable and uses
887  *  reference counts.
888  *
889  *  The gx_ht_order_component array (components array entry) is in
890  *  principle shareable, though it does not provide any reference
891  *  counting mechanism. Hence any sharing needs to be done with
892  *  caution.
893  *
894  *  Individual component orders are not shareable, as they are part of
895  *  the gx_ht_order_commponent structure (a major design error).
896  *
897  *  The levels, bit_data, and cache structures referenced by the
898  *  gx_ht_order structure are in principle shareable, but they also do
899  *  not provide any reference counting mechanism. Traditionally, one set
900  *  of two component orders could share these structures, using the
901  *  halftone's "order" field and various scattered bits of special case
902  *  code. This practice has been ended because it did not extend to
903  *  sharing amongst more than two components.
904  *
905  *  The gx_transfer_map structure referenced by the gx_ht_order structure
906  *  is shareable, and uses reference counts. Traditionally this structure
907  *  was not shared, but this is no longer the case.
908  *
909  * As noted, the rc field of the operand halftone is not initialized, so
910  * this procedure cannot simply take ownership of the operand device
911  * halftone structure (i.e.: an ostensibly shareable structure is not
912  * shareable). Hence, this procedure will always create a new copy of the
913  * gx_device_halftone structure, either by allocating a new structure or
914  * re-using the structure already referenced by the imager state. This
915  * feature must be retained, as in several cases the calling code will
916  * allocate the operand device halftone structure on the stack.
917  *
918  * Traditionally, this procedure took ownership of all of the structures
919  * referenced by the operand device halftone structure. This implied
920  * that all structures referenced by the gx_device_halftone structure
921  * needed to be allocated on the heap, and should not be released once
922  * the call to gx_imager_dev_ht_install completes.
923  *
924  * There were two problems with this approach:
925  *
926  *  1. In the event of an error, the calling code most likely would have
927  *     to release referenced components, as the imager state had not yet
928  *     take ownership of them. In many cases, the code did not do this.
929  *
930  *  2. When the structures referenced by a single order needed to be
931  *     shared amongst more than one component, there was no easy way to
932  *     discover this sharing when the imager state's device halftone
933  *     subsequently needed to be released. Hence, objects would be
934  *     released multiple times.
935  *
936  * Subsequently, the code in this routine was changed to copy most of
937  * the referenced structures (everything except the transfer functions).
938  * Unfortunately, the calling code was not changed, which caused memory
939  * leaks.
940  *
941  * The approach now taken uses a mixture of the two approaches.
942  * Ownership to structures referenced by the operand device halftone is
943  * assumed by the device halftone in the imager state where this is
944  * possible. In these cases, the corresponding references are removed in
945  * the operand device halftone (hence, this operand is no longer
946  * qualified as const). When a structure is required but ownership cannot
947  * be assumed, a copy is made and the reference in the operand device
948  * halftone is left undisturbed. The calling code has also been modified
949  * to release any remaining referenced structures when this routine
950  * returns, whether or not an error is indicated.
951  */
952 int
gx_imager_dev_ht_install(gs_imager_state * pis,gx_device_halftone * pdht,gs_halftone_type type,const gx_device * dev)953 gx_imager_dev_ht_install(
954     gs_imager_state *       pis,
955     gx_device_halftone *    pdht,
956     gs_halftone_type        type,
957     const gx_device *       dev )
958 {
959     gx_device_halftone      dht;
960     int                     num_comps = pdht->num_dev_comp;
961     int                     i, code = 0;
962     bool                    used_default = false;
963     int                     lcm_width = 1, lcm_height = 1;
964     gs_wts_screen_enum_t *  wse0 = pdht->order.wse;
965     wts_screen_t *          wts0 = 0;
966     bool                    mem_diff = pdht->rc.memory != pis->memory;
967 
968     /* construct the new device halftone structure */
969     memset(&dht.order, 0, sizeof(dht.order));
970     /* the rc field is filled in later */
971     dht.id = gs_next_ids(pis->memory, 1);
972     dht.type = type;
973     dht.components =  gs_alloc_struct_array(
974                           pis->memory,
975                           num_comps,
976                           gx_ht_order_component,
977                           &st_ht_order_component_element,
978                           "gx_imager_dev_ht_install(components)" );
979     if (dht.components == NULL)
980 	return_error(gs_error_VMerror);
981     dht.num_comp = dht.num_dev_comp = num_comps;
982     /* lcm_width, lcm_height are filled in later */
983 
984     /* initialize the components array */
985     memset(dht.components, 0, num_comps * sizeof(dht.components[0]));
986     for (i = 0; i < num_comps; i++)
987         dht.components[i].comp_number = -1;
988 
989     /*
990      * Duplicate any of the non-default components, but do not create copies
991      * of the levels or bit_data arrays. If all goes according to plan, the
992      * imager state's device halftone will assume ownership of these arrays
993      * by clearing the corresponding pointers in the operand halftone's
994      * orders.
995      */
996     if (pdht->components != 0) {
997         int     input_ncomps = pdht->num_comp;
998 
999         for (i = 0; i < input_ncomps && code >= 0; i++) {
1000             gx_ht_order_component * p_s_comp = &pdht->components[i];
1001             gx_ht_order *           p_s_order = &p_s_comp->corder;
1002             int                     comp_num = p_s_comp->comp_number;
1003 
1004 	    if (comp_num >= 0 && comp_num < GX_DEVICE_COLOR_MAX_COMPONENTS) {
1005                 gx_ht_order *   p_d_order = &dht.components[comp_num].corder;
1006 
1007                 /* indicate that this order has been filled in */
1008                 dht.components[comp_num].comp_number = comp_num;
1009 
1010                 /*
1011                  * The component can be used only if it is from the
1012                  * proper memory
1013                  */
1014                 if (mem_diff)
1015                     code = gx_ht_copy_ht_order( p_d_order,
1016                                                 p_s_order,
1017                                                 pis->memory );
1018                 else {
1019                     /* check if this is also the default component */
1020                     used_default = used_default ||
1021                                    p_s_order->bit_data == pdht->order.bit_data;
1022 
1023                     gx_ht_move_ht_order(p_d_order, p_s_order);
1024                 }
1025             }
1026         }
1027     }
1028 
1029     /*
1030      * Copy the default order to any remaining components.
1031      *
1032      * For well-tempered screens, generate the wts_screen_t structure
1033      * for each component that corresponds to the sample information
1034      * that has been gathered.
1035      *
1036      * Some caution is necessary here, as multiple component orders may
1037      * have wse fields pointing to the same gs_wts_creeen_enum_t
1038      * structure. This structure should only be released once. If
1039      * multiple components have such a wse value, it will be the same as
1040      * pdht->order.wse pointer, so we can just release that pointer once
1041      * when done.
1042      *
1043      * If serveral component orders have the same wse value, this code
1044      * will create just one wts_screen_t structure. In a somewhat ugly
1045      * hack, the width field (which is otherwise unused) will be set to
1046      * 0xffff for all components other than the first component that
1047      * makes use of a give wts_screen_t structure. gx_ht_order_release
1048      * will check this field to see if it should release the structure
1049      * pointed to by the wts field of a component order.
1050      *
1051      * Components that are not well-tempered screens require a cache.
1052      * In practice, either all or non of the components will be well-
1053      * tempered screens, but we ignore that fact here.
1054      *
1055      * While engaged in all of these other activities, also calculate
1056      * the lcm_width and lcm_heigth values (only for non-well-tempered
1057      * components).
1058      */
1059     for (i = 0; i < num_comps && code >= 0; i++) {
1060         gx_ht_order *           porder = &dht.components[i].corder;
1061         gs_wts_screen_enum_t *  wse;
1062 
1063         if (dht.components[i].comp_number != i) {
1064             if (used_default || mem_diff)
1065                 code = gx_ht_copy_ht_order(porder, &pdht->order, pis->memory);
1066             else {
1067                 gx_ht_move_ht_order(porder, &pdht->order);
1068                 used_default = true;
1069             }
1070             dht.components[i].comp_number = i;
1071         }
1072         if ((wse = porder->wse) != 0) {
1073             wts_screen_t *  wts = 0;
1074 
1075             porder->width = 0;
1076             porder->wse = 0;
1077             if (wse != wse0)
1078                 wts = wts_screen_from_enum(wse);
1079             else {
1080                 if (wts0 == 0)
1081                     wts0 = wts_screen_from_enum(wse);
1082                 else
1083                     porder->width = ht_wts_suppress_release;
1084                 wts = wts0;
1085             }
1086             if (wts == 0)
1087                 code = gs_error_VMerror;
1088             else
1089                 porder->wts = wts;
1090         } else {
1091             uint   w = porder->width, h = porder->full_height;
1092             int    dw = igcd(lcm_width, w), dh = igcd(lcm_height, h);
1093 
1094             lcm_width /= dw;
1095             lcm_height /= dh;
1096             lcm_width = (w > max_int / lcm_width ? max_int : lcm_width * w);
1097             lcm_height = (h > max_int / lcm_height ? max_int : lcm_height * h);
1098 
1099             if (porder->cache == 0) {
1100                 uint            tile_bytes, num_tiles;
1101                 gx_ht_cache *   pcache;
1102 
1103                 tile_bytes = porder->raster
1104                               * (porder->num_bits / porder->width);
1105                 num_tiles = 1 + max_tile_cache_bytes / tile_bytes;
1106                 pcache = gx_ht_alloc_cache( pis->memory,
1107                                             num_tiles,
1108                                             tile_bytes * num_tiles );
1109                 if (pcache == NULL)
1110                     code = gs_error_VMerror;
1111                 else {
1112                     porder->cache = pcache;
1113                     gx_ht_init_cache(pis->memory, pcache, porder);
1114                 }
1115             }
1116         }
1117     }
1118     dht.lcm_width = lcm_width;
1119     dht.lcm_height = lcm_height;
1120 
1121     /*
1122      * If everything is OK so far, allocate a unique copy of the device
1123      * halftone reference by the imager state.
1124      *
1125      * This code requires a special check for the case in which the
1126      * deivce halftone referenced by the imager state is already unique.
1127      * In this case, we must explicitly release just the components array
1128      * (and any structures it refers to) of the existing halftone. This
1129      * cannot be done automatically, as the rc_unshare_struct macro only
1130      * ensures that a unique instance of the top-level structure is
1131      * created, not that any substructure references are updated.
1132      *
1133      * Though this is scheduled to be changed, for the time being the
1134      * command list renderer may invoke this code with pdht == psi->dev_ht
1135      * (in which case we know pis->dev_ht.rc.ref_count == 1). Special
1136      * handling is required in that case, to avoid releasing structures
1137      * we still need.
1138      */
1139     if (code >= 0) {
1140         gx_device_halftone *    pisdht = pis->dev_ht;
1141         rc_header               tmp_rc;
1142 
1143         if (pisdht != 0 && pisdht->rc.ref_count == 1) {
1144             if (pdht != pisdht)
1145                 gx_device_halftone_release(pisdht, pisdht->rc.memory);
1146         } else {
1147             rc_unshare_struct( pis->dev_ht,
1148                                gx_device_halftone,
1149                                &st_device_halftone,
1150                                pis->memory,
1151                                BEGIN code = gs_error_VMerror; goto err; END,
1152                                "gx_imager_dev_ht_install" );
1153             pisdht = pis->dev_ht;
1154         }
1155 
1156         /*
1157          * Everything worked. "Assume ownership" of the appropriate
1158          * portions of the source device halftone by clearing the
1159          * associated references. This includes explicitly releasing
1160          * any gs_wts_screen_enum_t structures. Since we might have
1161          * pdht == pis->dev_ht, this must done before updating pis->dev_ht.
1162          *
1163          * If the default order has been used for a device component, and
1164          * any of the source component orders share their levels or bit_data
1165          * arrays with the default order, clear the pointers in those orders
1166          * now. This is necessary because the default order's pointers will
1167          * be cleared immediately below, so subsequently it will not be
1168          * possible to tell if that this information is being shared.
1169          */
1170         if (pdht->components != 0) {
1171             int     input_ncomps = pdht->num_comp;
1172 
1173             for (i = 0; i < input_ncomps; i++) {
1174                 gx_ht_order_component * p_s_comp = &pdht->components[i];
1175                 gx_ht_order *           p_s_order = &p_s_comp->corder;
1176                 int                     comp_num = p_s_comp->comp_number;
1177 
1178                 if ( comp_num >= 0                            &&
1179                      comp_num < GX_DEVICE_COLOR_MAX_COMPONENTS  ) {
1180                     if (p_s_order->wse != 0)
1181                         gs_wts_free_enum(p_s_order->wse);
1182                     memset(p_s_order, 0, sizeof(*p_s_order));
1183                 } else if ( comp_num == GX_DEVICE_COLOR_MAX_COMPONENTS &&
1184                             used_default                                 )
1185                     memset(p_s_order, 0, sizeof(*p_s_order));
1186             }
1187         }
1188         if (used_default) {
1189             if (wse0 != 0)
1190                 gs_wts_free_enum(wse0);
1191             memset(&pdht->order, 0, sizeof(pdht->order));
1192         }
1193 
1194         tmp_rc = pisdht->rc;
1195         *pisdht = dht;
1196         pisdht->rc = tmp_rc;
1197 
1198         /* update the effective transfer function array */
1199         gx_imager_set_effective_xfer(pis);
1200 
1201         return 0;
1202     }
1203 
1204     /* something went amiss; release all copied components */
1205   err:
1206     for (i = 0; i < num_comps; i++) {
1207         gx_ht_order_component * pcomp = &dht.components[i];
1208         gx_ht_order *           porder = &pcomp->corder;
1209 
1210         if (pcomp->comp_number == -1)
1211             gx_ht_order_release(porder, pis->memory, true);
1212     }
1213     gs_free_object(pis->memory, dht.components, "gx_imager_dev_ht_install");
1214 
1215     return code;
1216 }
1217 
1218 /*
1219  * Install a new halftone in the graphics state.  Note that we copy the top
1220  * level of the gs_halftone and the gx_device_halftone, and take ownership
1221  * of any substructures.
1222  */
1223 int
gx_ht_install(gs_state * pgs,const gs_halftone * pht,gx_device_halftone * pdht)1224 gx_ht_install(gs_state * pgs, const gs_halftone * pht,
1225 	      gx_device_halftone * pdht)
1226 {
1227     gs_memory_t *mem = pht->rc.memory;
1228     gs_halftone *old_ht = pgs->halftone;
1229     gs_halftone *new_ht;
1230     int code;
1231 
1232     pdht->num_dev_comp = pgs->device->color_info.num_components;
1233     if (old_ht != 0 && old_ht->rc.memory == mem &&
1234 	old_ht->rc.ref_count == 1
1235 	)
1236 	new_ht = old_ht;
1237     else
1238 	rc_alloc_struct_1(new_ht, gs_halftone, &st_halftone,
1239 			  mem, return_error(gs_error_VMerror),
1240 			  "gx_ht_install(new halftone)");
1241     code = gx_imager_dev_ht_install((gs_imager_state *) pgs,
1242 			     pdht, pht->type, gs_currentdevice_inline(pgs));
1243     if (code < 0) {
1244 	if (new_ht != old_ht)
1245 	    gs_free_object(mem, new_ht, "gx_ht_install(new halftone)");
1246 	return code;
1247     }
1248 
1249     /*
1250      * Discard and unused components and the components array of the
1251      * operand device halftone
1252      */
1253     gx_device_halftone_release(pdht, pdht->rc.memory);
1254 
1255     if (new_ht != old_ht)
1256 	rc_decrement(old_ht, "gx_ht_install(old halftone)");
1257     {
1258 	rc_header rc;
1259 
1260 	rc = new_ht->rc;
1261 	*new_ht = *pht;
1262 	new_ht->rc = rc;
1263     }
1264     pgs->halftone = new_ht;
1265     gx_unset_dev_color(pgs);
1266     return 0;
1267 }
1268 
1269 /*
1270  * This macro will determine the colorant number of a given color name.
1271  * A value of -1 indicates that the name is not valid.
1272  */
1273 #define check_colorant_name(name, dev) \
1274    ((*dev_proc(dev, get_color_comp_index)) (dev, name, strlen(name), NO_NAME_TYPE))
1275 
1276 /* Reestablish the effective transfer functions, taking into account */
1277 /* any overrides from halftone dictionaries. */
1278 void
gx_imager_set_effective_xfer(gs_imager_state * pis)1279 gx_imager_set_effective_xfer(gs_imager_state * pis)
1280 {
1281     const gx_device_halftone *pdht = pis->dev_ht;
1282     gx_transfer_map *pmap;
1283     int i, component_num;
1284 
1285     for (i = 0; i < GX_DEVICE_COLOR_MAX_COMPONENTS; i++)
1286 	pis->effective_transfer[i] = pis->set_transfer.gray;	/* default */
1287 
1288     /* Check if we have a transfer functions from setcolortransfer */
1289     if (pis->set_transfer.red) {
1290 	component_num = pis->set_transfer.red_component_num;
1291 	if (component_num >= 0)
1292 	    pis->effective_transfer[component_num] = pis->set_transfer.red;;
1293     }
1294     if (pis->set_transfer.green) {
1295 	component_num = pis->set_transfer.green_component_num;
1296 	if (component_num >= 0)
1297 	    pis->effective_transfer[component_num] = pis->set_transfer.green;
1298     }
1299     if (pis->set_transfer.blue) {
1300 	component_num = pis->set_transfer.blue_component_num;
1301 	if (component_num >= 0)
1302 	    pis->effective_transfer[component_num] = pis->set_transfer.blue;
1303     }
1304 
1305     if (pdht == NULL)
1306 	return;			/* not initialized yet */
1307 
1308     for (i = 0; i < pdht->num_comp; i++) {
1309 	pmap = pdht->components[i].corder.transfer;
1310 	if (pmap != NULL)
1311 	    pis->effective_transfer[i] = pmap;
1312     }
1313 }
1314 
1315 void
gx_set_effective_transfer(gs_state * pgs)1316 gx_set_effective_transfer(gs_state * pgs)
1317 {
1318     gx_imager_set_effective_xfer((gs_imager_state *) pgs);
1319 }
1320