1 /* Copyright (C) 2001-2019 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,
8    modified or distributed except as expressly authorized under the terms
9    of the license contained in the file LICENSE in this distribution.
10 
11    Refer to licensing information at http://www.artifex.com or contact
12    Artifex Software, Inc.,  1305 Grant Avenue - Suite 200, Novato,
13    CA 94945, U.S.A., +1(415)492-9861, for further information.
14 */
15 
16 
17 /* Pattern color mapping for Ghostscript library */
18 #include "math_.h"
19 #include "memory_.h"
20 #include "gx.h"
21 #include "gp.h"
22 #include "gserrors.h"
23 #include "gsstruct.h"
24 #include "gsutil.h"             /* for gs_next_ids */
25 #include "gxfixed.h"
26 #include "gxmatrix.h"
27 #include "gspath2.h"
28 #include "gxcspace.h"           /* for gscolor2.h */
29 #include "gxcolor2.h"
30 #include "gxdcolor.h"
31 #include "gxdevice.h"
32 #include "gxdevmem.h"
33 #include "gxpcolor.h"
34 #include "gxp1impl.h"
35 #include "gxclist.h"
36 #include "gxcldev.h"
37 #include "gzstate.h"
38 #include "gxdevsop.h"
39 #include "gdevmpla.h"
40 #include "gdevp14.h"
41 #include "gxgetbit.h"
42 #include "gscoord.h"
43 
44 #if RAW_PATTERN_DUMP
45 unsigned int global_pat_index = 0;
46 #endif
47 
48 /* Define the default size of the Pattern cache. */
49 #define max_cached_patterns_LARGE 50
50 #define max_pattern_bits_LARGE 100000
51 #define max_cached_patterns_SMALL 5
52 #define max_pattern_bits_SMALL 1000
53 uint
gx_pat_cache_default_tiles(void)54 gx_pat_cache_default_tiles(void)
55 {
56 #if ARCH_SMALL_MEMORY
57     return max_cached_patterns_SMALL;
58 #else
59 #ifdef DEBUG
60     return (gs_debug_c('.') ? max_cached_patterns_SMALL :
61             max_cached_patterns_LARGE);
62 #else
63     return max_cached_patterns_LARGE;
64 #endif
65 #endif
66 }
67 ulong
gx_pat_cache_default_bits(void)68 gx_pat_cache_default_bits(void)
69 {
70 #if ARCH_SMALL_MEMORY
71     return max_pattern_bits_SMALL;
72 #else
73 #ifdef DEBUG
74     return (gs_debug_c('.') ? max_pattern_bits_SMALL :
75             max_pattern_bits_LARGE);
76 #else
77     return max_pattern_bits_LARGE;
78 #endif
79 #endif
80 }
81 
82 /* Define the structures for Pattern rendering and caching. */
83 private_st_color_tile();
84 private_st_color_tile_element();
85 private_st_pattern_cache();
86 private_st_device_pattern_accum();
87 private_st_pattern_trans();
88 
89 /* ------ Pattern rendering ------ */
90 
91 /* Device procedures */
92 static dev_proc_open_device(pattern_accum_open);
93 static dev_proc_close_device(pattern_accum_close);
94 static dev_proc_fill_rectangle(pattern_accum_fill_rectangle);
95 static dev_proc_copy_mono(pattern_accum_copy_mono);
96 static dev_proc_copy_color(pattern_accum_copy_color);
97 static dev_proc_copy_planes(pattern_accum_copy_planes);
98 static dev_proc_get_bits_rectangle(pattern_accum_get_bits_rectangle);
99 static dev_proc_fill_rectangle_hl_color(pattern_accum_fill_rectangle_hl_color);
100 /* not static for use by clist_dev_spec_op with pattern-clist */
101 dev_proc_dev_spec_op(pattern_accum_dev_spec_op);
102 
103 /* The device descriptor */
104 static const gx_device_pattern_accum gs_pattern_accum_device =
105 {std_device_std_body_type_open(gx_device_pattern_accum, 0,
106                           "pattern accumulator", &st_device_pattern_accum,
107                           0, 0, 72, 72),
108  {
109      /* NOTE: all drawing procedures must be defaulted, not forwarded. */
110      pattern_accum_open,
111      NULL,                              /* get_initial_matrix */
112      NULL,                              /* sync_output */
113      NULL,                              /* output_page */
114      pattern_accum_close,
115      NULL,                              /* map_rgb_color */
116      NULL,                              /* map_color_rgb */
117      pattern_accum_fill_rectangle,
118      gx_default_tile_rectangle,
119      pattern_accum_copy_mono,
120      pattern_accum_copy_color,
121      NULL,                              /* obselete_draw_line */
122      gx_default_get_bits,
123      NULL,                              /* get_params */
124      NULL,                              /* put_params */
125      NULL,                              /* map_cmyk_color */
126      NULL,                              /* get_xfont_procs */
127      NULL,                              /* get_xfont_device */
128      NULL,                              /* map_rgb_alpha_color */
129      NULL,                              /* get_page_device */
130      NULL,                              /* get_alpha_bits */
131      gx_default_copy_alpha,
132      NULL,                              /* get_band */
133      gx_default_copy_rop,
134      gx_default_fill_path,
135      gx_default_stroke_path,
136      gx_default_fill_mask,
137      gx_default_fill_trapezoid,
138      gx_default_fill_parallelogram,
139      gx_default_fill_triangle,
140      gx_default_draw_thin_line,
141      gx_default_begin_image,
142      gx_default_image_data,
143      gx_default_end_image,
144      gx_default_strip_tile_rectangle,
145      gx_default_strip_copy_rop,
146      gx_get_largest_clipping_box,
147      gx_default_begin_typed_image,
148      pattern_accum_get_bits_rectangle,
149      NULL,                              /* map_color_rgb_alpha */
150      gx_default_create_compositor,
151      NULL,                              /* create_compositor */
152      gx_default_text_begin,
153      gx_default_finish_copydevice,
154      NULL,                              /* begin_transparency_group */
155      NULL,                              /* end_transparency_group */
156      NULL,                              /* begin_transparency_mask */
157      NULL,                              /* end_transparency_mask */
158      NULL,                              /* discard_transparency_layer */
159      NULL,                              /* get_color_mapping_procs */
160      NULL,                              /* get_color_comp_index */
161      NULL,                              /* encode_color */
162      NULL,                              /* decode_color */
163      NULL,                              /* pattern_manage */
164      pattern_accum_fill_rectangle_hl_color, /* fill_rectangle_hl_color */
165      NULL,                              /* include_color_space */
166      NULL,                              /* fill_linear_color_scanline */
167      NULL,                              /* fill_linear_color_trapezoid */
168      NULL,                              /* fill_linear_color_triangle */
169      NULL,                              /* update_spot_equivalent_colors */
170      NULL,                              /* ret_devn_params */
171      NULL,                              /* fillpage */
172      NULL,                              /* push_transparency_state */
173      NULL,                              /* pop_transparency_state */
174      NULL,                              /* put_image */
175      pattern_accum_dev_spec_op,         /* dev_spec_op */
176      pattern_accum_copy_planes,         /* copy_planes */
177      NULL,                              /* get_profile */
178      NULL,                              /* set_graphics_type_tag */
179      gx_default_strip_copy_rop2,
180      gx_default_strip_tile_rect_devn,
181      NULL,                              /* alpha_hl_color */
182      NULL,                              /* process_page */
183      gx_default_transform_pixel_region, /* NOT the default forwarding one */
184      gx_default_fill_stroke_path,
185 },
186  0,                             /* target */
187  0, 0, 0, 0                     /* bitmap_memory, bits, mask, instance */
188 };
189 
190 int
pattern_clist_open_device(gx_device * dev)191 pattern_clist_open_device(gx_device *dev)
192 {
193     /* This function is defiled only for clist_init_bands. */
194     return gs_clist_device_procs.open_device(dev);
195 }
196 
dev_proc_create_buf_device(dummy_create_buf_device)197 static dev_proc_create_buf_device(dummy_create_buf_device)
198 {
199     gx_device_memory *mdev = (gx_device_memory *)*pbdev;
200 
201     gs_make_mem_device(mdev, gdev_mem_device_for_bits(target->color_info.depth),
202                 mem, 0, target);
203     return 0;
204 }
dev_proc_size_buf_device(dummy_size_buf_device)205 static dev_proc_size_buf_device(dummy_size_buf_device)
206 {
207     return 0;
208 }
dev_proc_setup_buf_device(dummy_setup_buf_device)209 static dev_proc_setup_buf_device(dummy_setup_buf_device)
210 {
211     return 0;
212 }
dev_proc_destroy_buf_device(dummy_destroy_buf_device)213 static dev_proc_destroy_buf_device(dummy_destroy_buf_device)
214 {
215 }
216 /* Attempt to determine the size of a pattern (the approximate amount that will */
217 /* be needed in the pattern cache). If we end up using the clist, this is only  */
218 /* a guess -- we use the tile size which will _probably_ be too large.          */
219 static int
gx_pattern_size_estimate(gs_pattern1_instance_t * pinst,bool has_tags)220 gx_pattern_size_estimate(gs_pattern1_instance_t *pinst, bool has_tags)
221 {
222     gx_device *tdev = pinst->saved->device;
223     int depth = (pinst->templat.PaintType == 2 ? 1 : tdev->color_info.depth);
224     int64_t raster;
225     int64_t size;
226 
227     if (pinst->size.x == 0 || pinst->size.y == 0)
228         return 0;
229 
230     if (pinst->templat.uses_transparency) {
231         /* if the device has tags, add in an extra tag byte for the pdf14 compositor */
232         raster = ((int64_t)pinst->size.x * ((depth/8) + 1 + (has_tags ? 1 : 0)));
233     } else {
234         raster = ((int64_t)pinst->size.x * depth + 7) / 8;
235     }
236     size = raster > max_int / pinst->size.y ? (max_int & ~0xFFFF) : raster * pinst->size.y;
237     if (size > (int64_t)max_int)
238         size = (max_int & ~0xFFFF);
239     return (int)size;
240 }
241 
gx_pattern_accum_finalize_cw(gx_device * dev)242 static void gx_pattern_accum_finalize_cw(gx_device * dev)
243 {
244     gx_device_clist_writer *cwdev = (gx_device_clist_writer *)dev;
245     rc_decrement_only(cwdev->target, "gx_pattern_accum_finalize_cw");
246 }
247 
gx_device_is_pattern_accum(gx_device * dev)248 bool gx_device_is_pattern_accum(gx_device *dev)
249 {
250     return dev_proc(dev, open_device) == pattern_accum_open;
251 }
252 
gx_device_is_pattern_clist(gx_device * dev)253 bool gx_device_is_pattern_clist(gx_device *dev)
254 {
255     return dev_proc(dev, open_device) == pattern_clist_open_device;
256 }
257 
258 /* Allocate a pattern accumulator, with an initial refct of 0. */
259 gx_device_forward *
gx_pattern_accum_alloc(gs_memory_t * mem,gs_memory_t * storage_memory,gs_pattern1_instance_t * pinst,client_name_t cname)260 gx_pattern_accum_alloc(gs_memory_t * mem, gs_memory_t * storage_memory,
261                        gs_pattern1_instance_t *pinst, client_name_t cname)
262 {
263     gx_device *tdev = pinst->saved->device;
264     bool has_tags = device_encodes_tags(tdev);
265     int size = gx_pattern_size_estimate(pinst, has_tags);
266     gx_device_forward *fdev;
267     int force_no_clist = 0;
268     int max_pattern_bitmap = tdev->MaxPatternBitmap == 0 ? MaxPatternBitmap_DEFAULT :
269                                 tdev->MaxPatternBitmap;
270 
271     pinst->is_planar = tdev->is_planar;
272     /*
273      * If the target device can accumulate a pattern stream and the language
274      * client supports high level patterns (ps and pdf only) we don't need a
275      * raster or clist representation for the pattern, but the code goes
276      * through the motions of creating the device anyway.  Later when the
277      * pattern paint procedure is called  an error is returned and whatever
278      * has been set up here is destroyed.  We try to make sure the same path
279      * is taken in the code even though the device is never used because
280      * there are pathological problems (see Bug689851.pdf) where the pattern
281      * is so large we can't even allocate the memory for the device and the
282      * dummy clist path must be used.  None of this discussion is relevant if
283      * the client language does not support high level patterns or the device
284      * cannot accumulate the pattern stream.
285      */
286     if (pinst->saved->have_pattern_streams == 0 && (*dev_proc(pinst->saved->device,
287         dev_spec_op))((gx_device *)pinst->saved->device,
288         gxdso_pattern_can_accum, pinst, 0) == 1)
289         force_no_clist = 1; /* Set only for first time through */
290     if (force_no_clist || (size < max_pattern_bitmap && !pinst->is_clist)
291         || pinst->templat.PaintType != 1 ) {
292         gx_device_pattern_accum *adev = gs_alloc_struct(mem, gx_device_pattern_accum,
293                         &st_device_pattern_accum, cname);
294         if (adev == 0)
295             return 0;
296 #ifdef DEBUG
297         if (pinst->is_clist)
298             emprintf(mem, "not using clist even though clist is requested\n");
299 #endif
300         pinst->is_clist = false;
301         gx_device_init((gx_device *)adev,
302                        (const gx_device *)&gs_pattern_accum_device,
303                        mem, true);
304         adev->instance = pinst;
305         adev->bitmap_memory = storage_memory;
306         fdev = (gx_device_forward *)adev;
307     } else {
308         gx_device_buf_procs_t buf_procs = {dummy_create_buf_device,
309         dummy_size_buf_device, dummy_setup_buf_device, dummy_destroy_buf_device};
310         gx_device_clist *cdev;
311         gx_device_clist_writer *cwdev;
312         const int data_size = 1024*128;
313         gx_band_params_t band_params = { 0 };
314         byte *data  = gs_alloc_bytes(tdev->memory->non_gc_memory, data_size, cname);
315 
316         if (data == NULL)
317             return 0;
318         pinst->is_clist = true;
319         /* NB: band_params.page_uses_transparency is set in clist_make_accum_device */
320         band_params.BandWidth = pinst->size.x;
321         band_params.BandHeight = pinst->size.y;
322         band_params.BandBufferSpace = 0;
323 
324         cdev = clist_make_accum_device(tdev, "pattern-clist", data, data_size,
325                                        &buf_procs, &band_params, true, /* use_memory_clist */
326                                        pinst->templat.uses_transparency, pinst);
327         if (cdev == 0) {
328             gs_free_object(tdev->memory->non_gc_memory, data, cname);
329             return 0;
330         }
331         cwdev = (gx_device_clist_writer *)cdev;
332         cwdev->finalize = gx_pattern_accum_finalize_cw;
333         set_dev_proc(cwdev, open_device, pattern_clist_open_device);
334         fdev = (gx_device_forward *)cdev;
335     }
336     fdev->log2_align_mod = tdev->log2_align_mod;
337     fdev->pad = tdev->pad;
338     fdev->is_planar = tdev->is_planar;
339     fdev->graphics_type_tag = tdev->graphics_type_tag;
340     fdev->interpolate_control = tdev->interpolate_control;
341     gx_device_forward_fill_in_procs(fdev);
342     return fdev;
343 }
344 
345 gx_pattern_trans_t*
new_pattern_trans_buff(gs_memory_t * mem)346 new_pattern_trans_buff(gs_memory_t *mem)
347 {
348     gx_pattern_trans_t *result;
349 
350     /* Allocate structure that we will use for the trans pattern */
351     result = gs_alloc_struct(mem, gx_pattern_trans_t, &st_pattern_trans, "new_pattern_trans_buff");
352     result->transbytes = NULL;
353     result->pdev14 = NULL;
354     result->mem = NULL;
355     result->fill_trans_buffer = NULL;
356     result->buf = NULL;
357     result->n_chan = 0;
358 
359     return(result);
360 }
361 
362 /*
363  * Initialize a pattern accumulator.
364  * Client must already have set instance and bitmap_memory.
365  *
366  * Note that mask and bits accumulators are only created if necessary.
367  */
368 static int
pattern_accum_open(gx_device * dev)369 pattern_accum_open(gx_device * dev)
370 {
371     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *) dev;
372     const gs_pattern1_instance_t *pinst = padev->instance;
373     gs_memory_t *mem = padev->bitmap_memory;
374     gx_device_memory *mask = 0;
375     gx_device_memory *bits = 0;
376     /*
377      * The client should preset the target, because the device for which the
378      * pattern is being rendered may not (in general, will not) be the same
379      * as the one that was current when the pattern was instantiated.
380      */
381     gx_device *target =
382         (padev->target == 0 ? gs_currentdevice(pinst->saved) :
383          padev->target);
384     int width = pinst->size.x;
385     int height = pinst->size.y;
386     int code = 0;
387     bool mask_open = false;
388 
389     /*
390      * C's bizarre coercion rules force us to copy HWResolution in pieces
391      * rather than using a single assignment.
392      */
393 #define PDSET(dev)\
394   ((dev)->width = width, (dev)->height = height,\
395    /*(dev)->HWResolution = target->HWResolution*/\
396    (dev)->HWResolution[0] = target->HWResolution[0],\
397    (dev)->HWResolution[1] = target->HWResolution[1])
398 
399     PDSET(padev);
400     padev->color_info = target->color_info;
401     /* Bug 689737: If PaintType == 2 (Uncolored tiling pattern), pattern is
402      * 1bpp bitmap. No antialiasing in this case! */
403     if (pinst->templat.PaintType == 2) {
404         padev->color_info.anti_alias.text_bits = 1;
405         padev->color_info.anti_alias.graphics_bits = 1;
406     }
407     /* If we have transparency, then fix the color info
408        now so that the mem device allocates the proper
409        buffer space for the pattern template.  We can
410        do this since the transparency code all */
411     if (pinst->templat.uses_transparency) {
412         /* Allocate structure that we will use for the trans pattern */
413         padev->transbuff = new_pattern_trans_buff(mem);
414         if (padev->transbuff == NULL)
415             return_error(gs_error_VMerror);
416     } else {
417         padev->transbuff = NULL;
418     }
419     if (pinst->uses_mask) {
420         mask = gs_alloc_struct( mem,
421                                 gx_device_memory,
422                                 &st_device_memory,
423                                 "pattern_accum_open(mask)"
424                                 );
425         if (mask == 0)
426             return_error(gs_error_VMerror);
427         gs_make_mem_mono_device(mask, mem, 0);
428         PDSET(mask);
429         mask->bitmap_memory = mem;
430         mask->base = 0;
431         code = (*dev_proc(mask, open_device)) ((gx_device *) mask);
432         if (code >= 0) {
433             mask_open = true;
434             memset(mask->base, 0, mask->raster * mask->height);
435         }
436     }
437 
438     if (code >= 0) {
439         if (pinst->templat.uses_transparency) {
440             /* In this case, we will grab the buffer created
441                by the graphic state's device (which is pdf14) and
442                we will be tiling that into a transparency group buffer
443                to blend with the pattern accumulator's target.  Since
444                all the transparency stuff is planar format, it is
445                best just to keep the data in that form */
446             gx_device_set_target((gx_device_forward *)padev, target);
447         } else {
448             switch (pinst->templat.PaintType) {
449             case 2:             /* uncolored */
450                 gx_device_set_target((gx_device_forward *)padev, target);
451                 break;
452             case 1:             /* colored */
453                 bits = gs_alloc_struct(mem, gx_device_memory,
454                                        &st_device_memory,
455                                        "pattern_accum_open(bits)");
456                 if (bits == 0)
457                     code = gs_note_error(gs_error_VMerror);
458                 else {
459                     gs_make_mem_device(bits,
460                             gdev_mem_device_for_bits(padev->color_info.depth),
461                                        mem, -1, target);
462                     PDSET(bits);
463 #undef PDSET
464                     bits->color_info = padev->color_info;
465                     bits->bitmap_memory = mem;
466                     if (target->is_planar > 0)
467                     {
468                         gx_render_plane_t planes[GX_DEVICE_COLOR_MAX_COMPONENTS];
469                         uchar num_comp = padev->color_info.num_components;
470                         uchar i;
471                         int depth = target->color_info.depth / target->color_info.num_components;
472                         for (i = 0; i < num_comp; i++)
473                         {
474                             planes[i].shift = depth * (num_comp - 1 - i);
475                             planes[i].depth = depth;
476                             planes[i].index = i;
477                         }
478                         code = gdev_mem_set_planar(bits, num_comp, planes);
479                     }
480                     if (code >= 0) {
481                         code = (*dev_proc(bits, open_device)) ((gx_device *) bits);
482                         gx_device_set_target((gx_device_forward *)padev,
483                                              (gx_device *)bits);
484                         /* The update_spot_equivalent_color proc for the bits device
485                            should forward to the real target device.  This will ensure
486                            that the target device can get equivalent CMYK values for
487                            spot colors if we are using a separation device and the spot
488                            color occurs only in patterns on the page. */
489                         bits->procs.update_spot_equivalent_colors = gx_forward_update_spot_equivalent_colors;
490                     }
491                 }
492             }
493         }
494     }
495     if (code < 0) {
496         if (bits != 0)
497             gs_free_object(mem, bits, "pattern_accum_open(bits)");
498         if (mask != 0) {
499             if (mask_open)
500                 (*dev_proc(mask, close_device)) ((gx_device *) mask);
501             gs_free_object(mem, mask, "pattern_accum_open(mask)");
502         }
503         return code;
504     }
505     padev->mask = mask;
506     padev->bits = bits;
507     /* Retain the device, so it will survive anomalous grestores. */
508     gx_device_retain(dev, true);
509     return code;
510 }
511 
512 /* Close an accumulator and free the bits. */
513 static int
pattern_accum_close(gx_device * dev)514 pattern_accum_close(gx_device * dev)
515 {
516     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *) dev;
517     gs_memory_t *mem = padev->bitmap_memory;
518 
519     /*
520      * If bits != 0, it is the target of the device; reference counting
521      * will close and free it.
522      */
523     gx_device_set_target((gx_device_forward *)padev, NULL);
524     padev->bits = 0;
525     if (padev->mask != 0) {
526         (*dev_proc(padev->mask, close_device)) ((gx_device *) padev->mask);
527         gs_free_object(mem, padev->mask, "pattern_accum_close(mask)");
528         padev->mask = 0;
529     }
530 
531     if (padev->transbuff != 0) {
532         gs_free_object(mem,padev->target,"pattern_accum_close(transbuff)");
533         padev->transbuff = NULL;
534     }
535 
536     /* Un-retain the device now, so reference counting will free it. */
537     gx_device_retain(dev, false);
538     return 0;
539 }
540 
541 /* _hl_color */
542 static int
pattern_accum_fill_rectangle_hl_color(gx_device * dev,const gs_fixed_rect * rect,const gs_gstate * pgs,const gx_drawing_color * pdcolor,const gx_clip_path * pcpath)543 pattern_accum_fill_rectangle_hl_color(gx_device *dev, const gs_fixed_rect *rect,
544                                       const gs_gstate *pgs,
545                                       const gx_drawing_color *pdcolor,
546                                       const gx_clip_path *pcpath)
547 {
548     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *) dev;
549     int code;
550 
551     if (padev->bits) {
552         code = (*dev_proc(padev->target, fill_rectangle_hl_color))
553             (padev->target, rect, pgs, pdcolor, pcpath);
554         if (code < 0)
555             return code;
556     }
557     if (padev->mask) {
558         int x, y, w, h;
559 
560         x = fixed2int(rect->p.x);
561         y = fixed2int(rect->p.y);
562         w = fixed2int(rect->q.x) - x;
563         h = fixed2int(rect->q.y) - y;
564 
565         return (*dev_proc(padev->mask, fill_rectangle))
566             ((gx_device *) padev->mask, x, y, w, h, (gx_color_index) 1);
567     }
568     return 0;
569 }
570 
571 /* Fill a rectangle */
572 static int
pattern_accum_fill_rectangle(gx_device * dev,int x,int y,int w,int h,gx_color_index color)573 pattern_accum_fill_rectangle(gx_device * dev, int x, int y, int w, int h,
574                              gx_color_index color)
575 {
576     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *) dev;
577 
578     if (padev->bits)
579         (*dev_proc(padev->target, fill_rectangle))
580             (padev->target, x, y, w, h, color);
581     if (padev->mask)
582         return (*dev_proc(padev->mask, fill_rectangle))
583             ((gx_device *) padev->mask, x, y, w, h, (gx_color_index) 1);
584      else
585         return 0;
586 }
587 
588 /* Copy a monochrome bitmap. */
589 static int
pattern_accum_copy_mono(gx_device * dev,const byte * data,int data_x,int raster,gx_bitmap_id id,int x,int y,int w,int h,gx_color_index color0,gx_color_index color1)590 pattern_accum_copy_mono(gx_device * dev, const byte * data, int data_x,
591                     int raster, gx_bitmap_id id, int x, int y, int w, int h,
592                         gx_color_index color0, gx_color_index color1)
593 {
594     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *) dev;
595 
596     /* opt out early if nothing to render (some may think this a bug) */
597     if (color0 == gx_no_color_index && color1 == gx_no_color_index)
598         return 0;
599     if (padev->bits)
600         (*dev_proc(padev->target, copy_mono))
601             (padev->target, data, data_x, raster, id, x, y, w, h,
602              color0, color1);
603     if (padev->mask) {
604         if (color0 != gx_no_color_index)
605             color0 = 1;
606         if (color1 != gx_no_color_index)
607             color1 = 1;
608         if (color0 == 1 && color1 == 1)
609             return (*dev_proc(padev->mask, fill_rectangle))
610                 ((gx_device *) padev->mask, x, y, w, h, (gx_color_index) 1);
611         else
612             return (*dev_proc(padev->mask, copy_mono))
613                 ((gx_device *) padev->mask, data, data_x, raster, id, x, y, w, h,
614                  color0, color1);
615     } else
616         return 0;
617 }
618 
619 /* Copy a color bitmap. */
620 static int
pattern_accum_copy_color(gx_device * dev,const byte * data,int data_x,int raster,gx_bitmap_id id,int x,int y,int w,int h)621 pattern_accum_copy_color(gx_device * dev, const byte * data, int data_x,
622                     int raster, gx_bitmap_id id, int x, int y, int w, int h)
623 {
624     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *) dev;
625 
626     if (padev->bits)
627         (*dev_proc(padev->target, copy_color))
628             (padev->target, data, data_x, raster, id, x, y, w, h);
629     if (padev->mask)
630         return (*dev_proc(padev->mask, fill_rectangle))
631             ((gx_device *) padev->mask, x, y, w, h, (gx_color_index) 1);
632     else
633         return 0;
634 }
635 
636 /* Copy a color plane. */
637 static int
pattern_accum_copy_planes(gx_device * dev,const byte * data,int data_x,int raster,gx_bitmap_id id,int x,int y,int w,int h,int plane_height)638 pattern_accum_copy_planes(gx_device * dev, const byte * data, int data_x,
639                           int raster, gx_bitmap_id id,
640                           int x, int y, int w, int h, int plane_height)
641 {
642     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *) dev;
643 
644     if (padev->bits)
645         (*dev_proc(padev->target, copy_planes))
646             (padev->target, data, data_x, raster, id, x, y, w, h, plane_height);
647     if (padev->mask)
648         return (*dev_proc(padev->mask, fill_rectangle))
649             ((gx_device *) padev->mask, x, y, w, h, (gx_color_index) 1);
650     else
651         return 0;
652 }
653 
654 static int
blank_unmasked_bits(gx_device * mask,int polarity,int num_comps,int depth,const gs_int_rect * prect,gs_get_bits_params_t * p)655 blank_unmasked_bits(gx_device * mask,
656                     int polarity,
657                     int num_comps,
658                     int depth,
659                     const gs_int_rect *prect,
660                     gs_get_bits_params_t *p)
661 {
662     static const int required_options = GB_COLORS_NATIVE
663                        | GB_ALPHA_NONE
664                        | GB_RETURN_COPY
665                        | GB_ALIGN_STANDARD
666                        | GB_OFFSET_0
667                        | GB_RASTER_STANDARD;
668     int raster = p->raster;
669     byte *min;
670     int x0 = prect->p.x;
671     int y0 = prect->p.y;
672     int x, y;
673     int w = prect->q.x - x0;
674     int h = prect->q.y - y0;
675     int code = 0;
676     byte *ptr;
677     int blank = (polarity == GX_CINFO_POLARITY_ADDITIVE ? 255 : 0);
678 
679     if ((p->options & required_options) != required_options)
680         return_error(gs_error_rangecheck);
681 
682     min = gs_alloc_bytes(mask->memory, (w+7)>>3, "blank_unmasked_bits");
683     if (min == NULL)
684         return_error(gs_error_VMerror);
685 
686     if (p->options & GB_PACKING_CHUNKY)
687     {
688         if ((depth & 7) != 0 || depth > 64)
689             return_error(gs_error_rangecheck);
690         ptr = p->data[0];
691         depth >>= 3;
692         raster -= w*depth;
693         for (y = 0; y < h; y++)
694         {
695             byte *mine;
696             code = dev_proc(mask, get_bits)(mask, y+y0, min, &mine);
697             if (code < 0)
698                 goto fail;
699             for (x = 0; x < w; x++)
700             {
701                 int xx = x+x0;
702                 if (((mine[xx>>3]>>(x&7)) & 1) == 0) {
703                     switch (depth)
704                     {
705                     case 8:
706                         *ptr++ = blank;
707                     case 7:
708                         *ptr++ = blank;
709                     case 6:
710                         *ptr++ = blank;
711                     case 5:
712                         *ptr++ = blank;
713                     case 4:
714                         *ptr++ = blank;
715                     case 3:
716                         *ptr++ = blank;
717                     case 2:
718                         *ptr++ = blank;
719                     case 1:
720                         *ptr++ = blank;
721                         break;
722                     }
723                 } else {
724                     ptr += depth;
725                 }
726             }
727             ptr += raster;
728         }
729     } else {
730         if (depth/num_comps != 8)
731             return_error(gs_error_rangecheck);
732         for (y = 0; y < h; y++)
733         {
734             int c;
735             byte *mine;
736             code = dev_proc(mask, get_bits)(mask, y+y0, min, &mine);
737             if (code < 0)
738                 goto fail;
739             for (c = 0; c < num_comps; c++)
740             {
741                 if (p->data[c] == NULL)
742                     continue;
743                 ptr = p->data[c] + raster * y;
744                 for (x = 0; x < w; x++)
745                 {
746                     int xx = x+x0;
747                     if (((mine[xx>>3]>>(x&7)) & 1) == 0) {
748                         *ptr++ = blank;
749                     } else {
750                         ptr++;
751                     }
752                 }
753             }
754         }
755     }
756 
757 fail:
758     gs_free_object(mask->memory, min, "blank_unmasked_bits");
759 
760     return code;
761 }
762 
763 /* Read back a rectangle of bits. */
764 /****** SHOULD USE MASK TO DEFINE UNREAD AREA *****/
765 static int
pattern_accum_get_bits_rectangle(gx_device * dev,const gs_int_rect * prect,gs_get_bits_params_t * params,gs_int_rect ** unread)766 pattern_accum_get_bits_rectangle(gx_device * dev, const gs_int_rect * prect,
767                        gs_get_bits_params_t * params, gs_int_rect ** unread)
768 {
769     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *) dev;
770     int code;
771     gs_get_bits_params_t params2 = *params;
772 
773     if (padev->bits) {
774         if (padev->mask)
775             params2.options &= ~GB_RETURN_POINTER;
776         code = (*dev_proc(padev->target, get_bits_rectangle))
777             (padev->target, prect, &params2, unread);
778         /* If we have a mask, then unmarked pixels of the bits
779          * will be undefined. Strictly speaking it makes no
780          * sense for us to return any value here, but the only
781          * caller of this currently is the overprint code, which
782          * uses the the values to parrot back to us. Let's
783          * make sure they are set to the default 'empty' values.
784          */
785         if (code >= 0 && padev->mask)
786             code = blank_unmasked_bits((gx_device *)padev->mask,
787                                        padev->target->color_info.polarity,
788                                        padev->target->color_info.num_components,
789                                        padev->target->color_info.depth,
790                                        prect, &params2);
791         return code;
792     }
793 
794     return_error(gs_error_Fatal); /* shouldn't happen */
795 }
796 
797 /* ------ Color space implementation ------ */
798 
799 /* Free all entries in a pattern cache. */
800 static bool
pattern_cache_choose_all(gx_color_tile * ctile,void * proc_data)801 pattern_cache_choose_all(gx_color_tile * ctile, void *proc_data)
802 {
803     return true;
804 }
805 static void
pattern_cache_free_all(gx_pattern_cache * pcache)806 pattern_cache_free_all(gx_pattern_cache * pcache)
807 {
808     gx_pattern_cache_winnow(pcache, pattern_cache_choose_all, NULL);
809 }
810 
811 /* Allocate a Pattern cache. */
812 gx_pattern_cache *
gx_pattern_alloc_cache(gs_memory_t * mem,uint num_tiles,ulong max_bits)813 gx_pattern_alloc_cache(gs_memory_t * mem, uint num_tiles, ulong max_bits)
814 {
815     gx_pattern_cache *pcache =
816     gs_alloc_struct(mem, gx_pattern_cache, &st_pattern_cache,
817                     "gx_pattern_alloc_cache(struct)");
818     gx_color_tile *tiles =
819     gs_alloc_struct_array(mem, num_tiles, gx_color_tile,
820                           &st_color_tile_element,
821                           "gx_pattern_alloc_cache(tiles)");
822     uint i;
823 
824     if (pcache == 0 || tiles == 0) {
825         gs_free_object(mem, tiles, "gx_pattern_alloc_cache(tiles)");
826         gs_free_object(mem, pcache, "gx_pattern_alloc_cache(struct)");
827         return 0;
828     }
829     pcache->memory = mem;
830     pcache->tiles = tiles;
831     pcache->num_tiles = num_tiles;
832     pcache->tiles_used = 0;
833     pcache->next = 0;
834     pcache->bits_used = 0;
835     pcache->max_bits = max_bits;
836     pcache->free_all = pattern_cache_free_all;
837     for (i = 0; i < num_tiles; tiles++, i++) {
838         tiles->id = gx_no_bitmap_id;
839         /* Clear the pointers to pacify the GC. */
840         uid_set_invalid(&tiles->uid);
841         tiles->bits_used = 0;
842 #ifdef PACIFY_VALGRIND
843         /* The following memsets are required to avoid a valgrind warning
844          * in:
845          *   gs -I./gs/lib -sOutputFile=out.pgm -dMaxBitmap=10000
846          *      -sDEVICE=pgmraw -r300 -Z: -sDEFAULTPAPERSIZE=letter
847          *      -dNOPAUSE -dBATCH -K2000000 -dClusterJob -dJOBSERVER
848          *      tests_private/ps/ps3cet/11-14.PS
849          * Setting the individual elements of the structures directly is
850          * not enough, which leads me to believe that we are writing the
851          * entire structs out, padding and all.
852          */
853         memset(&tiles->tbits, 0, sizeof(tiles->tbits));
854         memset(&tiles->tmask, 0, sizeof(tiles->tmask));
855 #else
856         tiles->tbits.data = 0;
857         tiles->tmask.data = 0;
858 #endif
859         tiles->index = i;
860         tiles->cdev = NULL;
861         tiles->ttrans = NULL;
862         tiles->is_planar = false;
863     }
864     return pcache;
865 }
866 /* Ensure that an imager has a Pattern cache. */
867 static int
ensure_pattern_cache(gs_gstate * pgs)868 ensure_pattern_cache(gs_gstate * pgs)
869 {
870     if (pgs->pattern_cache == 0) {
871         gx_pattern_cache *pcache =
872         gx_pattern_alloc_cache(pgs->memory,
873                                gx_pat_cache_default_tiles(),
874                                gx_pat_cache_default_bits());
875 
876         if (pcache == 0)
877             return_error(gs_error_VMerror);
878         pgs->pattern_cache = pcache;
879     }
880     return 0;
881 }
882 
883 /* Free pattern cache and its components. */
884 void
gx_pattern_cache_free(gx_pattern_cache * pcache)885 gx_pattern_cache_free(gx_pattern_cache *pcache)
886 {
887     if (pcache == NULL)
888         return;
889     pattern_cache_free_all(pcache);
890     gs_free_object(pcache->memory, pcache->tiles, "gx_pattern_cache_free");
891     pcache->tiles = NULL;
892     gs_free_object(pcache->memory, pcache, "gx_pattern_cache_free");
893 }
894 
895 /* Get and set the Pattern cache in a gstate. */
896 gx_pattern_cache *
gstate_pattern_cache(gs_gstate * pgs)897 gstate_pattern_cache(gs_gstate * pgs)
898 {
899     return pgs->pattern_cache;
900 }
901 void
gstate_set_pattern_cache(gs_gstate * pgs,gx_pattern_cache * pcache)902 gstate_set_pattern_cache(gs_gstate * pgs, gx_pattern_cache * pcache)
903 {
904     pgs->pattern_cache = pcache;
905 }
906 
907 /* Free a Pattern cache entry. */
908 /* This will not free a pattern if it is 'locked' which should only be for */
909 /* a stroke pattern during fill_stroke_path.                               */
910 static void
gx_pattern_cache_free_entry(gx_pattern_cache * pcache,gx_color_tile * ctile)911 gx_pattern_cache_free_entry(gx_pattern_cache * pcache, gx_color_tile * ctile)
912 {
913     gx_device *temp_device;
914 
915     if ((ctile->id != gx_no_bitmap_id) && !ctile->is_dummy && !ctile->is_locked) {
916         gs_memory_t *mem = pcache->memory;
917 
918         /*
919          * We must initialize the memory device properly, even though
920          * we aren't using it for drawing.
921          */
922         if (ctile->tmask.data != 0) {
923             gs_free_object(mem, ctile->tmask.data,
924                            "free_pattern_cache_entry(mask data)");
925             ctile->tmask.data = 0;      /* for GC */
926         }
927         if (ctile->tbits.data != 0) {
928             gs_free_object(mem, ctile->tbits.data,
929                            "free_pattern_cache_entry(bits data)");
930             ctile->tbits.data = 0;      /* for GC */
931         }
932         if (ctile->cdev != NULL) {
933             ctile->cdev->common.do_not_open_or_close_bandfiles = false;  /* make sure memfile gets freed/closed */
934             dev_proc(&ctile->cdev->common, close_device)((gx_device *)&ctile->cdev->common);
935             /* Free up the icc based stuff in the clist device.  I am puzzled
936                why the other objects are not released */
937             clist_free_icc_table(ctile->cdev->common.icc_table,
938                             ctile->cdev->common.memory);
939             ctile->cdev->common.icc_table = NULL;
940             rc_decrement(ctile->cdev->common.icc_cache_cl,
941                             "gx_pattern_cache_free_entry");
942             ctile->cdev->common.icc_cache_cl = NULL;
943             ctile->cdev->writer.pinst = NULL;
944             gs_free_object(ctile->cdev->common.memory->non_gc_memory, ctile->cdev->common.cache_chunk, "free tile cache for clist");
945             ctile->cdev->common.cache_chunk = 0;
946             temp_device = (gx_device *)ctile->cdev;
947             gx_device_retain(temp_device, false);
948             ctile->cdev = NULL;
949         }
950 
951         if (ctile->ttrans != NULL) {
952             if_debug2m('v', mem,
953                        "[v*] Freeing trans pattern from cache, uid = %ld id = %ld \n",
954                        ctile->uid.id, ctile->id);
955             if ( ctile->ttrans->pdev14 == NULL) {
956                 /* This can happen if we came from the clist */
957                 if (ctile->ttrans->mem != NULL)
958                     gs_free_object(ctile->ttrans->mem ,ctile->ttrans->transbytes,
959                                    "free_pattern_cache_entry(transbytes)");
960                 gs_free_object(mem,ctile->ttrans->fill_trans_buffer,
961                                 "free_pattern_cache_entry(fill_trans_buffer)");
962                 ctile->ttrans->transbytes = NULL;
963                 ctile->ttrans->fill_trans_buffer = NULL;
964             } else {
965                 dev_proc(ctile->ttrans->pdev14, close_device)((gx_device *)ctile->ttrans->pdev14);
966                 temp_device = (gx_device *)(ctile->ttrans->pdev14);
967                 gx_device_retain(temp_device, false);
968                 rc_decrement(temp_device,"gx_pattern_cache_free_entry");
969                 ctile->ttrans->pdev14 = NULL;
970                 ctile->ttrans->transbytes = NULL;  /* should be ok due to pdf14_close */
971                 ctile->ttrans->fill_trans_buffer = NULL; /* This is always freed */
972             }
973 
974             gs_free_object(mem, ctile->ttrans,
975                            "free_pattern_cache_entry(ttrans)");
976             ctile->ttrans = NULL;
977 
978         }
979 
980         pcache->tiles_used--;
981         pcache->bits_used -= ctile->bits_used;
982         ctile->id = gx_no_bitmap_id;
983     }
984 }
985 
986 /* Given the size of a new pattern tile, free entries from the cache until  */
987 /* enough space is available (or nothing left to free).                     */
988 /* This will allow 1 oversized entry                                        */
989 void
gx_pattern_cache_ensure_space(gs_gstate * pgs,int needed)990 gx_pattern_cache_ensure_space(gs_gstate * pgs, int needed)
991 {
992     int code = ensure_pattern_cache(pgs);
993     gx_pattern_cache *pcache;
994     int start_free_id;
995 
996     if (code < 0)
997         return;                 /* no cache -- just exit */
998 
999     pcache = pgs->pattern_cache;
1000     start_free_id = pcache->next;	/* for scan wrap check */
1001     /* If too large then start freeing entries */
1002     /* By starting just after 'next', we attempt to first free the oldest entries */
1003     while (pcache->bits_used + needed > pcache->max_bits &&
1004            pcache->bits_used != 0) {
1005         pcache->next = (pcache->next + 1) % pcache->num_tiles;
1006         gx_pattern_cache_free_entry(pcache, &pcache->tiles[pcache->next]);
1007         /* since a pattern may be temporarily locked (stroke pattern for fill_stroke_path) */
1008         /* we may not have freed all entries even though we've scanned the entire cache.   */
1009         /* The following check for wrapping prevents infinite loop if stroke pattern was   */
1010         /* larger than pcache->max_bits,                                                   */
1011         if (pcache->next == start_free_id)
1012             break;		/* we wrapped -- cache may not be empty */
1013     }
1014 }
1015 
1016 /* Export updating the pattern_cache bits_used and tiles_used for clist reading */
1017 void
gx_pattern_cache_update_used(gs_gstate * pgs,ulong used)1018 gx_pattern_cache_update_used(gs_gstate *pgs, ulong used)
1019 {
1020     gx_pattern_cache *pcache = pgs->pattern_cache;
1021 
1022     pcache->bits_used += used;
1023     pcache->tiles_used++;
1024 }
1025 
1026 /*
1027  * Add a Pattern cache entry.  This is exported for the interpreter.
1028  * Note that this does not free any of the data in the accumulator
1029  * device, but it may zero out the bitmap_memory pointers to prevent
1030  * the accumulated bitmaps from being freed when the device is closed.
1031  */
1032 static void make_bitmap(gx_strip_bitmap *, const gx_device_memory *, gx_bitmap_id, const gs_memory_t *);
1033 int
gx_pattern_cache_add_entry(gs_gstate * pgs,gx_device_forward * fdev,gx_color_tile ** pctile,gs_gstate * saved)1034 gx_pattern_cache_add_entry(gs_gstate * pgs,
1035                    gx_device_forward * fdev, gx_color_tile ** pctile, gs_gstate* saved)
1036 {
1037     gx_pattern_cache *pcache;
1038     const gs_pattern1_instance_t *pinst;
1039     ulong used = 0, mask_used = 0, trans_used = 0;
1040     gx_bitmap_id id;
1041     gx_color_tile *ctile;
1042     int code = ensure_pattern_cache(pgs);
1043     extern dev_proc_open_device(pattern_clist_open_device);
1044     gx_device_memory *mmask = NULL;
1045     gx_device_memory *mbits = NULL;
1046     gx_pattern_trans_t *trans = NULL;
1047     int size_b, size_c;
1048 
1049     if (code < 0)
1050         return code;
1051     pcache = pgs->pattern_cache;
1052 
1053     if (dev_proc(fdev, open_device) != pattern_clist_open_device) {
1054         gx_device_pattern_accum *padev = (gx_device_pattern_accum *)fdev;
1055 
1056         mbits = padev->bits;
1057         mmask = padev->mask;
1058         pinst = padev->instance;
1059         trans = padev->transbuff;
1060 
1061         /*
1062          * Check whether the pattern completely fills its box.
1063          * If so, we can avoid the expensive masking operations
1064          * when using the pattern.
1065          */
1066         /* Bug 700624: In cases where the mask is completely full,
1067          * but the pattern cells are separated from one another,
1068          * we need to leave gaps between the cells when rendering
1069          * them. Sadly, the graphics library can't cope with this
1070          * in the no-mask case. Therefore, only do the optimisation
1071          * of not sending the mask if the step matrix is suitable.
1072          *
1073          * To do this, we compare the step matrix to the size. My
1074          * belief is that the mask will only ever be full if it's
1075          * orthogonal, cos otherwise the edges will be clipped,
1076          * hence we lose no generality by checking for .xy and .yx
1077          * being 0.
1078          */
1079         if (mmask != 0 &&
1080             fabsf(pinst->step_matrix.xx) <= pinst->size.x &&
1081             fabsf(pinst->step_matrix.yy) <= pinst->size.y &&
1082             pinst->step_matrix.xy == 0 &&
1083             pinst->step_matrix.yx == 0) {
1084             int y;
1085             int w_less_8 = mmask->width-8;
1086 
1087             for (y = 0; y < mmask->height; y++) {
1088                 const byte *row = scan_line_base(mmask, y);
1089                 int w;
1090 
1091                 for (w = w_less_8; w > 0; w -= 8)
1092                     if (*row++ != 0xff)
1093                         goto keep;
1094                 w += 8;
1095                 if ((*row | (0xff >> w)) != 0xff)
1096                     goto keep;
1097             }
1098             /* We don't need a mask. */
1099             mmask = 0;
1100           keep:;
1101         }
1102         /* Need to get size of buffers that are being added to the cache */
1103         if (mbits != 0)
1104             gdev_mem_bitmap_size(mbits, &used);
1105         if (mmask != 0) {
1106             gdev_mem_bitmap_size(mmask, &mask_used);
1107             used += mask_used;
1108         }
1109         if (trans != 0) {
1110             trans_used = trans->planestride*trans->n_chan;
1111             used += trans_used;
1112         }
1113     } else {
1114         gx_device_clist *cdev = (gx_device_clist *)fdev;
1115         gx_device_clist_writer * cldev = (gx_device_clist_writer *)cdev;
1116 
1117         code = clist_end_page(cldev);
1118         if (code < 0)
1119             return code;
1120         pinst = cdev->writer.pinst;
1121         size_b = clist_data_size(cdev, 0);
1122         if (size_b < 0)
1123             return_error(gs_error_unregistered);
1124         size_c = clist_data_size(cdev, 1);
1125         if (size_c < 0)
1126             return_error(gs_error_unregistered);
1127         /* The memfile size is the size, not the size determined by the depth*width*height */
1128         used = size_b + size_c;
1129     }
1130     id = pinst->id;
1131     ctile = &pcache->tiles[id % pcache->num_tiles];
1132     gx_pattern_cache_free_entry(pcache, ctile);         /* ensure that this cache slot is empty */
1133     ctile->id = id;
1134     ctile->is_planar = pinst->is_planar;
1135     ctile->depth = fdev->color_info.depth;
1136     ctile->uid = pinst->templat.uid;
1137     ctile->tiling_type = pinst->templat.TilingType;
1138     ctile->step_matrix = pinst->step_matrix;
1139     ctile->bbox = pinst->bbox;
1140     ctile->is_simple = pinst->is_simple;
1141     ctile->has_overlap = pinst->has_overlap;
1142     ctile->is_dummy = false;
1143     ctile->is_locked = false;
1144     if (pinst->templat.uses_transparency) {
1145         /* to work with pdfi get the blend mode out of the saved pgs device */
1146         ctile->blending_mode = ((pdf14_device*)(saved->device))->blend_mode;
1147     }
1148     else
1149         ctile->blending_mode = 0;
1150     ctile->trans_group_popped = false;
1151     if (dev_proc(fdev, open_device) != pattern_clist_open_device) {
1152         if (mbits != 0) {
1153             make_bitmap(&ctile->tbits, mbits, gs_next_ids(pgs->memory, 1), pgs->memory);
1154             mbits->bitmap_memory = 0;   /* don't free the bits */
1155         } else
1156             ctile->tbits.data = 0;
1157         if (mmask != 0) {
1158             make_bitmap(&ctile->tmask, mmask, id, pgs->memory);
1159             mmask->bitmap_memory = 0;   /* don't free the bits */
1160         } else
1161             ctile->tmask.data = 0;
1162         if (trans != 0) {
1163             if_debug2m('v', pgs->memory,
1164                        "[v*] Adding trans pattern to cache, uid = %ld id = %ld \n",
1165                        ctile->uid.id, ctile->id);
1166             ctile->ttrans = trans;
1167         }
1168 
1169         ctile->cdev = NULL;
1170     } else {
1171         gx_device_clist *cdev = (gx_device_clist *)fdev;
1172         gx_device_clist_writer *cwdev = (gx_device_clist_writer *)fdev;
1173 
1174         ctile->tbits.data = 0;
1175         ctile->tbits.size.x = 0;
1176         ctile->tbits.size.y = 0;
1177         ctile->tmask.data = 0;
1178         ctile->tmask.size.x = 0;
1179         ctile->tmask.size.y = 0;
1180         ctile->cdev = cdev;
1181         /* Prevent freeing files on pattern_paint_cleanup : */
1182         cwdev->do_not_open_or_close_bandfiles = true;
1183     }
1184     /* In the clist case, used is accurate. In the non-clist case, it may
1185      * not be. The important thing is that we account the same for tiles
1186      * going in and coming out of the cache. Therefore we store the used
1187      * figure in the tile so we always remove the same amount. */
1188     ctile->bits_used = used;
1189     gx_pattern_cache_update_used(pgs, used);
1190 
1191     *pctile = ctile;
1192     return 0;
1193 }
1194 
1195 /* set or clear the 'is_locked' flag for a tile in the cache. Used by	*/
1196 /* fill_stroke_path to make sure a large stroke pattern stays in the	*/
1197 /* cache even if the fill is also a pattern.				*/
1198 int
gx_pattern_cache_entry_set_lock(gs_gstate * pgs,gs_id id,bool new_lock_value)1199 gx_pattern_cache_entry_set_lock(gs_gstate *pgs, gs_id id, bool new_lock_value)
1200 {
1201     gx_pattern_cache *pcache;
1202     gx_color_tile *ctile;
1203     int code = ensure_pattern_cache(pgs);
1204 
1205     if (code < 0)
1206         return code;
1207     pcache = pgs->pattern_cache;
1208     ctile = &pcache->tiles[id % pcache->num_tiles];
1209     if (ctile->id != id)
1210         return_error(gs_error_undefined);
1211     ctile->is_locked = new_lock_value;
1212     return 0;
1213 }
1214 
1215 /* Get entry for reading a pattern from clist. */
1216 int
gx_pattern_cache_get_entry(gs_gstate * pgs,gs_id id,gx_color_tile ** pctile)1217 gx_pattern_cache_get_entry(gs_gstate * pgs, gs_id id, gx_color_tile ** pctile)
1218 {
1219     gx_pattern_cache *pcache;
1220     gx_color_tile *ctile;
1221     int code = ensure_pattern_cache(pgs);
1222 
1223     if (code < 0)
1224         return code;
1225     pcache = pgs->pattern_cache;
1226     ctile = &pcache->tiles[id % pcache->num_tiles];
1227     gx_pattern_cache_free_entry(pgs->pattern_cache, ctile);
1228     ctile->id = id;
1229     *pctile = ctile;
1230     return 0;
1231 }
1232 
1233 bool
gx_pattern_tile_is_clist(gx_color_tile * ptile)1234 gx_pattern_tile_is_clist(gx_color_tile *ptile)
1235 {
1236     return ptile != NULL && ptile->cdev != NULL;
1237 }
1238 
1239 /* Add a dummy Pattern cache entry.  Stubs a pattern tile for interpreter when
1240    device handles high level patterns. */
1241 int
gx_pattern_cache_add_dummy_entry(gs_gstate * pgs,gs_pattern1_instance_t * pinst,int depth)1242 gx_pattern_cache_add_dummy_entry(gs_gstate *pgs,
1243             gs_pattern1_instance_t *pinst, int depth)
1244 {
1245     gx_color_tile *ctile;
1246     gx_pattern_cache *pcache;
1247     gx_bitmap_id id = pinst->id;
1248     int code = ensure_pattern_cache(pgs);
1249 
1250     if (code < 0)
1251         return code;
1252     pcache = pgs->pattern_cache;
1253     ctile = &pcache->tiles[id % pcache->num_tiles];
1254     gx_pattern_cache_free_entry(pcache, ctile);
1255     ctile->id = id;
1256     ctile->depth = depth;
1257     ctile->uid = pinst->templat.uid;
1258     ctile->tiling_type = pinst->templat.TilingType;
1259     ctile->step_matrix = pinst->step_matrix;
1260     ctile->bbox = pinst->bbox;
1261     ctile->is_simple = pinst->is_simple;
1262     ctile->has_overlap = pinst->has_overlap;
1263     ctile->is_dummy = true;
1264     ctile->is_locked = false;
1265     memset(&ctile->tbits, 0 , sizeof(ctile->tbits));
1266     ctile->tbits.size = pinst->size;
1267     ctile->tbits.id = gs_no_bitmap_id;
1268     memset(&ctile->tmask, 0 , sizeof(ctile->tmask));
1269     ctile->cdev = NULL;
1270     ctile->ttrans = NULL;
1271     ctile->bits_used = 0;
1272     pcache->tiles_used++;
1273     return 0;
1274 }
1275 
1276 #if RAW_PATTERN_DUMP
1277 /* Debug dump of pattern image data. Saved in
1278    interleaved form with global indexing in
1279    file name */
1280 static void
dump_raw_pattern(int height,int width,int n_chan,int depth,byte * Buffer,int raster,const gx_device_memory * mdev,const gs_memory_t * memory)1281 dump_raw_pattern(int height, int width, int n_chan, int depth,
1282                 byte *Buffer, int raster, const gx_device_memory * mdev,
1283                 const gs_memory_t *memory)
1284 {
1285     char full_file_name[50];
1286     gp_file *fid;
1287     int max_bands;
1288     int j, k, m;
1289     int byte_number, bit_position;
1290     unsigned char current_byte;
1291     unsigned char output_val;
1292     bool is_planar;
1293     byte *curr_ptr = Buffer;
1294     int plane_offset;
1295 
1296     is_planar = mdev->is_planar;
1297     max_bands = ( n_chan < 57 ? n_chan : 56);   /* Photoshop handles at most 56 bands */
1298     if (is_planar) {
1299         gs_sprintf(full_file_name, "%d)PATTERN_PLANE_%dx%dx%d.raw", global_pat_index,
1300                 mdev->raster, height, max_bands);
1301     } else {
1302         gs_sprintf(full_file_name, "%d)PATTERN_CHUNK_%dx%dx%d.raw", global_pat_index,
1303                 width, height, max_bands);
1304     }
1305     fid = gp_fopen(memory,full_file_name,"wb");
1306     if (depth >= 8) {
1307         /* Contone data. */
1308         if (is_planar) {
1309             for (m = 0; m < max_bands; m++) {
1310                 curr_ptr = mdev->line_ptrs[m*mdev->height];
1311                 gp_fwrite(curr_ptr, 1, mdev->height * mdev->raster, fid);
1312             }
1313         } else {
1314             /* Just dump it like it is */
1315             gp_fwrite(Buffer, 1, max_bands * height * width, fid);
1316         }
1317     } else {
1318         /* Binary Data. Lets get to 8 bit for debugging.  We have to
1319            worry about planar vs. chunky.  Note this assumes 1 bit data
1320            only. */
1321         if (is_planar) {
1322             plane_offset = mdev->raster * mdev->height;
1323             for (m = 0; m < max_bands; m++) {
1324                 curr_ptr = mdev->line_ptrs[m*mdev->height];
1325                 for (j = 0; j < height; j++) {
1326                     for (k = 0; k < width; k++) {
1327                         byte_number = (int) ceil((( (float) k + 1.0) / 8.0)) - 1;
1328                         current_byte = curr_ptr[j*(mdev->raster) + byte_number];
1329                         bit_position = 7 - (k -  byte_number*8);
1330                         output_val = ((current_byte >> bit_position) & 0x1) * 255;
1331                         gp_fwrite(&output_val,1,1,fid);
1332                     }
1333                 }
1334             }
1335         } else {
1336             for (j = 0; j < height; j++) {
1337                 for (k = 0; k < width; k++) {
1338                     for (m = 0; m < max_bands; m++) {
1339                         /* index current byte */
1340                         byte_number =
1341                             (int) ceil((( (float) k * (float) max_bands +
1342                                           (float) m + 1.0) / 8.0)) - 1;
1343                         /* get byte of interest */
1344                         current_byte =
1345                                 curr_ptr[j*(mdev->raster) + byte_number];
1346                         /* get bit position */
1347                         bit_position =
1348                                 7 - (k * max_bands + m -  byte_number * 8);
1349                         /* extract and create byte */
1350                         output_val =
1351                                 ((current_byte >> bit_position) & 0x1) * 255;
1352                         gp_fwrite(&output_val,1,1,fid);
1353                     }
1354                 }
1355             }
1356         }
1357     }
1358     gp_fclose(fid);
1359 }
1360 #endif
1361 
1362 static void
make_bitmap(register gx_strip_bitmap * pbm,const gx_device_memory * mdev,gx_bitmap_id id,const gs_memory_t * memory)1363 make_bitmap(register gx_strip_bitmap * pbm, const gx_device_memory * mdev,
1364             gx_bitmap_id id, const gs_memory_t *memory)
1365 {
1366     pbm->data = mdev->base;
1367     pbm->raster = mdev->raster;
1368     pbm->rep_width = pbm->size.x = mdev->width;
1369     pbm->rep_height = pbm->size.y = mdev->height;
1370     pbm->id = id;
1371     pbm->rep_shift = pbm->shift = 0;
1372     pbm->num_planes = (mdev->is_planar ? mdev->color_info.num_components : 1);
1373 
1374         /* Lets dump this for debug purposes */
1375 
1376 #if RAW_PATTERN_DUMP
1377     dump_raw_pattern(pbm->rep_height, pbm->rep_width,
1378                         mdev->color_info.num_components,
1379                         mdev->color_info.depth,
1380                         (unsigned char*) mdev->base,
1381                         pbm->raster, mdev, memory);
1382 
1383         global_pat_index++;
1384 
1385 #endif
1386 
1387 }
1388 
1389 /* Purge selected entries from the pattern cache. */
1390 void
gx_pattern_cache_winnow(gx_pattern_cache * pcache,bool (* proc)(gx_color_tile * ctile,void * proc_data),void * proc_data)1391 gx_pattern_cache_winnow(gx_pattern_cache * pcache,
1392   bool(*proc) (gx_color_tile * ctile, void *proc_data), void *proc_data)
1393 {
1394     uint i;
1395 
1396     if (pcache == 0)            /* no cache created yet */
1397         return;
1398     for (i = 0; i < pcache->num_tiles; ++i) {
1399         gx_color_tile *ctile = &pcache->tiles[i];
1400 
1401         ctile->is_locked = false;		/* force freeing */
1402         if (ctile->id != gx_no_bitmap_id && (*proc) (ctile, proc_data))
1403             gx_pattern_cache_free_entry(pcache, ctile);
1404     }
1405 }
1406 
1407 /* blank the pattern accumulator device assumed to be in the graphics
1408    state */
1409 int
gx_erase_colored_pattern(gs_gstate * pgs)1410 gx_erase_colored_pattern(gs_gstate *pgs)
1411 {
1412     int code;
1413     gx_device_pattern_accum *pdev = (gx_device_pattern_accum *)gs_currentdevice(pgs);
1414 
1415     if ((code = gs_gsave(pgs)) < 0)
1416         return code;
1417     if ((code = gs_setgray(pgs, 1.0)) >= 0) {
1418         gs_rect rect;
1419         gx_device_memory *mask;
1420         static const gs_matrix identity = { 1, 0, 0, 1, 0, 0 };
1421 
1422         pgs->log_op = lop_default;
1423         rect.p.x = 0.0;
1424         rect.p.y = 0.0;
1425         rect.q.x = (double)pdev->width;
1426         rect.q.y = (double)pdev->height;
1427 
1428         code = gs_setmatrix(pgs, &identity);
1429         if (code < 0) {
1430             gs_grestore_only(pgs);
1431             return code;
1432         }
1433         /* we don't want the fill rectangle device call to use the
1434            mask */
1435         mask = pdev->mask;
1436         pdev->mask = NULL;
1437         code = gs_rectfill(pgs, &rect, 1);
1438         /* restore the mask */
1439         pdev->mask = mask;
1440         if (code < 0) {
1441             gs_grestore_only(pgs);
1442             return code;
1443         }
1444     }
1445     /* we don't need wraparound here */
1446     gs_grestore_only(pgs);
1447     return code;
1448 }
1449 
1450 /* Reload a (non-null) Pattern color into the cache. */
1451 /* *pdc is already set, except for colors.pattern.p_tile and mask.m_tile. */
1452 int
gx_pattern_load(gx_device_color * pdc,const gs_gstate * pgs,gx_device * dev,gs_color_select_t select)1453 gx_pattern_load(gx_device_color * pdc, const gs_gstate * pgs,
1454                 gx_device * dev, gs_color_select_t select)
1455 {
1456     gx_device_forward *adev = NULL;
1457     gs_pattern1_instance_t *pinst =
1458         (gs_pattern1_instance_t *)pdc->ccolor.pattern;
1459     gs_gstate *saved;
1460     gx_color_tile *ctile;
1461     gs_memory_t *mem = pgs->memory;
1462     bool has_tags = device_encodes_tags(dev);
1463     int code;
1464 
1465     if (pgs->pattern_cache == NULL)
1466         if ((code = ensure_pattern_cache((gs_gstate *) pgs))< 0)      /* break const for call */
1467             return code;
1468 
1469     if (gx_pattern_cache_lookup(pdc, pgs, dev, select))
1470         return 0;
1471 
1472     /* Get enough space in the cache for this pattern (estimated if it is a clist) */
1473     gx_pattern_cache_ensure_space((gs_gstate *)pgs, gx_pattern_size_estimate(pinst, has_tags));
1474     /*
1475      * Note that adev is an internal device, so it will be freed when the
1476      * last reference to it from a graphics state is deleted.
1477      */
1478     adev = gx_pattern_accum_alloc(mem, pgs->pattern_cache->memory, pinst, "gx_pattern_load");
1479     if (adev == 0)
1480         return_error(gs_error_VMerror);
1481     gx_device_set_target((gx_device_forward *)adev, dev);
1482     code = dev_proc(adev, open_device)((gx_device *)adev);
1483     if (code < 0) {
1484         gs_free_object(mem, adev, "gx_pattern_load");
1485         return code;
1486     }
1487     saved = gs_gstate_copy(pinst->saved, pinst->saved->memory);
1488     if (saved == 0) {
1489         code = gs_note_error(gs_error_VMerror);
1490         goto fail;
1491     }
1492     if (saved->pattern_cache == 0)
1493         saved->pattern_cache = pgs->pattern_cache;
1494     code = gs_setdevice_no_init(saved, (gx_device *)adev);
1495     if (code < 0)
1496         goto fail;
1497     if (pinst->templat.uses_transparency) {
1498         if_debug0m('v', mem, "gx_pattern_load: pushing the pdf14 compositor device into this graphics state\n");
1499         if ((code = gs_push_pdf14trans_device(saved, true, false)) < 0)
1500             return code;
1501         saved->device->is_open = true;
1502     } else {
1503         /* For colored patterns we clear the pattern device's
1504            background.  This is necessary for the anti aliasing code
1505            and (unfortunately) it masks a difficult to fix UMR
1506            affecting pcl patterns, see bug #690487.  Note we have to
1507            make a similar change in zpcolor.c where much of this
1508            pattern code is duplicated to support high level stream
1509            patterns. */
1510         if (pinst->templat.PaintType == 1 && !(pinst->is_clist)
1511             && dev_proc(pinst->saved->device, dev_spec_op)(pinst->saved->device, gxdso_pattern_can_accum, NULL, 0) == 0)
1512             if ((code = gx_erase_colored_pattern(saved)) < 0)
1513                 goto fail;
1514     }
1515 
1516     code = (*pinst->templat.PaintProc)(&pdc->ccolor, saved);
1517     if (code < 0) {
1518         if (dev_proc(adev, open_device) == pattern_accum_open) {
1519             // free pattern cache data that never got added to the dictionary
1520             gx_device_pattern_accum *padev = (gx_device_pattern_accum *) adev;
1521             if ((padev->bits != NULL) && (padev->bits->base != NULL)) {
1522                 gs_free_object(padev->bits->memory, padev->bits->base, "mem_open");
1523             }
1524         }
1525         /* RJW: At this point, in the non transparency case,
1526          * saved->device == adev. So unretain it, close it, and the
1527          * gs_gstate_free(saved) will remove it. In the transparency case,
1528          * saved->device = the pdf14 device. So we need to unretain it,
1529          * close adev, and finally close saved->device.
1530          */
1531         gx_device_retain(saved->device, false);         /* device no longer retained */
1532         if (pinst->templat.uses_transparency) {
1533             if (pinst->is_clist == 0) {
1534                 gs_free_object(((gx_device_pattern_accum *)adev)->bitmap_memory,
1535                                ((gx_device_pattern_accum *)adev)->transbuff,
1536                                "gx_pattern_load");
1537                 ((gx_device_pattern_accum *)adev)->transbuff = NULL;
1538             }
1539             dev_proc(adev, close_device)((gx_device *)adev);
1540             /* adev was the target of the pdf14 device, so also is no longer retained */
1541             gx_device_retain((gx_device *)adev, false);         /* device no longer retained */
1542         }
1543         dev_proc(saved->device, close_device)((gx_device *)saved->device);
1544         /* Freeing the state should now free the device which may be the pdf14 compositor. */
1545         gs_gstate_free_chain(saved);
1546         if (code == gs_error_handled)
1547             code = 0;
1548         return code;
1549     }
1550     if (pinst->templat.uses_transparency) {
1551         /* if_debug0m('v', saved->memory, "gx_pattern_load: popping the pdf14 compositor device from this graphics state\n");
1552         if ((code = gs_pop_pdf14trans_device(saved, true)) < 0)
1553             return code; */
1554             if (pinst->is_clist) {
1555                 /* Send the compositor command to close the PDF14 device */
1556                 code = gs_pop_pdf14trans_device(saved, true);
1557                 if (code < 0)
1558                     return code;
1559             } else {
1560                 /* Not a clist, get PDF14 buffer information */
1561                 code =
1562                     pdf14_get_buffer_information(saved->device,
1563                                                 ((gx_device_pattern_accum*)adev)->transbuff,
1564                                                  saved->memory,
1565                                                  true);
1566                 /* PDF14 device (and buffer) is destroyed when pattern cache
1567                    entry is removed */
1568                 if (code < 0)
1569                     return code;
1570             }
1571     }
1572     /* We REALLY don't like the following cast.... */
1573     code = gx_pattern_cache_add_entry((gs_gstate *)pgs,
1574                 adev, &ctile, saved);
1575     if (code >= 0) {
1576         if (!gx_pattern_cache_lookup(pdc, pgs, dev, select)) {
1577             mlprintf(mem, "Pattern cache lookup failed after insertion!\n");
1578             code = gs_note_error(gs_error_Fatal);
1579         }
1580     }
1581 #ifdef DEBUG
1582     if (gs_debug_c('B') && dev_proc(adev, open_device) == pattern_accum_open) {
1583         gx_device_pattern_accum *pdev = (gx_device_pattern_accum *)adev;
1584 
1585         if (pdev->mask)
1586             debug_dump_bitmap(pdev->memory,
1587                               pdev->mask->base, pdev->mask->raster,
1588                               pdev->mask->height, "[B]Pattern mask");
1589         if (pdev->bits)
1590             debug_dump_bitmap(pdev->memory,
1591                               ((gx_device_memory *) pdev->target)->base,
1592                               ((gx_device_memory *) pdev->target)->raster,
1593                               pdev->target->height, "[B]Pattern bits");
1594     }
1595 #endif
1596     /* Free the bookkeeping structures, except for the bits and mask */
1597     /* data iff they are still needed. */
1598     dev_proc(adev, close_device)((gx_device *)adev);
1599     /* Free the chain of gstates. Freeing the state will free the device. */
1600     gs_gstate_free_chain(saved);
1601     return code;
1602 
1603 fail:
1604     if (dev_proc(adev, open_device) == pattern_accum_open) {
1605         // free pattern cache data that never got added to the dictionary
1606         gx_device_pattern_accum *padev = (gx_device_pattern_accum *) adev;
1607         if ((padev->bits != NULL) && (padev->bits->base != NULL)) {
1608             gs_free_object(padev->bits->memory, padev->bits->base, "mem_open");
1609         }
1610     }
1611     if (dev_proc(adev, open_device) == pattern_clist_open_device) {
1612         gx_device_clist *cdev = (gx_device_clist *)adev;
1613 
1614         gs_free_object(cdev->writer.bandlist_memory, cdev->common.data, "gx_pattern_load");
1615         cdev->common.data = 0;
1616     }
1617     dev_proc(adev, close_device)((gx_device *)adev);
1618     gs_gstate_free_chain(saved);
1619     return code;
1620 }
1621 
1622 /* Remap a PatternType 1 color. */
1623 cs_proc_remap_color(gx_remap_Pattern);  /* check the prototype */
1624 int
gs_pattern1_remap_color(const gs_client_color * pc,const gs_color_space * pcs,gx_device_color * pdc,const gs_gstate * pgs,gx_device * dev,gs_color_select_t select)1625 gs_pattern1_remap_color(const gs_client_color * pc, const gs_color_space * pcs,
1626                         gx_device_color * pdc, const gs_gstate * pgs,
1627                         gx_device * dev, gs_color_select_t select)
1628 {
1629     gs_pattern1_instance_t *pinst = (gs_pattern1_instance_t *)pc->pattern;
1630     int code;
1631 
1632     /* Save original color space and color info into dev color */
1633     pdc->ccolor = *pc;
1634     pdc->ccolor_valid = true;
1635     if (pinst == 0) {
1636         /* Null pattern */
1637         color_set_null_pattern(pdc);
1638         return 0;
1639     }
1640     if (pinst->templat.PaintType == 2) {       /* uncolored */
1641         if (pcs->base_space)
1642             code = (pcs->base_space->type->remap_color)
1643                 (pc, pcs->base_space, pdc, pgs, dev, select);
1644         else
1645             code = gs_note_error(gs_error_unregistered);
1646         if (code < 0)
1647             return code;
1648         if (pdc->type == gx_dc_type_pure)
1649             pdc->type = &gx_dc_pure_masked;
1650         else if (pdc->type == gx_dc_type_ht_binary)
1651             pdc->type = &gx_dc_binary_masked;
1652         else if (pdc->type == gx_dc_type_ht_colored)
1653             pdc->type = &gx_dc_colored_masked;
1654         else if (pdc->type == gx_dc_type_devn)
1655             pdc->type = &gx_dc_devn_masked;
1656         else
1657             return_error(gs_error_unregistered);
1658     } else
1659         color_set_null_pattern(pdc);
1660     pdc->mask.id = pinst->id;
1661     pdc->mask.m_tile = 0;
1662     return gx_pattern_load(pdc, pgs, dev, select);
1663 }
1664 
1665 int
pattern_accum_dev_spec_op(gx_device * dev,int dso,void * data,int size)1666 pattern_accum_dev_spec_op(gx_device *dev, int dso, void *data, int size)
1667 {
1668     gx_device_pattern_accum *const padev = (gx_device_pattern_accum *)dev;
1669     const gs_pattern1_instance_t *pinst = padev->instance;
1670     gx_device *target =
1671         (padev->target == 0 ? gs_currentdevice(pinst->saved) :
1672          padev->target);
1673 
1674     if (dso == gxdso_in_pattern_accumulator)
1675         return (pinst->templat.PaintType == 2 ? 2 : 1);
1676     if (dso == gxdso_get_dev_param) {
1677         dev_param_req_t *request = (dev_param_req_t *)data;
1678         gs_param_list * plist = (gs_param_list *)request->list;
1679         bool bool_true = 1;
1680 
1681         if (strcmp(request->Param, "NoInterpolateImagemasks") == 0) {
1682             return param_write_bool(plist, "NoInterpolateImagemasks", &bool_true);
1683         }
1684     }
1685 
1686     return dev_proc(target, dev_spec_op)(target, dso, data, size);
1687 }
1688