1
/* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
2
/* cairo - a vector graphics library with display and print output
3
 *
4
 * Copyright © 2003 University of Southern California
5
 * Copyright © 2005 Red Hat, Inc
6
 * Copyright © 2007,2008 Adrian Johnson
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it either under the terms of the GNU Lesser General Public
10
 * License version 2.1 as published by the Free Software Foundation
11
 * (the "LGPL") or, at your option, under the terms of the Mozilla
12
 * Public License Version 1.1 (the "MPL"). If you do not alter this
13
 * notice, a recipient may use your version of this file under either
14
 * the MPL or the LGPL.
15
 *
16
 * You should have received a copy of the LGPL along with this library
17
 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
19
 * You should have received a copy of the MPL along with this library
20
 * in the file COPYING-MPL-1.1
21
 *
22
 * The contents of this file are subject to the Mozilla Public License
23
 * Version 1.1 (the "License"); you may not use this file except in
24
 * compliance with the License. You may obtain a copy of the License at
25
 * http://www.mozilla.org/MPL/
26
 *
27
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
28
 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
29
 * the specific language governing rights and limitations.
30
 *
31
 * The Original Code is the cairo graphics library.
32
 *
33
 * The Initial Developer of the Original Code is University of Southern
34
 * California.
35
 *
36
 * Contributor(s):
37
 *	Carl D. Worth <cworth@cworth.org>
38
 *	Kristian Høgsberg <krh@redhat.com>
39
 *	Keith Packard <keithp@keithp.com>
40
 *	Adrian Johnson <ajohnson@redneon.com>
41
 */
42

            
43

            
44
/*
45
 * Design of the PS output:
46
 *
47
 * The PS output is harmonised with the PDF operations using PS procedures
48
 * to emulate the PDF operators.
49
 *
50
 * This has a number of advantages:
51
 *   1. A large chunk of code is shared between the PDF and PS backends.
52
 *      See cairo-pdf-operators.
53
 *   2. Using gs to do PS -> PDF and PDF -> PS will always work well.
54
 */
55

            
56
#define _DEFAULT_SOURCE /* for ctime_r(), snprintf(), strdup() */
57
#include "cairoint.h"
58

            
59
#include "cairo-ps.h"
60
#include "cairo-ps-surface-private.h"
61

            
62
#include "cairo-pdf-operators-private.h"
63
#include "cairo-pdf-shading-private.h"
64

            
65
#include "cairo-array-private.h"
66
#include "cairo-composite-rectangles-private.h"
67
#include "cairo-default-context-private.h"
68
#include "cairo-error-private.h"
69
#include "cairo-image-info-private.h"
70
#include "cairo-image-surface-inline.h"
71
#include "cairo-list-inline.h"
72
#include "cairo-output-stream-private.h"
73
#include "cairo-paginated-private.h"
74
#include "cairo-recording-surface-inline.h"
75
#include "cairo-recording-surface-private.h"
76
#include "cairo-scaled-font-subsets-private.h"
77
#include "cairo-surface-clipper-private.h"
78
#include "cairo-surface-snapshot-inline.h"
79
#include "cairo-surface-subsurface-private.h"
80
#include "cairo-tag-attributes-private.h"
81
#include "cairo-type3-glyph-surface-private.h"
82

            
83
#include <stdio.h>
84
#include <ctype.h>
85
#include <time.h>
86
#include <zlib.h>
87
#include <errno.h>
88

            
89
/* Forms are emitted at the start and stored in memory so we limit the
90
 * total size of all forms to prevent running out of memory. If this
91
 * limit is exceeded, surfaces that would be stored in forms are
92
 * emitted each time the surface is used. */
93
#define MAX_L2_FORM_DATA (256*1024)
94
#define MAX_L3_FORM_DATA (2*1024*1024) /* Assume Level 3 printers have more memory */
95

            
96
/* #define DEBUG_PS 1 */
97

            
98
#if DEBUG_PS
99
#define DEBUG_FALLBACK(s) \
100
    fprintf (stderr, "%s::%d -- %s\n", __FUNCTION__, __LINE__, (s))
101
#else
102
#define DEBUG_FALLBACK(s)
103
#endif
104

            
105
#ifndef HAVE_CTIME_R
106
static char *ctime_r(const time_t *timep, char *buf)
107
{
108
    (void)buf;
109
    return ctime(timep);
110
}
111
#endif
112

            
113
/**
114
 * SECTION:cairo-ps
115
 * @Title: PostScript Surfaces
116
 * @Short_Description: Rendering PostScript documents
117
 * @See_Also: #cairo_surface_t
118
 *
119
 * The PostScript surface is used to render cairo graphics to Adobe
120
 * PostScript files and is a multi-page vector surface backend.
121
 *
122
 * The following mime types are supported on source patterns:
123
 * %CAIRO_MIME_TYPE_JPEG, %CAIRO_MIME_TYPE_UNIQUE_ID,
124
 * %CAIRO_MIME_TYPE_CCITT_FAX, %CAIRO_MIME_TYPE_CCITT_FAX_PARAMS,
125
 * %CAIRO_MIME_TYPE_EPS, %CAIRO_MIME_TYPE_EPS_PARAMS.
126
 *
127
 * Source surfaces used by the PostScript surface that have a
128
 * %CAIRO_MIME_TYPE_UNIQUE_ID mime type will be stored in PostScript
129
 * printer memory for the duration of the print
130
 * job. %CAIRO_MIME_TYPE_UNIQUE_ID should only be used for small
131
 * frequently used sources.
132
 *
133
 * The %CAIRO_MIME_TYPE_CCITT_FAX and %CAIRO_MIME_TYPE_CCITT_FAX_PARAMS mime types
134
 * are documented in [CCITT Fax Images][ccitt].
135
 *
136
 * # Embedding EPS files # {#eps}
137
 *
138
 * Encapsulated PostScript files can be embedded in the PS output by
139
 * setting the CAIRO_MIME_TYPE_EPS mime data on a surface to the EPS
140
 * data and painting the surface.  The EPS will be scaled and
141
 * translated to the extents of the surface the EPS data is attached
142
 * to.
143
 *
144
 * The %CAIRO_MIME_TYPE_EPS mime type requires the
145
 * %CAIRO_MIME_TYPE_EPS_PARAMS mime data to also be provided in order
146
 * to specify the embeddding parameters.  %CAIRO_MIME_TYPE_EPS_PARAMS
147
 * mime data must contain a string of the form "bbox=[llx lly urx
148
 * ury]" that specifies the bounding box (in PS coordinates) of the
149
 * EPS graphics. The parameters are: lower left x, lower left y, upper
150
 * right x, upper right y. Normally the bbox data is identical to the
151
 * \%\%\%BoundingBox data in the EPS file.
152
 *
153
 **/
154

            
155
/**
156
 * CAIRO_HAS_PS_SURFACE:
157
 *
158
 * Defined if the PostScript surface backend is available.
159
 * This macro can be used to conditionally compile backend-specific code.
160
 *
161
 * Since: 1.2
162
 **/
163

            
164
typedef enum {
165
    CAIRO_PS_COMPRESS_NONE,
166
    CAIRO_PS_COMPRESS_LZW,
167
    CAIRO_PS_COMPRESS_DEFLATE
168
} cairo_ps_compress_t;
169

            
170
typedef enum {
171
    CAIRO_EMIT_SURFACE_ANALYZE,
172
    CAIRO_EMIT_SURFACE_EMIT,
173
    CAIRO_EMIT_SURFACE_EMIT_FORM
174
} cairo_emit_surface_mode_t;
175

            
176
typedef struct  {
177
    /* input params */
178
    cairo_surface_t *src_surface;
179
    unsigned int regions_id;
180
    cairo_operator_t op;
181
    const cairo_rectangle_int_t *src_surface_extents;
182
    cairo_bool_t src_surface_bounded;
183
    const cairo_rectangle_int_t *src_op_extents; /* operation extents in src space */
184
    cairo_filter_t filter;
185
    cairo_bool_t stencil_mask; /* TRUE if source is to be used as a mask */
186

            
187
    /* output params */
188
    cairo_bool_t is_image; /* returns TRUE if PS image will be emitted */
189
                           /*         FALSE if recording will be emitted */
190
    long approx_size;
191
    int eod_count;
192
} cairo_emit_surface_params_t;
193

            
194
static const cairo_surface_backend_t cairo_ps_surface_backend;
195
static const cairo_paginated_surface_backend_t cairo_ps_surface_paginated_backend;
196

            
197
static cairo_bool_t
198
_cairo_ps_surface_get_extents (void		       *abstract_surface,
199
			       cairo_rectangle_int_t   *rectangle);
200

            
201
static void
202
_cairo_ps_form_emit (void *entry, void *closure);
203

            
204
static const cairo_ps_level_t _cairo_ps_levels[] =
205
{
206
    CAIRO_PS_LEVEL_2,
207
    CAIRO_PS_LEVEL_3
208
};
209

            
210
#define CAIRO_PS_LEVEL_LAST ARRAY_LENGTH (_cairo_ps_levels)
211

            
212
static const char * _cairo_ps_level_strings[CAIRO_PS_LEVEL_LAST] =
213
{
214
    "PS Level 2",
215
    "PS Level 3"
216
};
217

            
218
static const char *_cairo_ps_supported_mime_types[] =
219
{
220
    CAIRO_MIME_TYPE_JPEG,
221
    CAIRO_MIME_TYPE_UNIQUE_ID,
222
    CAIRO_MIME_TYPE_CCITT_FAX,
223
    CAIRO_MIME_TYPE_CCITT_FAX_PARAMS,
224
    CAIRO_MIME_TYPE_EPS,
225
    CAIRO_MIME_TYPE_EPS_PARAMS,
226
    NULL
227
};
228

            
229
typedef struct _cairo_page_standard_media {
230
    const char *name;
231
    int width;
232
    int height;
233
} cairo_page_standard_media_t;
234

            
235
static const cairo_page_standard_media_t _cairo_page_standard_media[] =
236
{
237
    { "A0",       2384, 3371 },
238
    { "A1",       1685, 2384 },
239
    { "A2",       1190, 1684 },
240
    { "A3",        842, 1190 },
241
    { "A4",        595,  842 },
242
    { "A5",        420,  595 },
243
    { "B4",        729, 1032 },
244
    { "B5",        516,  729 },
245
    { "Letter",    612,  792 },
246
    { "Tabloid",   792, 1224 },
247
    { "Ledger",   1224,  792 },
248
    { "Legal",     612, 1008 },
249
    { "Statement", 396,  612 },
250
    { "Executive", 540,  720 },
251
    { "Folio",     612,  936 },
252
    { "Quarto",    610,  780 },
253
    { "10x14",     720, 1008 },
254
};
255

            
256
typedef struct _cairo_page_media {
257
    char *name;
258
    int width;
259
    int height;
260
    cairo_list_t link;
261
} cairo_page_media_t;
262

            
263
static void
264
_cairo_ps_form_init_key (cairo_ps_form_t *key)
265
{
266
    key->base.hash = _cairo_hash_bytes (_CAIRO_HASH_INIT_VALUE,
267
					key->unique_id, key->unique_id_length);
268
}
269

            
270
static cairo_bool_t
271
_cairo_ps_form_equal (const void *key_a, const void *key_b)
272
{
273
    const cairo_ps_form_t *a = key_a;
274
    const cairo_ps_form_t *b = key_b;
275

            
276
    if (a->filter != b->filter)
277
	return FALSE;
278

            
279
    if (a->unique_id_length != b->unique_id_length)
280
	return FALSE;
281

            
282
    return memcmp (a->unique_id, b->unique_id, a->unique_id_length) == 0;
283
}
284

            
285
static void
286
_cairo_ps_form_pluck (void *entry, void *closure)
287
{
288
    cairo_ps_form_t *surface_entry = entry;
289
    cairo_hash_table_t *patterns = closure;
290

            
291
    _cairo_hash_table_remove (patterns, &surface_entry->base);
292
    free (surface_entry->unique_id);
293
    if (_cairo_surface_is_recording (surface_entry->src_surface) && surface_entry->regions_id != 0)
294
	_cairo_recording_surface_region_array_remove (surface_entry->src_surface, surface_entry->regions_id);
295
    cairo_surface_destroy (surface_entry->src_surface);
296
    free (surface_entry);
297
}
298

            
299
static void
300
5
_cairo_ps_surface_emit_header (cairo_ps_surface_t *surface)
301
{
302
    char ctime_buf[26];
303
    time_t now;
304
    char **comments;
305
    int i, num_comments;
306
    int level;
307
5
    const char *eps_header = "";
308
    cairo_bool_t has_bbox;
309

            
310
5
    if (surface->has_creation_date)
311
	now = surface->creation_date;
312
    else
313
5
	now = time (NULL);
314

            
315
5
    if (surface->ps_level_used == CAIRO_PS_LEVEL_2)
316
4
	level = 2;
317
    else
318
1
	level = 3;
319

            
320
5
    if (surface->eps)
321
	eps_header = " EPSF-3.0";
322

            
323
5
    _cairo_output_stream_printf (surface->final_stream,
324
				 "%%!PS-Adobe-3.0%s\n"
325
				 "%%%%Creator: cairo %s (https://cairographics.org)\n",
326
				 eps_header,
327
				 cairo_version_string ());
328

            
329
5
    if (!getenv ("CAIRO_DEBUG_PS_NO_DATE")) {
330
5
	_cairo_output_stream_printf (surface->final_stream,
331
				     "%%%%CreationDate: %s",
332
				     ctime_r (&now, ctime_buf));
333
    }
334

            
335
5
    _cairo_output_stream_printf (surface->final_stream,
336
				 "%%%%Pages: %d\n"
337
				 "%%%%DocumentData: Clean7Bit\n"
338
				 "%%%%LanguageLevel: %d\n",
339
				 surface->num_pages,
340
				 level);
341

            
342
5
    if (!cairo_list_is_empty (&surface->document_media)) {
343
	cairo_page_media_t *page;
344
5
	cairo_bool_t first = TRUE;
345

            
346
10
	cairo_list_foreach_entry (page, cairo_page_media_t, &surface->document_media, link) {
347
5
	    if (first) {
348
5
		_cairo_output_stream_printf (surface->final_stream,
349
					     "%%%%DocumentMedia: ");
350
5
		first = FALSE;
351
	    } else {
352
		_cairo_output_stream_printf (surface->final_stream,
353
					     "%%%%+ ");
354
	    }
355
5
	    _cairo_output_stream_printf (surface->final_stream,
356
					 "%s %d %d 0 () ()\n",
357
					 page->name,
358
					 page->width,
359
					 page->height);
360
	}
361
    }
362

            
363
5
    has_bbox = FALSE;
364
5
    num_comments = _cairo_array_num_elements (&surface->dsc_header_comments);
365
5
    comments = _cairo_array_index (&surface->dsc_header_comments, 0);
366
5
    for (i = 0; i < num_comments; i++) {
367
	_cairo_output_stream_printf (surface->final_stream,
368
				     "%s\n", comments[i]);
369
	if (strncmp (comments[i], "%%BoundingBox:", 14) == 0)
370
	    has_bbox = TRUE;
371

            
372
	free (comments[i]);
373
	comments[i] = NULL;
374
    }
375

            
376
5
    if (!has_bbox) {
377
5
	_cairo_output_stream_printf (surface->final_stream,
378
				     "%%%%BoundingBox: %d %d %d %d\n",
379
				     surface->document_bbox_p1.x,
380
				     surface->document_bbox_p1.y,
381
				     surface->document_bbox_p2.x,
382
				     surface->document_bbox_p2.y);
383
    }
384

            
385
5
    _cairo_output_stream_printf (surface->final_stream,
386
				 "%%%%EndComments\n");
387

            
388
5
    _cairo_output_stream_printf (surface->final_stream,
389
				 "%%%%BeginProlog\n");
390

            
391
5
    if (surface->eps) {
392
	_cairo_output_stream_printf (surface->final_stream,
393
				     "50 dict begin\n");
394
    } else {
395
5
	_cairo_output_stream_printf (surface->final_stream,
396
				     "/languagelevel where\n"
397
				     "{ pop languagelevel } { 1 } ifelse\n"
398
				     "%d lt { /Helvetica findfont 12 scalefont setfont 50 500 moveto\n"
399
				     "  (This print job requires a PostScript Language Level %d printer.) show\n"
400
				     "  showpage quit } if\n",
401
				     level,
402
				     level);
403
    }
404

            
405
5
    _cairo_output_stream_printf (surface->final_stream,
406
				 "/q { gsave } bind def\n"
407
				 "/Q { grestore } bind def\n"
408
				 "/cm { 6 array astore concat } bind def\n"
409
				 "/w { setlinewidth } bind def\n"
410
				 "/J { setlinecap } bind def\n"
411
				 "/j { setlinejoin } bind def\n"
412
				 "/M { setmiterlimit } bind def\n"
413
				 "/d { setdash } bind def\n"
414
				 "/m { moveto } bind def\n"
415
				 "/l { lineto } bind def\n"
416
				 "/c { curveto } bind def\n"
417
				 "/h { closepath } bind def\n"
418
				 "/re { exch dup neg 3 1 roll 5 3 roll moveto 0 rlineto\n"
419
				 "      0 exch rlineto 0 rlineto closepath } bind def\n"
420
				 "/S { stroke } bind def\n"
421
				 "/f { fill } bind def\n"
422
				 "/f* { eofill } bind def\n"
423
				 "/n { newpath } bind def\n"
424
				 "/W { clip } bind def\n"
425
				 "/W* { eoclip } bind def\n"
426
				 "/BT { } bind def\n"
427
				 "/ET { } bind def\n"
428
				 "/BDC { mark 3 1 roll /BDC pdfmark } bind def\n"
429
				 "/EMC { mark /EMC pdfmark } bind def\n"
430
				 "/cairo_store_point { /cairo_point_y exch def /cairo_point_x exch def } def\n"
431
				 "/Tj { show currentpoint cairo_store_point } bind def\n"
432
				 "/TJ {\n"
433
				 "  {\n"
434
				 "    dup\n"
435
				 "    type /stringtype eq\n"
436
				 "    { show } { -0.001 mul 0 cairo_font_matrix dtransform rmoveto } ifelse\n"
437
				 "  } forall\n"
438
				 "  currentpoint cairo_store_point\n"
439
				 "} bind def\n"
440
				 "/cairo_selectfont { cairo_font_matrix aload pop pop pop 0 0 6 array astore\n"
441
				 "    cairo_font exch selectfont cairo_point_x cairo_point_y moveto } bind def\n"
442
				 "/Tf { pop /cairo_font exch def /cairo_font_matrix where\n"
443
				 "      { pop cairo_selectfont } if } bind def\n"
444
				 "/Td { matrix translate cairo_font_matrix matrix concatmatrix dup\n"
445
				 "      /cairo_font_matrix exch def dup 4 get exch 5 get cairo_store_point\n"
446
				 "      /cairo_font where { pop cairo_selectfont } if } bind def\n"
447
				 "/Tm { 2 copy 8 2 roll 6 array astore /cairo_font_matrix exch def\n"
448
				 "      cairo_store_point /cairo_font where { pop cairo_selectfont } if } bind def\n"
449
				 "/g { setgray } bind def\n"
450
				 "/rg { setrgbcolor } bind def\n"
451
				 "/d1 { setcachedevice } bind def\n"
452
				 "/cairo_data_source {\n"
453
				 "  CairoDataIndex CairoData length lt\n"
454
				 "    { CairoData CairoDataIndex get /CairoDataIndex CairoDataIndex 1 add def }\n"
455
				 "    { () } ifelse\n"
456
				 "} def\n"
457
				 "/cairo_flush_ascii85_file { cairo_ascii85_file status { cairo_ascii85_file flushfile } if } def\n"
458
				 "/cairo_image { image cairo_flush_ascii85_file } def\n"
459
				 "/cairo_imagemask { imagemask cairo_flush_ascii85_file } def\n");
460

            
461
5
    if (!surface->eps) {
462
5
	_cairo_output_stream_printf (surface->final_stream,
463
				     "/cairo_set_page_size {\n"
464
				     "  %% Change paper size, but only if different from previous paper size otherwise\n"
465
				     "  %% duplex fails. PLRM specifies a tolerance of 5 pts when matching paper size\n"
466
				     "  %% so we use the same when checking if the size changes.\n"
467
				     "  /setpagedevice where {\n"
468
				     "    pop currentpagedevice\n"
469
				     "    /PageSize known {\n"
470
				     "      2 copy\n"
471
				     "      currentpagedevice /PageSize get aload pop\n"
472
				     "      exch 4 1 roll\n"
473
				     "      sub abs 5 gt\n"
474
				     "      3 1 roll\n"
475
				     "      sub abs 5 gt\n"
476
				     "      or\n"
477
				     "    } {\n"
478
				     "      true\n"
479
				     "    } ifelse\n"
480
				     "    {\n"
481
				     "      2 array astore\n"
482
				     "      2 dict begin\n"
483
				     "        /PageSize exch def\n"
484
				     "        /ImagingBBox null def\n"
485
				     "      currentdict end\n"
486
				     "      setpagedevice\n"
487
				     "    } {\n"
488
				     "      pop pop\n"
489
				     "    } ifelse\n"
490
				     "  } {\n"
491
				     "    pop\n"
492
				     "  } ifelse\n"
493
				     "} def\n");
494
    }
495
5
    if (surface->contains_eps) {
496
	_cairo_output_stream_printf (surface->final_stream,
497
				     "/cairo_eps_begin {\n"
498
				     "  /cairo_save_state save def\n"
499
				     "  /dict_count countdictstack def\n"
500
				     "  /op_count count 1 sub def\n"
501
				     "  userdict begin\n"
502
				     "  /showpage { } def\n"
503
				     "  0 g 0 J 1 w 0 j 10 M [ ] 0 d n\n"
504
				     "} bind def\n"
505
				     "/cairo_eps_end {\n"
506
				     "  count op_count sub { pop } repeat\n"
507
				     "  countdictstack dict_count sub { end } repeat\n"
508
				     "  cairo_save_state restore\n"
509
				     "} bind def\n");
510
    }
511

            
512
5
    _cairo_output_stream_printf (surface->final_stream,
513
				 "%%%%EndProlog\n");
514
5
}
515

            
516
static cairo_status_t
517
_cairo_ps_surface_emit_type1_font_subset (cairo_ps_surface_t		*surface,
518
					  cairo_scaled_font_subset_t	*font_subset)
519

            
520

            
521
{
522
    cairo_type1_subset_t subset;
523
    cairo_status_t status;
524
    int length;
525
    char name[64];
526

            
527
    snprintf (name, sizeof name, "f-%d-%d",
528
	      font_subset->font_id, font_subset->subset_id);
529
    status = _cairo_type1_subset_init (&subset, name, font_subset, TRUE);
530
    if (unlikely (status))
531
	return status;
532

            
533
    /* FIXME: Figure out document structure convention for fonts */
534

            
535
#if DEBUG_PS
536
    _cairo_output_stream_printf (surface->final_stream,
537
				 "%% _cairo_ps_surface_emit_type1_font_subset\n");
538
#endif
539

            
540
    _cairo_output_stream_printf (surface->final_stream,
541
				 "%%%%BeginResource: font %s\n",
542
				 subset.base_font);
543
    length = subset.header_length + subset.data_length + subset.trailer_length;
544
    _cairo_output_stream_write (surface->final_stream, subset.data, length);
545
    _cairo_output_stream_printf (surface->final_stream,
546
				 "%%%%EndResource\n");
547

            
548
    _cairo_type1_subset_fini (&subset);
549

            
550
    return CAIRO_STATUS_SUCCESS;
551
}
552

            
553

            
554
static cairo_status_t
555
_cairo_ps_surface_emit_type1_font_fallback (cairo_ps_surface_t		*surface,
556
                                            cairo_scaled_font_subset_t	*font_subset)
557
{
558
    cairo_type1_subset_t subset;
559
    cairo_status_t status;
560
    int length;
561
    char name[64];
562

            
563
    snprintf (name, sizeof name, "f-%d-%d",
564
	      font_subset->font_id, font_subset->subset_id);
565
    status = _cairo_type1_fallback_init_hex (&subset, name, font_subset);
566
    if (unlikely (status))
567
	return status;
568

            
569
#if DEBUG_PS
570
    _cairo_output_stream_printf (surface->final_stream,
571
				 "%% _cairo_ps_surface_emit_type1_font_fallback\n");
572
#endif
573

            
574
    _cairo_output_stream_printf (surface->final_stream,
575
				 "%%%%BeginResource: font %s\n",
576
				 subset.base_font);
577
    length = subset.header_length + subset.data_length + subset.trailer_length;
578
    _cairo_output_stream_write (surface->final_stream, subset.data, length);
579
    _cairo_output_stream_printf (surface->final_stream,
580
				 "%%%%EndResource\n");
581

            
582
    _cairo_type1_fallback_fini (&subset);
583

            
584
    return CAIRO_STATUS_SUCCESS;
585
}
586

            
587
static cairo_status_t
588
_cairo_ps_surface_emit_truetype_font_subset (cairo_ps_surface_t		*surface,
589
					     cairo_scaled_font_subset_t	*font_subset)
590

            
591

            
592
{
593
    cairo_truetype_subset_t subset;
594
    cairo_status_t status;
595
    unsigned int i, begin, end;
596

            
597
    status = _cairo_truetype_subset_init_ps (&subset, font_subset);
598
    if (unlikely (status))
599
	return status;
600

            
601
    /* FIXME: Figure out document structure convention for fonts */
602

            
603
#if DEBUG_PS
604
    _cairo_output_stream_printf (surface->final_stream,
605
				 "%% _cairo_ps_surface_emit_truetype_font_subset\n");
606
#endif
607

            
608
    _cairo_output_stream_printf (surface->final_stream,
609
				 "%%%%BeginResource: font %s\n",
610
				 subset.ps_name);
611
    _cairo_output_stream_printf (surface->final_stream,
612
				 "11 dict begin\n"
613
				 "/FontType 42 def\n"
614
				 "/FontName /%s def\n"
615
				 "/PaintType 0 def\n"
616
				 "/FontMatrix [ 1 0 0 1 0 0 ] def\n"
617
				 "/FontBBox [ 0 0 0 0 ] def\n"
618
				 "/Encoding 256 array def\n"
619
				 "0 1 255 { Encoding exch /.notdef put } for\n",
620
				 subset.ps_name);
621

            
622
    /* FIXME: Figure out how subset->x_max etc maps to the /FontBBox */
623

            
624
    if (font_subset->is_latin) {
625
	for (i = 1; i < 256; i++) {
626
	    if (font_subset->latin_to_subset_glyph_index[i] > 0) {
627
		if (font_subset->glyph_names != NULL) {
628
		    _cairo_output_stream_printf (surface->final_stream,
629
						 "Encoding %d /%s put\n",
630
						 i, font_subset->glyph_names[font_subset->latin_to_subset_glyph_index[i]]);
631
		} else {
632
		    _cairo_output_stream_printf (surface->final_stream,
633
						 "Encoding %d /g%ld put\n", i, font_subset->latin_to_subset_glyph_index[i]);
634
		}
635
	    }
636
	}
637
    } else {
638
	for (i = 1; i < font_subset->num_glyphs; i++) {
639
	    if (font_subset->glyph_names != NULL) {
640
		_cairo_output_stream_printf (surface->final_stream,
641
					     "Encoding %d /%s put\n",
642
					     i, font_subset->glyph_names[i]);
643
	    } else {
644
		_cairo_output_stream_printf (surface->final_stream,
645
					     "Encoding %d /g%d put\n", i, i);
646
	    }
647
	}
648
    }
649

            
650
    _cairo_output_stream_printf (surface->final_stream,
651
				 "/CharStrings %d dict dup begin\n"
652
				 "/.notdef 0 def\n",
653
				 font_subset->num_glyphs);
654

            
655
    for (i = 1; i < font_subset->num_glyphs; i++) {
656
	if (font_subset->glyph_names != NULL) {
657
	    _cairo_output_stream_printf (surface->final_stream,
658
					 "/%s %d def\n",
659
					 font_subset->glyph_names[i], i);
660
	} else {
661
	    _cairo_output_stream_printf (surface->final_stream,
662
					 "/g%d %d def\n", i, i);
663
	}
664
    }
665

            
666
    _cairo_output_stream_printf (surface->final_stream,
667
				 "end readonly def\n");
668

            
669
    _cairo_output_stream_printf (surface->final_stream,
670
				 "/sfnts [\n");
671
    begin = 0;
672
    end = 0;
673
    for (i = 0; i < subset.num_string_offsets; i++) {
674
        end = subset.string_offsets[i];
675
        _cairo_output_stream_printf (surface->final_stream,"<");
676
        _cairo_output_stream_write_hex_string (surface->final_stream,
677
                                               subset.data + begin, end - begin);
678
        _cairo_output_stream_printf (surface->final_stream,"00>\n");
679
        begin = end;
680
    }
681
    if (subset.data_length > end) {
682
        _cairo_output_stream_printf (surface->final_stream,"<");
683
        _cairo_output_stream_write_hex_string (surface->final_stream,
684
                                               subset.data + end, subset.data_length - end);
685
        _cairo_output_stream_printf (surface->final_stream,"00>\n");
686
    }
687

            
688
    _cairo_output_stream_printf (surface->final_stream,
689
				 "] def\n"
690
				 "/f-%d-%d currentdict end definefont pop\n",
691
				 font_subset->font_id,
692
				 font_subset->subset_id);
693
    _cairo_output_stream_printf (surface->final_stream,
694
				 "%%%%EndResource\n");
695
    _cairo_truetype_subset_fini (&subset);
696

            
697

            
698
    return CAIRO_STATUS_SUCCESS;
699
}
700

            
701
static cairo_int_status_t
702
_cairo_ps_emit_imagemask (cairo_image_surface_t *image,
703
			  cairo_output_stream_t *stream)
704
{
705
    uint8_t *row, *byte;
706
    int rows, cols;
707

            
708
    /* The only image type supported by Type 3 fonts are 1-bit image
709
     * masks */
710
    assert (image->format == CAIRO_FORMAT_A1);
711

            
712
    _cairo_output_stream_printf (stream,
713
				 "<<\n"
714
				 "   /ImageType 1\n"
715
				 "   /Width %d\n"
716
				 "   /Height %d\n"
717
				 "   /ImageMatrix [%d 0 0 %d 0 %d]\n"
718
				 "   /Decode [1 0]\n"
719
				 "   /BitsPerComponent 1\n",
720
				 image->width,
721
				 image->height,
722
				 image->width,
723
				 -image->height,
724
				 image->height);
725

            
726
    _cairo_output_stream_printf (stream,
727
				 "   /DataSource {<\n   ");
728
    for (row = image->data, rows = image->height; rows; row += image->stride, rows--) {
729
	for (byte = row, cols = (image->width + 7) / 8; cols; byte++, cols--) {
730
	    uint8_t output_byte = CAIRO_BITSWAP8_IF_LITTLE_ENDIAN (*byte);
731
	    _cairo_output_stream_printf (stream, "%02x ", output_byte);
732
	}
733
	_cairo_output_stream_printf (stream, "\n   ");
734
    }
735
    _cairo_output_stream_printf (stream, ">}\n>>\n");
736

            
737
    _cairo_output_stream_printf (stream,
738
				 "imagemask\n");
739

            
740
    return _cairo_output_stream_get_status (stream);
741
}
742

            
743
static cairo_status_t
744
_cairo_ps_surface_emit_type3_font_subset (cairo_ps_surface_t		*surface,
745
					  cairo_scaled_font_subset_t	*font_subset)
746

            
747

            
748
{
749
    cairo_status_t status;
750
    unsigned int i;
751
    cairo_box_t font_bbox = {{0,0},{0,0}};
752
    cairo_box_t bbox = {{0,0},{0,0}};
753
    cairo_surface_t *type3_surface;
754
    double width;
755

            
756
    if (font_subset->num_glyphs == 0)
757
	return CAIRO_STATUS_SUCCESS;
758

            
759
#if DEBUG_PS
760
    _cairo_output_stream_printf (surface->final_stream,
761
				 "%% _cairo_ps_surface_emit_type3_font_subset\n");
762
#endif
763

            
764
    _cairo_output_stream_printf (surface->final_stream,
765
				 "%%%%BeginResource: font\n");
766
    _cairo_output_stream_printf (surface->final_stream,
767
				 "8 dict begin\n"
768
				 "/FontType 3 def\n"
769
				 "/FontMatrix [1 0 0 -1 0 0] def\n"
770
				 "/Encoding 256 array def\n"
771
				 "0 1 255 { Encoding exch /.notdef put } for\n");
772

            
773
    type3_surface = _cairo_type3_glyph_surface_create (font_subset->scaled_font,
774
						       NULL,
775
						       _cairo_ps_emit_imagemask,
776
						       surface->font_subsets,
777
						       TRUE);
778
    status = type3_surface->status;
779
    if (unlikely (status))
780
	return status;
781

            
782
    for (i = 0; i < font_subset->num_glyphs; i++) {
783
	if (font_subset->glyph_names != NULL) {
784
	    _cairo_output_stream_printf (surface->final_stream,
785
					 "Encoding %d /%s put\n",
786
					 i, font_subset->glyph_names[i]);
787
	} else {
788
	    _cairo_output_stream_printf (surface->final_stream,
789
					 "Encoding %d /g%d put\n", i, i);
790
	}
791
    }
792

            
793
    _cairo_output_stream_printf (surface->final_stream,
794
				 "/Glyphs [\n");
795

            
796
    for (i = 0; i < font_subset->num_glyphs; i++) {
797
	_cairo_output_stream_printf (surface->final_stream,
798
				     "    { %% %d\n", i);
799
	status = _cairo_type3_glyph_surface_emit_glyph (type3_surface,
800
							surface->final_stream,
801
							font_subset->glyphs[i],
802
							&bbox,
803
							&width);
804
	if (unlikely (status))
805
	    break;
806

            
807
	_cairo_output_stream_printf (surface->final_stream,
808
				     "    }\n");
809
        if (i == 0) {
810
            font_bbox.p1.x = bbox.p1.x;
811
            font_bbox.p1.y = bbox.p1.y;
812
            font_bbox.p2.x = bbox.p2.x;
813
            font_bbox.p2.y = bbox.p2.y;
814
        } else {
815
            if (bbox.p1.x < font_bbox.p1.x)
816
                font_bbox.p1.x = bbox.p1.x;
817
            if (bbox.p1.y < font_bbox.p1.y)
818
                font_bbox.p1.y = bbox.p1.y;
819
            if (bbox.p2.x > font_bbox.p2.x)
820
                font_bbox.p2.x = bbox.p2.x;
821
            if (bbox.p2.y > font_bbox.p2.y)
822
                font_bbox.p2.y = bbox.p2.y;
823
        }
824
    }
825
    cairo_surface_finish (type3_surface);
826
    cairo_surface_destroy (type3_surface);
827
    if (unlikely (status))
828
	return status;
829

            
830
    _cairo_output_stream_printf (surface->final_stream,
831
				 "] def\n"
832
				 "/FontBBox [%f %f %f %f] def\n"
833
				 "/BuildChar {\n"
834
				 "  exch /Glyphs get\n"
835
				 "  exch get\n"
836
				 "  10 dict begin exec end\n"
837
				 "} bind def\n"
838
				 "currentdict\n"
839
				 "end\n"
840
				 "/f-%d-%d exch definefont pop\n",
841
				 _cairo_fixed_to_double (font_bbox.p1.x),
842
				 - _cairo_fixed_to_double (font_bbox.p2.y),
843
				 _cairo_fixed_to_double (font_bbox.p2.x),
844
				 - _cairo_fixed_to_double (font_bbox.p1.y),
845
				 font_subset->font_id,
846
				 font_subset->subset_id);
847
    _cairo_output_stream_printf (surface->final_stream,
848
				 "%%%%EndResource\n");
849

            
850
    return CAIRO_STATUS_SUCCESS;
851
}
852

            
853
static cairo_int_status_t
854
_cairo_ps_surface_emit_unscaled_font_subset (cairo_scaled_font_subset_t	*font_subset,
855
				            void			*closure)
856
{
857
    cairo_ps_surface_t *surface = closure;
858
    cairo_int_status_t status;
859

            
860
    status = _cairo_scaled_font_subset_create_glyph_names (font_subset);
861
    if (_cairo_int_status_is_error (status))
862
	return status;
863

            
864
    status = _cairo_ps_surface_emit_type1_font_subset (surface, font_subset);
865
    if (status != CAIRO_INT_STATUS_UNSUPPORTED)
866
	return status;
867

            
868
    status = _cairo_ps_surface_emit_truetype_font_subset (surface, font_subset);
869
    if (status != CAIRO_INT_STATUS_UNSUPPORTED)
870
	return status;
871

            
872
    status = _cairo_ps_surface_emit_type1_font_fallback (surface, font_subset);
873
    if (status != CAIRO_INT_STATUS_UNSUPPORTED)
874
	return status;
875

            
876
    ASSERT_NOT_REACHED;
877
    return CAIRO_STATUS_SUCCESS;
878
}
879

            
880
static cairo_int_status_t
881
_cairo_ps_surface_emit_scaled_font_subset (cairo_scaled_font_subset_t *font_subset,
882
                                           void			      *closure)
883
{
884
    cairo_ps_surface_t *surface = closure;
885
    cairo_int_status_t status;
886

            
887
    status = _cairo_scaled_font_subset_create_glyph_names (font_subset);
888
    if (_cairo_int_status_is_error (status))
889
	return status;
890

            
891
    status = _cairo_ps_surface_emit_type3_font_subset (surface, font_subset);
892
    if (status != CAIRO_INT_STATUS_UNSUPPORTED)
893
	return status;
894

            
895
    ASSERT_NOT_REACHED;
896
    return CAIRO_INT_STATUS_SUCCESS;
897
}
898

            
899
static cairo_status_t
900
5
_cairo_ps_surface_emit_font_subsets (cairo_ps_surface_t *surface)
901
{
902
    cairo_status_t status;
903

            
904
#if DEBUG_PS
905
    _cairo_output_stream_printf (surface->final_stream,
906
				 "%% _cairo_ps_surface_emit_font_subsets\n");
907
#endif
908

            
909
5
    status = _cairo_scaled_font_subsets_foreach_unscaled (surface->font_subsets,
910
                                                          _cairo_ps_surface_emit_unscaled_font_subset,
911
                                                          surface);
912
5
    if (unlikely (status))
913
	return status;
914

            
915
5
    return _cairo_scaled_font_subsets_foreach_scaled (surface->font_subsets,
916
						      _cairo_ps_surface_emit_scaled_font_subset,
917
						      surface);
918
}
919

            
920
static cairo_int_status_t
921
5
_cairo_ps_surface_emit_forms (cairo_ps_surface_t *surface)
922
{
923
5
    _cairo_hash_table_foreach (surface->forms,
924
			       _cairo_ps_form_emit,
925
			       surface);
926
5
    return surface->base.status;
927
}
928

            
929
static cairo_status_t
930
5
_cairo_ps_surface_emit_body (cairo_ps_surface_t *surface)
931
{
932
    char    buf[4096];
933
    int	    n;
934

            
935
5
    if (ferror (surface->tmpfile) != 0)
936
	return _cairo_error (CAIRO_STATUS_TEMP_FILE_ERROR);
937

            
938
5
    rewind (surface->tmpfile);
939
15
    while ((n = fread (buf, 1, sizeof (buf), surface->tmpfile)) > 0)
940
10
	_cairo_output_stream_write (surface->final_stream, buf, n);
941

            
942
5
    if (ferror (surface->tmpfile) != 0)
943
	return _cairo_error (CAIRO_STATUS_TEMP_FILE_ERROR);
944

            
945
5
    return CAIRO_STATUS_SUCCESS;
946
}
947

            
948
static void
949
5
_cairo_ps_surface_emit_footer (cairo_ps_surface_t *surface)
950
{
951
5
    _cairo_output_stream_printf (surface->final_stream,
952
				 "%%%%Trailer\n");
953

            
954
5
    if (surface->eps) {
955
	_cairo_output_stream_printf (surface->final_stream,
956
				     "end\n");
957
    }
958

            
959
5
    _cairo_output_stream_printf (surface->final_stream,
960
				 "%%%%EOF\n");
961
5
}
962

            
963
static cairo_bool_t
964
34
_path_covers_bbox (cairo_ps_surface_t *surface,
965
		   cairo_path_fixed_t *path)
966
{
967
    cairo_box_t box;
968

            
969
34
    if (_cairo_path_fixed_is_box (path, &box)) {
970
	cairo_rectangle_int_t rect;
971

            
972
22
	_cairo_box_round_to_rectangle (&box, &rect);
973

            
974
	/* skip trivial whole-page clips */
975
22
	if (_cairo_rectangle_intersect (&rect, &surface->surface_extents)) {
976
22
	    if (rect.x == surface->surface_extents.x &&
977
		rect.width == surface->surface_extents.width &&
978
		rect.y == surface->surface_extents.y &&
979
		rect.height == surface->surface_extents.height)
980
	    {
981
		return TRUE;
982
	    }
983
	}
984
    }
985

            
986
34
    return FALSE;
987
}
988

            
989
static cairo_status_t
990
68
_cairo_ps_surface_clipper_intersect_clip_path (cairo_surface_clipper_t *clipper,
991
					       cairo_path_fixed_t *path,
992
					       cairo_fill_rule_t   fill_rule,
993
					       double		    tolerance,
994
					       cairo_antialias_t   antialias)
995
{
996
68
    cairo_ps_surface_t *surface = cairo_container_of (clipper,
997
						      cairo_ps_surface_t,
998
						      clipper);
999
68
    cairo_output_stream_t *stream = surface->stream;
    cairo_status_t status;
68
    assert (surface->paginated_mode != CAIRO_PAGINATED_MODE_ANALYZE);
#if DEBUG_PS
    _cairo_output_stream_printf (stream,
				 "%% _cairo_ps_surface_intersect_clip_path\n");
#endif
68
    if (path == NULL) {
34
	status = _cairo_pdf_operators_flush (&surface->pdf_operators);
34
	if (unlikely (status))
	    return status;
34
	_cairo_output_stream_printf (stream, "Q q\n");
34
	surface->current_pattern_is_solid_color = FALSE;
34
	_cairo_pdf_operators_reset (&surface->pdf_operators);
34
	return CAIRO_STATUS_SUCCESS;
    }
34
    if (_path_covers_bbox (surface, path))
	return CAIRO_STATUS_SUCCESS;
34
    return _cairo_pdf_operators_clip (&surface->pdf_operators,
				      path,
				      fill_rule);
}
/* PLRM specifies a tolerance of 5 points when matching page sizes */
static cairo_bool_t
85
_ps_page_dimension_equal (int a, int b)
{
85
    return (abs (a - b) < 5);
}
static const char *
5
_cairo_ps_surface_get_page_media (cairo_ps_surface_t     *surface)
{
    int width, height, i;
    char buf[50];
    cairo_page_media_t *page;
    const char *page_name;
5
    width = _cairo_lround (surface->width);
5
    height = _cairo_lround (surface->height);
    /* search previously used page sizes */
5
    cairo_list_foreach_entry (page, cairo_page_media_t, &surface->document_media, link) {
	if (_ps_page_dimension_equal (width, page->width) &&
	    _ps_page_dimension_equal (height, page->height))
	    return page->name;
    }
    /* search list of standard page sizes */
5
    page_name = NULL;
90
    for (i = 0; i < ARRAY_LENGTH (_cairo_page_standard_media); i++) {
85
	if (_ps_page_dimension_equal (width, _cairo_page_standard_media[i].width) &&
	    _ps_page_dimension_equal (height, _cairo_page_standard_media[i].height))
	{
	    page_name = _cairo_page_standard_media[i].name;
	    width = _cairo_page_standard_media[i].width;
	    height = _cairo_page_standard_media[i].height;
	    break;
	}
    }
5
    page = _cairo_calloc (sizeof (cairo_page_media_t));
5
    if (unlikely (page == NULL)) {
	_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
	return NULL;
    }
5
    if (page_name) {
	page->name = strdup (page_name);
    } else {
5
	snprintf (buf, sizeof (buf), "%dx%dmm",
5
		  (int) _cairo_lround (surface->width * 25.4/72),
5
		  (int) _cairo_lround (surface->height * 25.4/72));
5
	page->name = strdup (buf);
    }
5
    if (unlikely (page->name == NULL)) {
	free (page);
	_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
	return NULL;
    }
5
    page->width = width;
5
    page->height = height;
5
    cairo_list_add_tail (&page->link, &surface->document_media);
5
    return page->name;
}
static cairo_surface_t *
5
_cairo_ps_surface_create_for_stream_internal (cairo_output_stream_t *stream,
					      double		     width,
					      double		     height)
{
    cairo_status_t status, status_ignored;
    cairo_ps_surface_t *surface;
5
    surface = _cairo_calloc (sizeof (cairo_ps_surface_t));
5
    if (unlikely (surface == NULL)) {
	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	goto CLEANUP;
    }
5
    _cairo_surface_init (&surface->base,
			 &cairo_ps_surface_backend,
			 NULL, /* device */
			 CAIRO_CONTENT_COLOR_ALPHA,
			 TRUE); /* is_vector */
5
    surface->final_stream = stream;
5
    surface->tmpfile = _cairo_tmpfile ();
5
    if (surface->tmpfile == NULL) {
	switch (errno) {
	case ENOMEM:
	    status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	    break;
	default:
	    status = _cairo_error (CAIRO_STATUS_TEMP_FILE_ERROR);
	    break;
	}
	goto CLEANUP_SURFACE;
    }
5
    surface->stream = _cairo_output_stream_create_for_file (surface->tmpfile);
5
    status = _cairo_output_stream_get_status (surface->stream);
5
    if (unlikely (status))
	goto CLEANUP_OUTPUT_STREAM;
5
    surface->font_subsets = _cairo_scaled_font_subsets_create_simple ();
5
    if (unlikely (surface->font_subsets == NULL)) {
	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	goto CLEANUP_OUTPUT_STREAM;
    }
5
    _cairo_scaled_font_subsets_enable_latin_subset (surface->font_subsets, TRUE);
5
    surface->has_creation_date = FALSE;
5
    surface->eps = FALSE;
5
    surface->ps_level = CAIRO_PS_LEVEL_3;
5
    surface->ps_level_used = CAIRO_PS_LEVEL_2;
5
    surface->width  = width;
5
    surface->height = height;
5
    cairo_matrix_init (&surface->cairo_to_ps, 1, 0, 0, 1, 0, 0);
5
    surface->surface_extents.x = 0;
5
    surface->surface_extents.y = 0;
5
    surface->surface_extents.width  = ceil (surface->width);
5
    surface->surface_extents.height = ceil (surface->height);
5
    surface->surface_bounded = TRUE;
5
    surface->paginated_mode = CAIRO_PAGINATED_MODE_ANALYZE;
5
    surface->force_fallbacks = FALSE;
5
    surface->content = CAIRO_CONTENT_COLOR_ALPHA;
5
    surface->current_pattern_is_solid_color = FALSE;
5
    surface->document_bbox_p1.x = 0;
5
    surface->document_bbox_p1.y = 0;
5
    surface->document_bbox_p2.x = 0;
5
    surface->document_bbox_p2.y = 0;
5
    surface->total_form_size = 0;
5
    surface->contains_eps = FALSE;
5
    surface->paint_proc = FALSE;
5
    _cairo_surface_clipper_init (&surface->clipper,
				 _cairo_ps_surface_clipper_intersect_clip_path);
5
    _cairo_pdf_operators_init (&surface->pdf_operators,
			       surface->stream,
			       &surface->cairo_to_ps,
			       surface->font_subsets,
			       TRUE);
5
    surface->num_pages = 0;
5
    cairo_list_init (&surface->document_media);
5
    _cairo_array_init (&surface->dsc_header_comments, sizeof (char *));
5
    _cairo_array_init (&surface->dsc_setup_comments, sizeof (char *));
5
    _cairo_array_init (&surface->dsc_page_setup_comments, sizeof (char *));
5
    _cairo_array_init (&surface->recording_surf_stack, sizeof (unsigned int));
5
    surface->num_forms = 0;
5
    surface->forms = _cairo_hash_table_create (_cairo_ps_form_equal);
5
    if (unlikely (surface->forms == NULL)) {
	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	goto CLEANUP_FONT_SUBSETS;
    }
5
    surface->dsc_comment_target = &surface->dsc_header_comments;
5
    surface->paginated_surface = _cairo_paginated_surface_create (
	                                   &surface->base,
					   CAIRO_CONTENT_COLOR_ALPHA,
					   &cairo_ps_surface_paginated_backend);
5
    status = surface->paginated_surface->status;
5
    if (status == CAIRO_STATUS_SUCCESS) {
	/* paginated keeps the only reference to surface now, drop ours */
5
	cairo_surface_destroy (&surface->base);
5
	return surface->paginated_surface;
    }
 CLEANUP_FONT_SUBSETS:
    _cairo_scaled_font_subsets_destroy (surface->font_subsets);
 CLEANUP_OUTPUT_STREAM:
    status_ignored = _cairo_output_stream_destroy (surface->stream);
    fclose (surface->tmpfile);
 CLEANUP_SURFACE:
    free (surface);
 CLEANUP:
    /* destroy stream on behalf of caller */
    status_ignored = _cairo_output_stream_destroy (stream);
    return _cairo_surface_create_in_error (status);
}
/**
 * cairo_ps_surface_create:
 * @filename: a filename for the PS output (must be writable), %NULL may be
 *            used to specify no output. This will generate a PS surface that
 *            may be queried and used as a source, without generating a
 *            temporary file.
 * @width_in_points: width of the surface, in points (1 point == 1/72.0 inch)
 * @height_in_points: height of the surface, in points (1 point == 1/72.0 inch)
 *
 * Creates a PostScript surface of the specified size in points to be
 * written to @filename. See cairo_ps_surface_create_for_stream() for
 * a more flexible mechanism for handling the PostScript output than
 * simply writing it to a named file.
 *
 * Note that the size of individual pages of the PostScript output can
 * vary. See cairo_ps_surface_set_size().
 *
 * Return value: a pointer to the newly created surface. The caller
 * owns the surface and should call cairo_surface_destroy() when done
 * with it.
 *
 * This function always returns a valid pointer, but it will return a
 * pointer to a "nil" surface if an error such as out of memory
 * occurs. You can use cairo_surface_status() to check for this.
 *
 * Since: 1.2
 **/
cairo_surface_t *
4
cairo_ps_surface_create (const char		*filename,
			 double			 width_in_points,
			 double			 height_in_points)
{
    cairo_output_stream_t *stream;
4
    stream = _cairo_output_stream_create_for_filename (filename);
4
    if (_cairo_output_stream_get_status (stream))
	return _cairo_surface_create_in_error (_cairo_output_stream_destroy (stream));
4
    return _cairo_ps_surface_create_for_stream_internal (stream,
							 width_in_points,
							 height_in_points);
}
/**
 * cairo_ps_surface_create_for_stream:
 * @write_func: a #cairo_write_func_t to accept the output data, may be %NULL
 *              to indicate a no-op @write_func. With a no-op @write_func,
 *              the surface may be queried or used as a source without
 *              generating any temporary files.
 * @closure: the closure argument for @write_func
 * @width_in_points: width of the surface, in points (1 point == 1/72.0 inch)
 * @height_in_points: height of the surface, in points (1 point == 1/72.0 inch)
 *
 * Creates a PostScript surface of the specified size in points to be
 * written incrementally to the stream represented by @write_func and
 * @closure. See cairo_ps_surface_create() for a more convenient way
 * to simply direct the PostScript output to a named file.
 *
 * Note that the size of individual pages of the PostScript
 * output can vary. See cairo_ps_surface_set_size().
 *
 * Return value: a pointer to the newly created surface. The caller
 * owns the surface and should call cairo_surface_destroy() when done
 * with it.
 *
 * This function always returns a valid pointer, but it will return a
 * pointer to a "nil" surface if an error such as out of memory
 * occurs. You can use cairo_surface_status() to check for this.
 *
 * Since: 1.2
 **/
cairo_surface_t *
1
cairo_ps_surface_create_for_stream (cairo_write_func_t	write_func,
				    void	       *closure,
				    double		width_in_points,
				    double		height_in_points)
{
    cairo_output_stream_t *stream;
1
    stream = _cairo_output_stream_create (write_func, NULL, closure);
1
    if (_cairo_output_stream_get_status (stream))
	return _cairo_surface_create_in_error (_cairo_output_stream_destroy (stream));
1
    return _cairo_ps_surface_create_for_stream_internal (stream,
							 width_in_points,
							 height_in_points);
}
static cairo_bool_t
_cairo_surface_is_ps (cairo_surface_t *surface)
{
    return surface->backend == &cairo_ps_surface_backend;
}
/* If the abstract_surface is a paginated surface, and that paginated
 * surface's target is a ps_surface, then set ps_surface to that
 * target. Otherwise return FALSE.
 */
static cairo_bool_t
61
_extract_ps_surface (cairo_surface_t	 *surface,
                     cairo_bool_t         set_error_on_failure,
		     cairo_ps_surface_t **ps_surface)
{
    cairo_surface_t *target;
61
    if (surface->status)
16
	return FALSE;
45
    if (surface->finished) {
21
        if (set_error_on_failure)
18
	    _cairo_surface_set_error (surface,
18
				      _cairo_error (CAIRO_STATUS_SURFACE_FINISHED));
21
	return FALSE;
    }
24
    if (! _cairo_surface_is_paginated (surface)) {
24
        if (set_error_on_failure)
21
	    _cairo_surface_set_error (surface,
21
				      _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH));
24
	return FALSE;
    }
    target = _cairo_paginated_surface_get_target (surface);
    if (target->status) {
        if (set_error_on_failure)
	    _cairo_surface_set_error (surface, target->status);
	return FALSE;
    }
    if (target->finished) {
        if (set_error_on_failure)
	    _cairo_surface_set_error (surface,
				      _cairo_error (CAIRO_STATUS_SURFACE_FINISHED));
	return FALSE;
    }
    if (! _cairo_surface_is_ps (target)) {
        if (set_error_on_failure)
	    _cairo_surface_set_error (surface,
				      _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH));
	return FALSE;
    }
    *ps_surface = (cairo_ps_surface_t *) target;
    return TRUE;
}
/**
 * cairo_ps_surface_restrict_to_level:
 * @surface: a PostScript #cairo_surface_t
 * @level: PostScript level
 *
 * Restricts the generated PostSript file to @level. See
 * cairo_ps_get_levels() for a list of available level values that
 * can be used here.
 *
 * This function should only be called before any drawing operations
 * have been performed on the given surface. The simplest way to do
 * this is to call this function immediately after creating the
 * surface.
 *
 * Since: 1.6
 **/
void
8
cairo_ps_surface_restrict_to_level (cairo_surface_t  *surface,
                                    cairo_ps_level_t  level)
{
8
    cairo_ps_surface_t *ps_surface = NULL;
8
    if (! _extract_ps_surface (surface, TRUE, &ps_surface))
8
	return;
    if (level < CAIRO_PS_LEVEL_LAST)
	ps_surface->ps_level = level;
}
/**
 * cairo_ps_get_levels:
 * @levels: supported level list
 * @num_levels: list length
 *
 * Used to retrieve the list of supported levels. See
 * cairo_ps_surface_restrict_to_level().
 *
 * Since: 1.6
 **/
void
cairo_ps_get_levels (cairo_ps_level_t const	**levels,
                     int                     	 *num_levels)
{
    if (levels != NULL)
	*levels = _cairo_ps_levels;
    if (num_levels != NULL)
	*num_levels = CAIRO_PS_LEVEL_LAST;
}
/**
 * cairo_ps_level_to_string:
 * @level: a level id
 *
 * Get the string representation of the given @level id. This function
 * will return %NULL if @level id isn't valid. See cairo_ps_get_levels()
 * for a way to get the list of valid level ids.
 *
 * Return value: the string associated to given level.
 *
 * Since: 1.6
 **/
const char *
cairo_ps_level_to_string (cairo_ps_level_t level)
{
    if (level >= CAIRO_PS_LEVEL_LAST)
	return NULL;
    return _cairo_ps_level_strings[level];
}
/**
 * cairo_ps_surface_set_eps:
 * @surface: a PostScript #cairo_surface_t
 * @eps: %TRUE to output EPS format PostScript
 *
 * If @eps is %TRUE, the PostScript surface will output Encapsulated
 * PostScript.
 *
 * This function should only be called before any drawing operations
 * have been performed on the current page. The simplest way to do
 * this is to call this function immediately after creating the
 * surface. An Encapsulated PostScript file should never contain more
 * than one page.
 *
 * Since: 1.6
 **/
void
11
cairo_ps_surface_set_eps (cairo_surface_t	*surface,
			  cairo_bool_t           eps)
{
11
    cairo_ps_surface_t *ps_surface = NULL;
11
    if (! _extract_ps_surface (surface, TRUE, &ps_surface))
11
	return;
    ps_surface->eps = eps;
}
/**
 * cairo_ps_surface_get_eps:
 * @surface: a PostScript #cairo_surface_t
 *
 * Check whether the PostScript surface will output Encapsulated PostScript.
 *
 * Return value: %TRUE if the surface will output Encapsulated PostScript.
 *
 * Since: 1.6
 **/
cairo_public cairo_bool_t
10
cairo_ps_surface_get_eps (cairo_surface_t	*surface)
{
10
    cairo_ps_surface_t *ps_surface = NULL;
10
    if (! _extract_ps_surface (surface, FALSE, &ps_surface))
10
	return FALSE;
    return ps_surface->eps;
}
/**
 * cairo_ps_surface_set_size:
 * @surface: a PostScript #cairo_surface_t
 * @width_in_points: new surface width, in points (1 point == 1/72.0 inch)
 * @height_in_points: new surface height, in points (1 point == 1/72.0 inch)
 *
 * Changes the size of a PostScript surface for the current (and
 * subsequent) pages.
 *
 * This function should only be called before any drawing operations
 * have been performed on the current page. The simplest way to do
 * this is to call this function immediately after creating the
 * surface or immediately after completing a page with either
 * cairo_show_page() or cairo_copy_page().
 *
 * Since: 1.2
 **/
void
8
cairo_ps_surface_set_size (cairo_surface_t	*surface,
			   double		 width_in_points,
			   double		 height_in_points)
{
8
    cairo_ps_surface_t *ps_surface = NULL;
    cairo_status_t status;
8
    if (! _extract_ps_surface (surface, TRUE, &ps_surface))
8
	return;
    ps_surface->width = width_in_points;
    ps_surface->height = height_in_points;
    cairo_matrix_init (&ps_surface->cairo_to_ps, 1, 0, 0, 1, 0, 0);
    ps_surface->surface_extents.x = 0;
    ps_surface->surface_extents.y = 0;
    ps_surface->surface_extents.width  = ceil (ps_surface->width);
    ps_surface->surface_extents.height = ceil (ps_surface->height);
    _cairo_pdf_operators_set_cairo_to_pdf_matrix (&ps_surface->pdf_operators,
						  &ps_surface->cairo_to_ps);
    status = _cairo_paginated_surface_set_size (ps_surface->paginated_surface,
						width_in_points,
						height_in_points);
    if (status)
	status = _cairo_surface_set_error (surface, status);
}
/**
 * cairo_ps_surface_dsc_comment:
 * @surface: a PostScript #cairo_surface_t
 * @comment: a comment string to be emitted into the PostScript output
 *
 * Emit a comment into the PostScript output for the given surface.
 *
 * The comment is expected to conform to the PostScript Language
 * Document Structuring Conventions (DSC). Please see that manual for
 * details on the available comments and their meanings. In
 * particular, the \%\%IncludeFeature comment allows a
 * device-independent means of controlling printer device features. So
 * the PostScript Printer Description Files Specification will also be
 * a useful reference.
 *
 * The comment string must begin with a percent character (\%) and the
 * total length of the string (including any initial percent
 * characters) must not exceed 255 characters. Violating either of
 * these conditions will place @surface into an error state. But
 * beyond these two conditions, this function will not enforce
 * conformance of the comment with any particular specification.
 *
 * The comment string must not contain any newline characters.
 *
 * The DSC specifies different sections in which particular comments
 * can appear. This function provides for comments to be emitted
 * within three sections: the header, the Setup section, and the
 * PageSetup section.  Comments appearing in the first two sections
 * apply to the entire document while comments in the BeginPageSetup
 * section apply only to a single page.
 *
 * For comments to appear in the header section, this function should
 * be called after the surface is created, but before a call to
 * cairo_ps_surface_dsc_begin_setup().
 *
 * For comments to appear in the Setup section, this function should
 * be called after a call to cairo_ps_surface_dsc_begin_setup() but
 * before a call to cairo_ps_surface_dsc_begin_page_setup().
 *
 * For comments to appear in the PageSetup section, this function
 * should be called after a call to
 * cairo_ps_surface_dsc_begin_page_setup().
 *
 * Note that it is only necessary to call
 * cairo_ps_surface_dsc_begin_page_setup() for the first page of any
 * surface. After a call to cairo_show_page() or cairo_copy_page()
 * comments are unambiguously directed to the PageSetup section of the
 * current page. But it doesn't hurt to call this function at the
 * beginning of every page as that consistency may make the calling
 * code simpler.
 *
 * As a final note, cairo automatically generates several comments on
 * its own. As such, applications must not manually generate any of
 * the following comments:
 *
 * Header section: \%!PS-Adobe-3.0, \%\%Creator, \%\%CreationDate, \%\%Pages,
 * \%\%BoundingBox, \%\%DocumentData, \%\%LanguageLevel, \%\%EndComments.
 *
 * Setup section: \%\%BeginSetup, \%\%EndSetup
 *
 * PageSetup section: \%\%BeginPageSetup, \%\%PageBoundingBox, \%\%EndPageSetup.
 *
 * Other sections: \%\%BeginProlog, \%\%EndProlog, \%\%Page, \%\%Trailer, \%\%EOF
 *
 * Here is an example sequence showing how this function might be used:
 *
 * <informalexample><programlisting>
 * cairo_surface_t *surface = cairo_ps_surface_create (filename, width, height);
 * ...
 * cairo_ps_surface_dsc_comment (surface, "%%Title: My excellent document");
 * cairo_ps_surface_dsc_comment (surface, "%%Copyright: Copyright (C) 2006 Cairo Lover")
 * ...
 * cairo_ps_surface_dsc_begin_setup (surface);
 * cairo_ps_surface_dsc_comment (surface, "%%IncludeFeature: *MediaColor White");
 * ...
 * cairo_ps_surface_dsc_begin_page_setup (surface);
 * cairo_ps_surface_dsc_comment (surface, "%%IncludeFeature: *PageSize A3");
 * cairo_ps_surface_dsc_comment (surface, "%%IncludeFeature: *InputSlot LargeCapacity");
 * cairo_ps_surface_dsc_comment (surface, "%%IncludeFeature: *MediaType Glossy");
 * cairo_ps_surface_dsc_comment (surface, "%%IncludeFeature: *MediaColor Blue");
 * ... draw to first page here ..
 * cairo_show_page (cr);
 * ...
 * cairo_ps_surface_dsc_comment (surface, "%%IncludeFeature: *PageSize A5");
 * ...
 * </programlisting></informalexample>
 *
 * Since: 1.2
 **/
void
8
cairo_ps_surface_dsc_comment (cairo_surface_t	*surface,
			      const char	*comment)
{
8
    cairo_ps_surface_t *ps_surface = NULL;
    cairo_status_t status;
    char *comment_copy;
8
    if (! _extract_ps_surface (surface, TRUE, &ps_surface))
8
	return;
    /* A couple of sanity checks on the comment value. */
    if (comment == NULL) {
	status = _cairo_surface_set_error (surface, CAIRO_STATUS_NULL_POINTER);
	return;
    }
    if (comment[0] != '%' || strlen (comment) > 255) {
	status = _cairo_surface_set_error (surface, CAIRO_STATUS_INVALID_DSC_COMMENT);
	return;
    }
    /* Then, copy the comment and store it in the appropriate array. */
    comment_copy = strdup (comment);
    if (unlikely (comment_copy == NULL)) {
	status = _cairo_surface_set_error (surface, CAIRO_STATUS_NO_MEMORY);
	return;
    }
    status = _cairo_array_append (ps_surface->dsc_comment_target, &comment_copy);
    if (unlikely (status)) {
	free (comment_copy);
	status = _cairo_surface_set_error (surface, status);
	return;
    }
}
/**
 * cairo_ps_surface_dsc_begin_setup:
 * @surface: a PostScript #cairo_surface_t
 *
 * This function indicates that subsequent calls to
 * cairo_ps_surface_dsc_comment() should direct comments to the Setup
 * section of the PostScript output.
 *
 * This function should be called at most once per surface, and must
 * be called before any call to cairo_ps_surface_dsc_begin_page_setup()
 * and before any drawing is performed to the surface.
 *
 * See cairo_ps_surface_dsc_comment() for more details.
 *
 * Since: 1.2
 **/
void
8
cairo_ps_surface_dsc_begin_setup (cairo_surface_t *surface)
{
8
    cairo_ps_surface_t *ps_surface = NULL;
8
    if (! _extract_ps_surface (surface, TRUE, &ps_surface))
8
	return;
    if (ps_surface->dsc_comment_target == &ps_surface->dsc_header_comments)
	ps_surface->dsc_comment_target = &ps_surface->dsc_setup_comments;
}
/**
 * cairo_ps_surface_dsc_begin_page_setup:
 * @surface: a PostScript #cairo_surface_t
 *
 * This function indicates that subsequent calls to
 * cairo_ps_surface_dsc_comment() should direct comments to the
 * PageSetup section of the PostScript output.
 *
 * This function call is only needed for the first page of a
 * surface. It should be called after any call to
 * cairo_ps_surface_dsc_begin_setup() and before any drawing is
 * performed to the surface.
 *
 * See cairo_ps_surface_dsc_comment() for more details.
 *
 * Since: 1.2
 **/
void
8
cairo_ps_surface_dsc_begin_page_setup (cairo_surface_t *surface)
{
8
    cairo_ps_surface_t *ps_surface = NULL;
8
    if (! _extract_ps_surface (surface, TRUE, &ps_surface))
8
	return;
    if (ps_surface->dsc_comment_target == &ps_surface->dsc_header_comments ||
	ps_surface->dsc_comment_target == &ps_surface->dsc_setup_comments)
    {
	ps_surface->dsc_comment_target = &ps_surface->dsc_page_setup_comments;
    }
}
static cairo_status_t
5
_cairo_ps_surface_finish (void *abstract_surface)
{
    cairo_status_t status, status2;
5
    cairo_ps_surface_t *surface = abstract_surface;
    int i, num_comments;
    char **comments;
5
    status = surface->base.status;
5
    if (unlikely (status))
	goto CLEANUP;
5
    _cairo_ps_surface_emit_header (surface);
5
    _cairo_output_stream_printf (surface->final_stream,
				 "%%%%BeginSetup\n");
5
    num_comments = _cairo_array_num_elements (&surface->dsc_setup_comments);
5
    if (num_comments) {
	comments = _cairo_array_index (&surface->dsc_setup_comments, 0);
	for (i = 0; i < num_comments; i++) {
	    _cairo_output_stream_printf (surface->final_stream,
					 "%s\n", comments[i]);
	    free (comments[i]);
	    comments[i] = NULL;
	}
    }
5
    status = _cairo_ps_surface_emit_font_subsets (surface);
5
    if (unlikely (status))
	goto CLEANUP;
5
    status = _cairo_ps_surface_emit_forms (surface);
5
    if (unlikely (status))
	goto CLEANUP;
5
    _cairo_output_stream_printf (surface->final_stream,
				 "%%%%EndSetup\n");
5
    status = _cairo_ps_surface_emit_body (surface);
5
    if (unlikely (status))
	goto CLEANUP;
5
    _cairo_ps_surface_emit_footer (surface);
5
CLEANUP:
5
    _cairo_hash_table_foreach (surface->forms,
			       _cairo_ps_form_pluck,
5
			       surface->forms);
5
    _cairo_hash_table_destroy (surface->forms);
5
    _cairo_scaled_font_subsets_destroy (surface->font_subsets);
5
    status2 = _cairo_output_stream_destroy (surface->stream);
5
    if (status == CAIRO_STATUS_SUCCESS)
5
	status = status2;
5
    fclose (surface->tmpfile);
5
    status2 = _cairo_output_stream_destroy (surface->final_stream);
5
    if (status == CAIRO_STATUS_SUCCESS)
5
	status = status2;
10
    while (! cairo_list_is_empty (&surface->document_media)) {
        cairo_page_media_t *page;
5
        page = cairo_list_first_entry (&surface->document_media,
                                       cairo_page_media_t,
                                       link);
5
        cairo_list_del (&page->link);
5
	free (page->name);
5
	free (page);
    }
5
    num_comments = _cairo_array_num_elements (&surface->dsc_header_comments);
5
    comments = _cairo_array_index (&surface->dsc_header_comments, 0);
5
    for (i = 0; i < num_comments; i++)
	free (comments[i]);
5
    _cairo_array_fini (&surface->dsc_header_comments);
5
    num_comments = _cairo_array_num_elements (&surface->dsc_setup_comments);
5
    comments = _cairo_array_index (&surface->dsc_setup_comments, 0);
5
    for (i = 0; i < num_comments; i++)
	free (comments[i]);
5
    _cairo_array_fini (&surface->dsc_setup_comments);
5
    num_comments = _cairo_array_num_elements (&surface->dsc_page_setup_comments);
5
    comments = _cairo_array_index (&surface->dsc_page_setup_comments, 0);
5
    for (i = 0; i < num_comments; i++)
	free (comments[i]);
5
    _cairo_array_fini (&surface->dsc_page_setup_comments);
5
    _cairo_array_fini (&surface->recording_surf_stack);
5
    _cairo_surface_clipper_reset (&surface->clipper);
5
    return status;
}
static cairo_int_status_t
5
_cairo_ps_surface_start_page (void *abstract_surface)
{
5
    cairo_ps_surface_t *surface = abstract_surface;
    /* Increment before print so page numbers start at 1. */
5
    surface->num_pages++;
5
    return CAIRO_STATUS_SUCCESS;
}
static cairo_int_status_t
5
_cairo_ps_surface_show_page (void *abstract_surface)
{
5
    cairo_ps_surface_t *surface = abstract_surface;
    cairo_int_status_t status;
5
    if (surface->clipper.clip != NULL)
4
	_cairo_surface_clipper_reset (&surface->clipper);
5
    status = _cairo_pdf_operators_flush (&surface->pdf_operators);
5
    if (unlikely (status))
	return status;
5
    _cairo_output_stream_printf (surface->stream,
				 "Q Q\n"
				 "showpage\n");
5
    return CAIRO_STATUS_SUCCESS;
}
static cairo_bool_t
36
color_is_gray (double red, double green, double blue)
{
36
    const double epsilon = 0.00001;
48
    return (fabs (red - green) < epsilon &&
12
	    fabs (red - blue) < epsilon);
}
/**
 * _cairo_ps_surface_acquire_source_surface_from_pattern:
 * @surface: [in] the ps surface
 * @pattern: [in] A #cairo_pattern_t of type SURFACE or RASTER_SOURCE to use
 *                as the source
 * @extents: [in] extents of the operation that is using this source
 * @src_surface_extents: [out] return source surface extents
 * @src_surface_bounded: [out] return TRUE if source surface is bounded
 * @src_op_extents: [out] return operation extents in source space
 * @source_surface: [out] returns surface of type image surface or recording surface
 * @x_offset: [out] return x offset of surface
 * @y_offset: [out] return y offset of surface
 *
 * Acquire source surface or raster source pattern.
 **/
static cairo_status_t
14
_cairo_ps_surface_acquire_source_surface_from_pattern (
    cairo_ps_surface_t           *surface,
    const cairo_pattern_t        *pattern,
    const cairo_rectangle_int_t  *extents,
    cairo_rectangle_int_t        *src_surface_extents,
    cairo_bool_t                 *src_surface_bounded,
    cairo_rectangle_int_t        *src_op_extents,
    cairo_surface_t             **source_surface,
    double                       *x_offset,
    double                       *y_offset)
{
    cairo_status_t status;
    cairo_box_t bbox;
14
    *x_offset = 0;
14
    *y_offset = 0;
    /* get the operation extents in pattern space */
14
    _cairo_box_from_rectangle (&bbox, extents);
14
    _cairo_matrix_transform_bounding_box_fixed (&pattern->matrix, &bbox, NULL);
14
    _cairo_box_round_to_rectangle (&bbox, src_op_extents);
14
    if (pattern->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE) {
	cairo_surface_t *surf;
	surf = _cairo_raster_source_pattern_acquire (pattern, &surface->base, src_op_extents);
	if (!surf)
	    return CAIRO_INT_STATUS_UNSUPPORTED;
	*src_surface_bounded = _cairo_surface_get_extents (surf, src_surface_extents);
	cairo_surface_get_device_offset (surf, x_offset, y_offset);
	*source_surface = surf;
14
    } else if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE) {
14
	cairo_surface_t *surf = NULL;
14
	*source_surface = ((cairo_surface_pattern_t *) pattern)->surface;
14
	surf = *source_surface;
14
	*src_surface_bounded = _cairo_surface_get_extents (surf, src_surface_extents);
14
	if (surf->type == CAIRO_SURFACE_TYPE_RECORDING) {
4
	    if (_cairo_surface_is_snapshot (surf))
4
		surf = _cairo_surface_snapshot_get_target (surf);
4
	    if (surf->backend->type == CAIRO_SURFACE_TYPE_SUBSURFACE) {
		cairo_surface_subsurface_t *sub = (cairo_surface_subsurface_t *) surf;
		*src_surface_extents = sub->extents;
		*src_surface_bounded = TRUE;
		*x_offset = -sub->extents.x;
		*y_offset = -sub->extents.y;
	    }
4
	    cairo_surface_destroy (surf);
10
	} else if (surf->type != CAIRO_SURFACE_TYPE_IMAGE) {
	    cairo_image_surface_t *image;
	    void *image_extra;
	    status = _cairo_surface_acquire_source_image (surf, &image, &image_extra);
	    if (unlikely (status))
		return status;
	    *src_surface_bounded = _cairo_surface_get_extents (&image->base, src_surface_extents);
	    _cairo_surface_release_source_image (surf, image, image_extra);
	}
    } else {
	ASSERT_NOT_REACHED;
    }
14
    return CAIRO_STATUS_SUCCESS;
}
static void
14
_cairo_ps_surface_release_source_surface_from_pattern (cairo_ps_surface_t           *surface,
						       const cairo_pattern_t        *pattern,
						       cairo_surface_t              *source_surface)
{
14
    if  (pattern->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE)
	_cairo_raster_source_pattern_release (pattern, source_surface);
14
}
/**
 * _cairo_ps_surface_create_padded_image_from_image:
 * @surface: the ps surface
 * @source: The source image
 * @extents: extents of the operation that is using this source
 * @image: returns the padded image or NULL if padding not required to fill @extents
 * @image_extents: returns extents of padded image. These extents in are in source image space.
 *
 * Creates a padded image if the source image does not fill the extents.
 **/
static cairo_status_t
_cairo_ps_surface_create_padded_image_from_image (cairo_ps_surface_t           *surface,
						  cairo_image_surface_t        *source,
						  const cairo_matrix_t         *source_matrix,
						  const cairo_rectangle_int_t  *extents,
						  cairo_image_surface_t       **image,
						  cairo_rectangle_int_t        *image_extents)
{
    cairo_box_t box;
    cairo_rectangle_int_t rect;
    cairo_surface_t	   *pad_image;
    cairo_surface_pattern_t pad_pattern;
    int w, h;
    cairo_int_status_t      status;
    /* get the operation extents in pattern space */
    _cairo_box_from_rectangle (&box, extents);
    _cairo_matrix_transform_bounding_box_fixed (source_matrix, &box, NULL);
    _cairo_box_round_to_rectangle (&box, &rect);
    /* Check if image needs padding to fill extents. */
    w = source->width;
    h = source->height;
    if (_cairo_fixed_integer_ceil(box.p1.x) < 0 ||
	_cairo_fixed_integer_ceil(box.p1.y) < 0 ||
	_cairo_fixed_integer_floor(box.p2.y) > w ||
	_cairo_fixed_integer_floor(box.p2.y) > h)
    {
	pad_image = _cairo_image_surface_create_with_content (source->base.content,
							      rect.width,
							      rect.height);
	if (pad_image->status)
	    return pad_image->status;
	_cairo_pattern_init_for_surface (&pad_pattern, &source->base);
	cairo_matrix_init_translate (&pad_pattern.base.matrix, rect.x, rect.y);
	pad_pattern.base.extend = CAIRO_EXTEND_PAD;
	status = _cairo_surface_paint (pad_image,
				       CAIRO_OPERATOR_SOURCE,
				       &pad_pattern.base,
				       NULL);
	_cairo_pattern_fini (&pad_pattern.base);
	*image = (cairo_image_surface_t *) pad_image;
	image_extents->x = rect.x;
	image_extents->y = rect.y;
	image_extents->width = rect.width;
	image_extents->height = rect.height;
    } else {
	*image = NULL;
	status = CAIRO_STATUS_SUCCESS;
    }
    return status;
}
static cairo_int_status_t
_cairo_ps_surface_analyze_surface_pattern_transparency (cairo_ps_surface_t            *surface,
							const cairo_pattern_t         *pattern,
							const cairo_rectangle_int_t   *extents)
{
    cairo_rectangle_int_t src_surface_extents;
    cairo_bool_t src_surface_bounded;
    cairo_rectangle_int_t src_op_extents;
    cairo_surface_t *source_surface;
    double x_offset, y_offset;
    cairo_image_surface_t *image;
    void *image_extra;
    cairo_int_status_t status;
    cairo_image_transparency_t transparency;
    status = _cairo_ps_surface_acquire_source_surface_from_pattern (surface,
								    pattern,
								    extents,
								    &src_surface_extents,
								    &src_surface_bounded,
								    &src_op_extents,
								    &source_surface,
								    &x_offset,
								    &y_offset);
    if (unlikely (status))
	return status;
    status = _cairo_surface_acquire_source_image (source_surface, &image, &image_extra);
    if (unlikely (status))
	return status;
    if (image->base.status)
	return image->base.status;
    transparency = _cairo_image_analyze_transparency (image);
    switch (transparency) {
    case CAIRO_IMAGE_IS_OPAQUE:
	status = CAIRO_STATUS_SUCCESS;
	break;
    case CAIRO_IMAGE_HAS_BILEVEL_ALPHA:
	if (surface->ps_level == CAIRO_PS_LEVEL_2) {
	    status = CAIRO_INT_STATUS_FLATTEN_TRANSPARENCY;
	} else {
	    surface->ps_level_used = CAIRO_PS_LEVEL_3;
	    status = CAIRO_STATUS_SUCCESS;
	}
	break;
    case CAIRO_IMAGE_HAS_ALPHA:
	status = CAIRO_INT_STATUS_FLATTEN_TRANSPARENCY;
	break;
    case CAIRO_IMAGE_UNKNOWN:
	ASSERT_NOT_REACHED;
    }
    _cairo_surface_release_source_image (source_surface, image, image_extra);
    _cairo_ps_surface_release_source_surface_from_pattern (surface, pattern, source_surface);
    return status;
}
static cairo_bool_t
23
surface_pattern_supported (const cairo_surface_pattern_t *pattern)
{
23
    if (pattern->surface->type == CAIRO_SURFACE_TYPE_RECORDING)
13
	return TRUE;
10
    if (pattern->surface->backend->acquire_source_image == NULL)
	return FALSE;
    /* Does an ALPHA-only source surface even make sense? Maybe, but I
     * don't think it's worth the extra code to support it. */
/* XXX: Need to write this function here...
    content = pattern->surface->content;
    if (content == CAIRO_CONTENT_ALPHA)
	return FALSE;
*/
10
    return TRUE;
}
static cairo_bool_t
_gradient_pattern_supported (cairo_ps_surface_t    *surface,
			     const cairo_pattern_t *pattern)
{
    double min_alpha, max_alpha;
    if (surface->ps_level == CAIRO_PS_LEVEL_2)
	return FALSE;
    /* Alpha gradients are only supported (by flattening the alpha)
     * if there is no variation in the alpha across the gradient. */
    _cairo_pattern_alpha_range (pattern, &min_alpha, &max_alpha);
    if (min_alpha != max_alpha)
	return FALSE;
    surface->ps_level_used = CAIRO_PS_LEVEL_3;
    return TRUE;
}
static cairo_bool_t
95
pattern_supported (cairo_ps_surface_t *surface, const cairo_pattern_t *pattern)
{
95
    switch (pattern->type) {
72
    case CAIRO_PATTERN_TYPE_SOLID:
72
	return TRUE;
    case CAIRO_PATTERN_TYPE_LINEAR:
    case CAIRO_PATTERN_TYPE_RADIAL:
    case CAIRO_PATTERN_TYPE_MESH:
	return _gradient_pattern_supported (surface, pattern);
23
    case CAIRO_PATTERN_TYPE_SURFACE:
23
	return surface_pattern_supported ((cairo_surface_pattern_t *) pattern);
    case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
	return TRUE;
    default:
	ASSERT_NOT_REACHED;
	return FALSE;
    }
}
static cairo_bool_t
mask_supported (cairo_ps_surface_t *surface,
		const cairo_pattern_t *mask,
		const cairo_rectangle_int_t *extents)
{
    if (surface->ps_level == CAIRO_PS_LEVEL_2)
	return FALSE;
    if (mask->type == CAIRO_PATTERN_TYPE_SURFACE) {
	cairo_surface_pattern_t *surface_pattern = (cairo_surface_pattern_t *) mask;
	if (surface_pattern->surface->type == CAIRO_SURFACE_TYPE_IMAGE) {
	    /* check if mask if opaque or bilevel alpha */
	    if (_cairo_ps_surface_analyze_surface_pattern_transparency (surface, mask, extents) == CAIRO_INT_STATUS_SUCCESS) {
		surface->ps_level_used = CAIRO_PS_LEVEL_3;
		return TRUE;
	    }
	}
    }
    return FALSE;
}
static cairo_int_status_t
95
_cairo_ps_surface_analyze_operation (cairo_ps_surface_t    *surface,
				     cairo_operator_t       op,
				     const cairo_pattern_t       *pattern,
				     const cairo_pattern_t       *mask,
				     const cairo_rectangle_int_t *extents)
{
    double min_alpha;
95
    if (surface->force_fallbacks &&
	surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE)
    {
	return CAIRO_INT_STATUS_UNSUPPORTED;
    }
95
    if (! pattern_supported (surface, pattern))
	return CAIRO_INT_STATUS_UNSUPPORTED;
95
    if (! (op == CAIRO_OPERATOR_SOURCE || op == CAIRO_OPERATOR_OVER))
4
	return CAIRO_INT_STATUS_UNSUPPORTED;
    /* Mask is only supported when the mask is an image with opaque or bilevel alpha. */
91
    if (mask && !mask_supported (surface, mask, extents))
	return CAIRO_INT_STATUS_UNSUPPORTED;
91
    if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE) {
23
	cairo_surface_pattern_t *surface_pattern = (cairo_surface_pattern_t *) pattern;
23
	if (surface_pattern->surface->type == CAIRO_SURFACE_TYPE_RECORDING) {
13
	    if (pattern->extend == CAIRO_EXTEND_PAD) {
		cairo_box_t box;
		cairo_rectangle_int_t rect;
		cairo_rectangle_int_t rec_extents;
		/* get the operation extents in pattern space */
		_cairo_box_from_rectangle (&box, extents);
		_cairo_matrix_transform_bounding_box_fixed (&pattern->matrix, &box, NULL);
		_cairo_box_round_to_rectangle (&box, &rect);
		/* Check if surface needs padding to fill extents */
		if (_cairo_surface_get_extents (surface_pattern->surface, &rec_extents)) {
		    if (_cairo_fixed_integer_ceil(box.p1.x) < rec_extents.x ||
			_cairo_fixed_integer_ceil(box.p1.y) < rec_extents.y ||
			_cairo_fixed_integer_floor(box.p2.y) > rec_extents.x + rec_extents.width ||
			_cairo_fixed_integer_floor(box.p2.y) > rec_extents.y + rec_extents.height)
		    {
			return CAIRO_INT_STATUS_UNSUPPORTED;
		    }
		}
	    }
13
	    return CAIRO_INT_STATUS_ANALYZE_RECORDING_SURFACE_PATTERN;
	}
    }
78
    if (op == CAIRO_OPERATOR_SOURCE) {
58
	if (mask)
	    return CAIRO_INT_STATUS_UNSUPPORTED;
	else
58
	    return CAIRO_STATUS_SUCCESS;
    }
    /* CAIRO_OPERATOR_OVER is only supported for opaque patterns. If
     * the pattern contains transparency, we return
     * CAIRO_INT_STATUS_FLATTEN_TRANSPARENCY to the analysis
     * surface. If the analysis surface determines that there is
     * anything drawn under this operation, a fallback image will be
     * used. Otherwise the operation will be replayed during the
     * render stage and we blend the transparency into the white
     * background to convert the pattern to opaque.
     */
20
    if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE || pattern->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE)
	return _cairo_ps_surface_analyze_surface_pattern_transparency (surface, pattern, extents);
    /* Patterns whose drawn part is opaque are directly supported;
       those whose drawn part is partially transparent can be
       supported by flattening the alpha. */
20
    _cairo_pattern_alpha_range (pattern, &min_alpha, NULL);
20
    if (CAIRO_ALPHA_IS_OPAQUE (min_alpha))
20
	return CAIRO_STATUS_SUCCESS;
    return CAIRO_INT_STATUS_FLATTEN_TRANSPARENCY;
}
static cairo_bool_t
50
_cairo_ps_surface_operation_supported (cairo_ps_surface_t    *surface,
				       cairo_operator_t       op,
				       const cairo_pattern_t       *pattern,
				       const cairo_pattern_t       *mask,
				       const cairo_rectangle_int_t *extents)
{
50
    return _cairo_ps_surface_analyze_operation (surface, op, pattern, mask, extents) != CAIRO_INT_STATUS_UNSUPPORTED;
}
/* The "standard" implementation limit for PostScript string sizes is
 * 65535 characters (see PostScript Language Reference, Appendix
 * B).
 */
#define STRING_ARRAY_MAX_STRING_SIZE 65535
#define STRING_ARRAY_MAX_COLUMN	     72
typedef struct _string_array_stream {
    cairo_output_stream_t base;
    cairo_output_stream_t *output;
    int column;
    int string_size;
    int tuple_count;
    cairo_bool_t use_strings;
} string_array_stream_t;
static cairo_status_t
7364
_base85_string_wrap_stream_write (cairo_output_stream_t *base,
				  const unsigned char   *data,
				  unsigned int	   length)
{
7364
    string_array_stream_t *stream = (string_array_stream_t *) base;
    unsigned char c;
7364
    if (length == 0)
	return CAIRO_STATUS_SUCCESS;
44156
    while (length--) {
36792
	if (stream->column == 0) {
20
	    if (stream->use_strings) {
		_cairo_output_stream_printf (stream->output, "<~");
		stream->column = 2;
	    } else {
20
		_cairo_output_stream_printf (stream->output, " ");
20
		stream->column = 1;
	    }
	}
36792
	c = *data++;
36792
	_cairo_output_stream_write (stream->output, &c, 1);
36792
	stream->column++;
	/* Base85 encodes each 4 byte tuple with a 5 ASCII character
	 * tuple, except for 'z' with represents 4 zero bytes. We need
	 * to keep track of the string length after decoding.
	 */
36792
	if (c == 'z') {
	    stream->string_size += 4;
	    stream->tuple_count = 0;
	} else {
36792
	    if (++stream->tuple_count == 5) {
7350
		stream->string_size += 4;
7350
		stream->tuple_count = 0;
	    }
	}
	/* Split string at tuple boundary when there is not enough
	 * space for another tuple */
36792
	if (stream->use_strings &&
	    stream->tuple_count == 0 &&
	    stream->string_size > STRING_ARRAY_MAX_STRING_SIZE - 4)
	{
	    _cairo_output_stream_printf (stream->output, "~>\n");
	    stream->string_size = 0;
	    stream->column = 0;
	}
36792
	if (stream->column >= STRING_ARRAY_MAX_COLUMN) {
508
	    _cairo_output_stream_printf (stream->output, "\n ");
508
	    stream->column = 1;
	}
    }
7364
    return _cairo_output_stream_get_status (stream->output);
}
static cairo_status_t
20
_base85_string_wrap_stream_close (cairo_output_stream_t *base)
{
20
    string_array_stream_t *stream = (string_array_stream_t *) base;
20
    if (!stream->use_strings || stream->string_size != 0)
20
	_cairo_output_stream_printf (stream->output, "~>");
20
    return _cairo_output_stream_get_status (stream->output);
}
/* A _base85_strings_stream wraps an existing output stream. It takes
 * base85 encoded data and splits it into strings each limited to
 * STRING_ARRAY_MAX_STRING_SIZE bytes when decoded. Each string is
 * enclosed in "<~" and "~>".
 * The string array stream is also careful to wrap the output within
 * STRING_ARRAY_MAX_COLUMN columns. Wrapped lines start with a space
 * in case an encoded line starts with %% which could be interpreted
 * as a DSC comment.
 */
static cairo_output_stream_t *
_base85_strings_stream_create (cairo_output_stream_t *output)
{
    string_array_stream_t *stream;
    stream = _cairo_calloc (sizeof (string_array_stream_t));
    if (unlikely (stream == NULL)) {
	_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
	return (cairo_output_stream_t *) &_cairo_output_stream_nil;
    }
    _cairo_output_stream_init (&stream->base,
			       _base85_string_wrap_stream_write,
			       NULL,
			       _base85_string_wrap_stream_close);
    stream->output = output;
    stream->column = 0;
    stream->string_size = 0;
    stream->tuple_count = 0;
    stream->use_strings = TRUE;
    return &stream->base;
}
/* A base85_wrap_stream wraps an existing output stream. It wraps the
 * output within STRING_ARRAY_MAX_COLUMN columns. A base85 EOD "~>" is
 * appended to the end. Wrapped lines start with a space in case an
 * encoded line starts with %% which could be interpreted as a DSC
 * comment.
 */
static cairo_output_stream_t *
20
_base85_wrap_stream_create (cairo_output_stream_t *output)
{
    string_array_stream_t *stream;
20
    stream = _cairo_calloc (sizeof (string_array_stream_t));
20
    if (unlikely (stream == NULL)) {
	_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
	return (cairo_output_stream_t *) &_cairo_output_stream_nil;
    }
20
    _cairo_output_stream_init (&stream->base,
			       _base85_string_wrap_stream_write,
			       NULL,
			       _base85_string_wrap_stream_close);
20
    stream->output = output;
20
    stream->column = 0;
20
    stream->string_size = 0;
20
    stream->tuple_count = 0;
20
    stream->use_strings = FALSE;
20
    return &stream->base;
}
/* PS Output - this section handles output of the parts of the recording
 * surface we can render natively in PS. */
static cairo_status_t
20
_cairo_ps_surface_flatten_image_transparency (cairo_ps_surface_t    *surface,
					      cairo_image_surface_t *image,
					      cairo_image_surface_t **opaque_image)
{
    cairo_surface_t *opaque;
    cairo_surface_pattern_t pattern;
    cairo_status_t status;
20
    opaque = cairo_image_surface_create (CAIRO_FORMAT_RGB24,
					 image->width,
					 image->height);
20
    if (unlikely (opaque->status))
	return opaque->status;
20
    if (surface->content == CAIRO_CONTENT_COLOR_ALPHA) {
20
	status = _cairo_surface_paint (opaque,
				       CAIRO_OPERATOR_SOURCE,
				       &_cairo_pattern_white.base,
				       NULL);
20
	if (unlikely (status)) {
	    cairo_surface_destroy (opaque);
	    return status;
	}
    }
20
    _cairo_pattern_init_for_surface (&pattern, &image->base);
20
    pattern.base.filter = CAIRO_FILTER_NEAREST;
20
    status = _cairo_surface_paint (opaque, CAIRO_OPERATOR_OVER, &pattern.base, NULL);
20
    _cairo_pattern_fini (&pattern.base);
20
    if (unlikely (status)) {
	cairo_surface_destroy (opaque);
	return status;
    }
20
    *opaque_image = (cairo_image_surface_t *) opaque;
20
    return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
20
_cairo_ps_surface_emit_base85_string (cairo_ps_surface_t    *surface,
				      const unsigned char   *data,
				      unsigned long	     length,
				      cairo_ps_compress_t    compress,
				      cairo_bool_t           use_strings)
{
    cairo_output_stream_t *base85_stream, *string_array_stream, *deflate_stream;
    unsigned char *data_compressed;
    unsigned long data_compressed_size;
    cairo_status_t status, status2;
    cairo_status_t this_cannot_be_handled;
20
    if (use_strings)
	string_array_stream = _base85_strings_stream_create (surface->stream);
    else
20
	string_array_stream = _base85_wrap_stream_create (surface->stream);
20
    status = _cairo_output_stream_get_status (string_array_stream);
20
    if (unlikely (status))
	return _cairo_output_stream_destroy (string_array_stream);
20
    base85_stream = _cairo_base85_stream_create (string_array_stream);
20
    status = _cairo_output_stream_get_status (base85_stream);
20
    if (unlikely (status)) {
	status2 = _cairo_output_stream_destroy (string_array_stream);
	return _cairo_output_stream_destroy (base85_stream);
    }
20
    status = 0;
20
    switch (compress) {
	case CAIRO_PS_COMPRESS_NONE:
	    _cairo_output_stream_write (base85_stream, data, length);
	    break;
	case CAIRO_PS_COMPRESS_LZW:
	    /* XXX: Should fix cairo-lzw to provide a stream-based interface
	     * instead. */
	    data_compressed_size = length;
	    data_compressed = _cairo_lzw_compress ((unsigned char*)data, &data_compressed_size);
	    if (unlikely (data_compressed == NULL)) {
		this_cannot_be_handled = _cairo_output_stream_destroy (string_array_stream);
		this_cannot_be_handled = _cairo_output_stream_destroy (base85_stream);
		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
	    }
	    _cairo_output_stream_write (base85_stream, data_compressed, data_compressed_size);
	    free (data_compressed);
	    break;
20
	case CAIRO_PS_COMPRESS_DEFLATE:
20
	    deflate_stream = _cairo_deflate_stream_create (base85_stream);
20
	    if (_cairo_output_stream_get_status (deflate_stream)) {
		return _cairo_output_stream_destroy (deflate_stream);
	    }
20
	    _cairo_output_stream_write (deflate_stream, data, length);
20
	    status = _cairo_output_stream_destroy (deflate_stream);
20
	    if (unlikely (status)) {
		this_cannot_be_handled = _cairo_output_stream_destroy (string_array_stream);
		this_cannot_be_handled = _cairo_output_stream_destroy (base85_stream);
		return status;
	    }
20
	    break;
    }
20
    status = _cairo_output_stream_destroy (base85_stream);
20
    status2 = _cairo_output_stream_destroy (string_array_stream);
20
    if (status == CAIRO_STATUS_SUCCESS)
20
	status = status2;
20
    return status;
}
static const char *
20
get_interpolate (cairo_filter_t	filter)
{
    const char *interpolate;
20
    switch (filter) {
	default:
	case CAIRO_FILTER_GOOD:
	case CAIRO_FILTER_BEST:
	case CAIRO_FILTER_BILINEAR:
	    interpolate = "true";
	    break;
20
	case CAIRO_FILTER_FAST:
	case CAIRO_FILTER_NEAREST:
	case CAIRO_FILTER_GAUSSIAN:
20
	    interpolate = "false";
20
	break;
    }
20
    return interpolate;
}
static cairo_status_t
20
_cairo_ps_surface_emit_image (cairo_ps_surface_t          *surface,
			      cairo_emit_surface_mode_t    mode,
			      cairo_emit_surface_params_t *params)
{
    cairo_status_t status;
    unsigned char *data;
    unsigned long data_size;
    cairo_image_surface_t *ps_image;
    int x, y, i, a;
    cairo_image_transparency_t transparency;
    cairo_bool_t use_mask;
    uint32_t *pixel32;
    uint8_t *pixel8;
    int bit;
    cairo_image_color_t color;
    const char *interpolate;
    cairo_ps_compress_t compress;
    const char *compress_filter;
    cairo_image_surface_t *image_surf;
    cairo_image_surface_t *image;
    void *image_extra;
20
    if (params->src_surface->status)
	return params->src_surface->status;
20
    status = _cairo_surface_acquire_source_image (params->src_surface, &image_surf, &image_extra);
20
    if (unlikely (status))
	return status;
20
    image  = image_surf;
20
    if (image->format != CAIRO_FORMAT_RGB24 &&
20
	image->format != CAIRO_FORMAT_ARGB32 &&
	image->format != CAIRO_FORMAT_A8 &&
	image->format != CAIRO_FORMAT_A1)
    {
	cairo_surface_t *surf;
	cairo_surface_pattern_t pattern;
	surf = _cairo_image_surface_create_with_content (image->base.content,
							 image->width,
							 image->height);
	if (surf->status) {
	    status = surf->status;
	    goto bail0;
	}
	_cairo_pattern_init_for_surface (&pattern, &image->base);
	status = _cairo_surface_paint (surf,
				       CAIRO_OPERATOR_SOURCE, &pattern.base,
				       NULL);
        _cairo_pattern_fini (&pattern.base);
	image = (cairo_image_surface_t *) surf;
        if (unlikely (status))
            goto bail0;
    }
20
    ps_image = image;
20
    interpolate = get_interpolate (params->filter);
20
    if (params->stencil_mask) {
	use_mask = FALSE;
	color = CAIRO_IMAGE_IS_MONOCHROME;
	transparency = CAIRO_IMAGE_HAS_BILEVEL_ALPHA;
    } else {
20
	transparency = _cairo_image_analyze_transparency (image);
	/* PostScript can not represent the alpha channel, so we blend the
	   current image over a white (or black for CONTENT_COLOR
	   surfaces) RGB surface to eliminate it. */
20
	if (params->op == CAIRO_OPERATOR_SOURCE ||
	    transparency == CAIRO_IMAGE_HAS_ALPHA ||
	    (transparency == CAIRO_IMAGE_HAS_BILEVEL_ALPHA &&
	     surface->ps_level == CAIRO_PS_LEVEL_2))
	{
20
	    status = _cairo_ps_surface_flatten_image_transparency (surface,
								   image,
								   &ps_image);
20
	    if (unlikely (status))
		return status;
20
	    use_mask = FALSE;
	} else if (transparency == CAIRO_IMAGE_IS_OPAQUE) {
	    use_mask = FALSE;
	} else { /* transparency == CAIRO_IMAGE_HAS_BILEVEL_ALPHA */
	    use_mask = TRUE;
	}
20
	color = _cairo_image_analyze_color (ps_image);
    }
    /* Type 2 (mask and image interleaved) has the mask and image
     * samples interleaved by row.  The mask row is first, one bit per
     * pixel with (bit 7 first). The row is padded to byte
     * boundaries. The image data is 3 bytes per pixel RGB format. */
20
    switch (color) {
    default:
    case CAIRO_IMAGE_UNKNOWN_COLOR:
	ASSERT_NOT_REACHED;
    case CAIRO_IMAGE_IS_COLOR:
16
	data_size = ps_image->width * 3;
16
	break;
    case CAIRO_IMAGE_IS_GRAYSCALE:
	data_size = ps_image->width;
	break;
4
    case CAIRO_IMAGE_IS_MONOCHROME:
4
	data_size = (ps_image->width + 7)/8;
4
	break;
    }
20
    if (use_mask)
	data_size += (ps_image->width + 7)/8;
20
    data_size *= ps_image->height;
20
    data = _cairo_malloc (data_size);
20
    if (unlikely (data == NULL)) {
	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	goto bail1;
    }
20
    i = 0;
2036
    for (y = 0; y < ps_image->height; y++) {
2016
	if (params->stencil_mask || use_mask) {
	    /* mask row */
	    if (ps_image->format == CAIRO_FORMAT_A1) {
		pixel8 = (uint8_t *) (ps_image->data + y * ps_image->stride);
		for (x = 0; x < (ps_image->width + 7) / 8; x++, pixel8++) {
		    a = *pixel8;
		    a = CAIRO_BITSWAP8_IF_LITTLE_ENDIAN (a);
		    data[i++] = a;
		}
	    } else {
		pixel8 = (uint8_t *) (ps_image->data + y * ps_image->stride);
		pixel32 = (uint32_t *) (ps_image->data + y * ps_image->stride);
		bit = 7;
		for (x = 0; x < ps_image->width; x++) {
		    if (ps_image->format == CAIRO_FORMAT_ARGB32) {
			a = (*pixel32 & 0xff000000) >> 24;
			pixel32++;
		    } else {
			a = *pixel8;
			pixel8++;
		    }
		    if (transparency == CAIRO_IMAGE_HAS_ALPHA) {
			data[i++] = a;
		    } else { /* transparency == CAIRO_IMAGE_HAS_BILEVEL_ALPHA or CAIRO_IMAGE_IS_OPAQUE */
			if (bit == 7)
			    data[i] = 0;
			if (a != 0)
			    data[i] |= (1 << bit);
			bit--;
			if (bit < 0) {
			    bit = 7;
			    i++;
			}
		    }
		}
		if (bit != 7)
		    i++;
	    }
	}
2016
	if (params->stencil_mask)
	    continue;
	/* image row*/
2016
	pixel32 = (uint32_t *) (ps_image->data + y * ps_image->stride);
2016
	bit = 7;
359854
	for (x = 0; x < ps_image->width; x++, pixel32++) {
	    int r, g, b;
357838
	    if (ps_image->format == CAIRO_FORMAT_ARGB32) {
		/* At this point ARGB32 images are either opaque or
		 * bilevel alpha so we don't need to unpremultiply. */
		if (((*pixel32 & 0xff000000) >> 24) == 0) {
		    r = g = b = 0;
		} else {
		    r = (*pixel32 & 0x00ff0000) >> 16;
		    g = (*pixel32 & 0x0000ff00) >>  8;
		    b = (*pixel32 & 0x000000ff) >>  0;
		}
357838
	    } else if (ps_image->format == CAIRO_FORMAT_RGB24) {
357838
		r = (*pixel32 & 0x00ff0000) >> 16;
357838
		g = (*pixel32 & 0x0000ff00) >>  8;
357838
		b = (*pixel32 & 0x000000ff) >>  0;
	    } else {
		r = g = b = 0;
	    }
357838
	    switch (color) {
269150
		case CAIRO_IMAGE_IS_COLOR:
		case CAIRO_IMAGE_UNKNOWN_COLOR:
269150
		    data[i++] = r;
269150
		    data[i++] = g;
269150
		    data[i++] = b;
269150
		    break;
		case CAIRO_IMAGE_IS_GRAYSCALE:
		    data[i++] = r;
		    break;
88688
		case CAIRO_IMAGE_IS_MONOCHROME:
88688
		    if (bit == 7)
11264
			data[i] = 0;
88688
		    if (r != 0)
88688
			data[i] |= (1 << bit);
88688
		    bit--;
88688
		    if (bit < 0) {
10720
			bit = 7;
10720
			i++;
		    }
88688
		    break;
	    }
	}
2016
	if (bit != 7)
544
	    i++;
    }
20
    if (surface->ps_level == CAIRO_PS_LEVEL_2) {
	compress = CAIRO_PS_COMPRESS_LZW;
	compress_filter = "LZWDecode";
    } else {
20
	compress = CAIRO_PS_COMPRESS_DEFLATE;
20
	compress_filter = "FlateDecode";
20
	surface->ps_level_used = CAIRO_PS_LEVEL_3;
    }
20
    if (surface->paint_proc) {
	/* Emit the image data as a base85-encoded string which will
	 * be used as the data source for the image operator later. */
	_cairo_output_stream_printf (surface->stream,
				     "/CairoData [\n");
	status = _cairo_ps_surface_emit_base85_string (surface,
						       data,
						       data_size,
						       compress,
						       TRUE);
	if (unlikely (status))
	    goto bail2;
	_cairo_output_stream_printf (surface->stream,
				     "] def\n");
	_cairo_output_stream_printf (surface->stream,
				     "/CairoDataIndex 0 def\n");
    } else {
20
	_cairo_output_stream_printf (surface->stream,
				     "/cairo_ascii85_file currentfile /ASCII85Decode filter def\n");
    }
20
    if (use_mask) {
	_cairo_output_stream_printf (surface->stream,
				     "%s setcolorspace\n"
				     "<<\n"
				     "  /ImageType 3\n"
				     "  /InterleaveType 2\n"
				     "  /DataDict <<\n"
				     "    /ImageType 1\n"
				     "    /Width %d\n"
				     "    /Height %d\n"
				     "    /Interpolate %s\n"
				     "    /BitsPerComponent %d\n"
				     "    /Decode [ %s ]\n",
				     color == CAIRO_IMAGE_IS_COLOR ? "/DeviceRGB" : "/DeviceGray",
				     ps_image->width,
				     ps_image->height,
				     interpolate,
				     color == CAIRO_IMAGE_IS_MONOCHROME ? 1 : 8,
				     color == CAIRO_IMAGE_IS_COLOR ? "0 1 0 1 0 1" : "0 1");
	if (surface->paint_proc) {
	    _cairo_output_stream_printf (surface->stream,
					 "    /DataSource { cairo_data_source } /%s filter\n",
					 compress_filter);
	} else {
	    _cairo_output_stream_printf (surface->stream,
					 "    /DataSource cairo_ascii85_file /%s filter\n",
					 compress_filter);
	}
	_cairo_output_stream_printf (surface->stream,
				     "    /ImageMatrix [ %d 0 0 %d 0 %d ]\n"
				     "  >>\n"
				     "  /MaskDict <<\n"
				     "    /ImageType 1\n"
				     "    /Width %d\n"
				     "    /Height %d\n"
				     "    /Interpolate %s\n"
				     "    /BitsPerComponent 1\n"
				     "    /Decode [ 1 0 ]\n"
				     "    /ImageMatrix [ %d 0 0 %d 0 %d ]\n"
				     "  >>\n"
				     ">>\n"
				     "image\n",
				     ps_image->width,
				     -ps_image->height,
				     ps_image->height,
				     ps_image->width,
				     ps_image->height,
				     interpolate,
				     ps_image->width,
				     -ps_image->height,
				     ps_image->height);
    } else {
	const char *decode;
20
	if (!params->stencil_mask) {
20
	    _cairo_output_stream_printf (surface->stream,
					 "%s setcolorspace\n",
					 color == CAIRO_IMAGE_IS_COLOR ? "/DeviceRGB" : "/DeviceGray");
	}
20
	if (params->stencil_mask)
	    decode = "1 0";
20
	else if (color == CAIRO_IMAGE_IS_COLOR)
16
	    decode = "0 1 0 1 0 1";
	else
4
	    decode ="0 1";
20
	_cairo_output_stream_printf (surface->stream,
				     "<<\n"
				     "  /ImageType 1\n"
				     "  /Width %d\n"
				     "  /Height %d\n"
				     "  /Interpolate %s\n"
				     "  /BitsPerComponent %d\n"
				     "  /Decode [ %s ]\n",
20
				     ps_image->width,
20
				     ps_image->height,
				     interpolate,
				     color == CAIRO_IMAGE_IS_MONOCHROME ? 1 : 8,
				     decode);
20
	if (surface->paint_proc) {
	    _cairo_output_stream_printf (surface->stream,
					 "  /DataSource { cairo_data_source } /%s filter\n",
					 compress_filter);
	} else {
20
	    _cairo_output_stream_printf (surface->stream,
					 "  /DataSource cairo_ascii85_file /%s filter\n",
					 compress_filter);
	}
40
	_cairo_output_stream_printf (surface->stream,
				     "  /ImageMatrix [ %d 0 0 %d 0 %d ]\n"
				     ">>\n"
				     "%s%s\n",
20
				     ps_image->width,
20
				     -ps_image->height,
20
				     ps_image->height,
20
				     surface->paint_proc ? "" : "cairo_",
20
				     params->stencil_mask ? "imagemask" : "image");
    }
20
    if (!surface->paint_proc) {
	/* Emit the image data as a base85-encoded string which will
	 * be used as the data source for the image operator. */
20
	status = _cairo_ps_surface_emit_base85_string (surface,
						       data,
						       data_size,
						       compress,
						       FALSE);
20
	_cairo_output_stream_printf (surface->stream, "\n");
    } else {
	status = CAIRO_STATUS_SUCCESS;
    }
20
bail2:
20
    free (data);
20
bail1:
20
    if (!use_mask && ps_image != image)
20
	cairo_surface_destroy (&ps_image->base);
bail0:
20
    if (image != image_surf)
	cairo_surface_destroy (&image->base);
20
    _cairo_surface_release_source_image (params->src_surface, image_surf, image_extra);
20
    return status;
}
static cairo_int_status_t
28
_cairo_ps_surface_emit_jpeg_image (cairo_ps_surface_t          *surface,
				   cairo_emit_surface_mode_t    mode,
				   cairo_emit_surface_params_t *params)
{
    cairo_status_t status;
    const unsigned char *mime_data;
    unsigned long mime_data_length;
    cairo_image_info_t info;
    const char *colorspace;
    const char *decode;
28
    if (unlikely (params->src_surface->status))
	return params->src_surface->status;
28
    cairo_surface_get_mime_data (params->src_surface, CAIRO_MIME_TYPE_JPEG,
				 &mime_data, &mime_data_length);
28
    if (mime_data == NULL)
28
	return CAIRO_INT_STATUS_UNSUPPORTED;
    status = _cairo_image_info_get_jpeg_info (&info, mime_data, mime_data_length);
    if (unlikely (status))
	return status;
    switch (info.num_components) {
	case 1:
	    colorspace = "/DeviceGray";
	    decode = "0 1";
	    break;
	case 3:
	    colorspace = "/DeviceRGB";
	    decode =  "0 1 0 1 0 1";
	    break;
	case 4:
	    colorspace = "/DeviceCMYK";
	    decode =  "0 1 0 1 0 1 0 1";
	    break;
	default:
	    return CAIRO_INT_STATUS_UNSUPPORTED;
    }
    /* At this point we know emitting jpeg will succeed. */
    if (mode == CAIRO_EMIT_SURFACE_ANALYZE) {
	params->is_image = TRUE;
	params->approx_size = mime_data_length;
	return CAIRO_STATUS_SUCCESS;
    }
    if (surface->paint_proc) {
	/* Emit the image data as a base85-encoded string which will
	 * be used as the data source for the image operator later. */
	_cairo_output_stream_printf (surface->stream,
				     "/CairoData [\n");
	status = _cairo_ps_surface_emit_base85_string (surface,
						       mime_data,
						       mime_data_length,
						       CAIRO_PS_COMPRESS_NONE,
						       TRUE);
	if (unlikely (status))
	    return status;
	_cairo_output_stream_printf (surface->stream,
				     "] def\n");
	_cairo_output_stream_printf (surface->stream,
				     "/CairoDataIndex 0 def\n");
    } else {
	_cairo_output_stream_printf (surface->stream,
				     "/cairo_ascii85_file currentfile /ASCII85Decode filter def\n");
    }
    _cairo_output_stream_printf (surface->stream,
				 "%s setcolorspace\n"
				 "<<\n"
				 "  /ImageType 1\n"
				 "  /Width %d\n"
				 "  /Height %d\n"
				 "  /BitsPerComponent %d\n"
				 "  /Interpolate %s\n"
				 "  /Decode [ %s ]\n",
				 colorspace,
				 info.width,
				 info.height,
				 info.bits_per_component,
				 get_interpolate (params->filter),
                                 decode);
    if (surface->paint_proc) {
	_cairo_output_stream_printf (surface->stream,
				     "  /DataSource { cairo_data_source } /DCTDecode filter\n");
    } else {
	_cairo_output_stream_printf (surface->stream,
				     "  /DataSource cairo_ascii85_file /DCTDecode filter\n");
    }
    _cairo_output_stream_printf (surface->stream,
				 "  /ImageMatrix [ %d 0 0 %d 0 %d ]\n"
				 ">>\n"
				 "%simage\n",
				 info.width,
				 -info.height,
				 info.height,
				 surface->paint_proc ? "" : "cairo_");
    if (!surface->paint_proc) {
	/* Emit the image data as a base85-encoded string which will
	 * be used as the data source for the image operator. */
	status = _cairo_ps_surface_emit_base85_string (surface,
						       mime_data,
						       mime_data_length,
						       CAIRO_PS_COMPRESS_NONE,
						       FALSE);
    }
    return status;
}
static cairo_int_status_t
28
_cairo_ps_surface_emit_ccitt_image (cairo_ps_surface_t          *surface,
				    cairo_emit_surface_mode_t    mode,
				    cairo_emit_surface_params_t *params)
{
    cairo_status_t status;
    const unsigned char *ccitt_data;
    unsigned long ccitt_data_len;
    const unsigned char *ccitt_params_data;
    unsigned long ccitt_params_data_len;
    char *ccitt_params_string;
    cairo_ccitt_params_t ccitt_params;
28
    if (unlikely (params->src_surface->status))
	return params->src_surface->status;
28
    cairo_surface_get_mime_data (params->src_surface, CAIRO_MIME_TYPE_CCITT_FAX,
				 &ccitt_data, &ccitt_data_len);
28
    if (ccitt_data == NULL)
28
	return CAIRO_INT_STATUS_UNSUPPORTED;
    cairo_surface_get_mime_data (params->src_surface, CAIRO_MIME_TYPE_CCITT_FAX_PARAMS,
				 &ccitt_params_data, &ccitt_params_data_len);
    if (ccitt_params_data == NULL)
	return CAIRO_INT_STATUS_UNSUPPORTED;
    /* ensure params_string is null terminated */
    ccitt_params_string = _cairo_strndup ((const char *)ccitt_params_data, ccitt_params_data_len);
    if (unlikely (ccitt_params_string == NULL))
	return _cairo_surface_set_error (&surface->base, CAIRO_STATUS_NO_MEMORY);
    status = _cairo_tag_parse_ccitt_params (ccitt_params_string, &ccitt_params);
    if (unlikely(status))
	return status;
    free (ccitt_params_string);
    if (ccitt_params.columns <= 0 || ccitt_params.rows <= 0)
	return CAIRO_INT_STATUS_UNSUPPORTED;
    /* At this point we know emitting ccitt will succeed. */
    if (mode == CAIRO_EMIT_SURFACE_ANALYZE) {
	params->is_image = TRUE;
	params->approx_size = ccitt_data_len;
	return CAIRO_STATUS_SUCCESS;
    }
    if (surface->paint_proc) {
	/* Emit the image data as a base85-encoded string which will
	 * be used as the data source for the image operator later. */
	_cairo_output_stream_printf (surface->stream,
				     "/CairoData [\n");
	status = _cairo_ps_surface_emit_base85_string (surface,
						       ccitt_data,
						       ccitt_data_len,
						       CAIRO_PS_COMPRESS_NONE,
						       TRUE);
	if (unlikely (status))
	    return status;
	_cairo_output_stream_printf (surface->stream,
				     "] def\n");
	_cairo_output_stream_printf (surface->stream,
				     "/CairoDataIndex 0 def\n");
    } else {
	_cairo_output_stream_printf (surface->stream,
				     "/cairo_ascii85_file currentfile /ASCII85Decode filter def\n");
    }
    if (!params->stencil_mask) {
	_cairo_output_stream_printf (surface->stream,
				     "/DeviceGray setcolorspace\n");
    }
    _cairo_output_stream_printf (surface->stream,
				 "<<\n"
				 "  /ImageType 1\n"
				 "  /Width %d\n"
				 "  /Height %d\n"
				 "  /BitsPerComponent 1\n"
				 "  /Interpolate %s\n"
				 "  /Decode [ 0 1 ]\n",
				 ccitt_params.columns,
				 ccitt_params.rows,
				 get_interpolate (params->filter));
    if (surface->paint_proc) {
	_cairo_output_stream_printf (surface->stream,
				     "  /DataSource { cairo_data_source }\n");
    } else {
	_cairo_output_stream_printf (surface->stream,
				     "  /DataSource cairo_ascii85_file\n");
    }
    _cairo_output_stream_printf (surface->stream,
				 "  << /Columns %d /Rows %d /K %d\n",
				 ccitt_params.columns,
				 ccitt_params.rows,
				 ccitt_params.k);
    if (ccitt_params.end_of_line)
	_cairo_output_stream_printf (surface->stream, "     /EndOfLine true\n");
    if (ccitt_params.encoded_byte_align)
	_cairo_output_stream_printf (surface->stream, "     /EncodedByteAlign true\n");
    if (!ccitt_params.end_of_block)
	_cairo_output_stream_printf (surface->stream, "     /EndOfBlock false\n");
    if (ccitt_params.black_is_1)
	_cairo_output_stream_printf (surface->stream, "     /BlackIs1 true\n");
    if (ccitt_params.damaged_rows_before_error > 0) {
	_cairo_output_stream_printf (surface->stream,
				     "     /DamagedRowsBeforeError %d\n",
				     ccitt_params.damaged_rows_before_error);
    }
    _cairo_output_stream_printf (surface->stream,
				 "  >> /CCITTFaxDecode filter\n");
    _cairo_output_stream_printf (surface->stream,
				 "  /ImageMatrix [ %d 0 0 %d 0 %d ]\n"
				 ">>\n"
				 "%s%s\n",
				 ccitt_params.columns,
				 -ccitt_params.rows,
				 ccitt_params.rows,
				 surface->paint_proc ? "" : "cairo_",
				 params->stencil_mask ? "imagemask" : "image");
    if (!surface->paint_proc) {
	/* Emit the image data as a base85-encoded string which will
	 * be used as the data source for the image operator. */
	status = _cairo_ps_surface_emit_base85_string (surface,
						       ccitt_data,
						       ccitt_data_len,
						       CAIRO_PS_COMPRESS_NONE,
						       FALSE);
    }
    return status;
}
/* The '|' character is not used in PS (including ASCII85).  We can
 * speed up the search by first searching for the first char before
 * comparing strings.
 */
#define SUBFILE_FILTER_EOD "|EOD|"
/* Count number of non overlapping occurrences of SUBFILE_FILTER_EOD in data. */
static int
count_eod_strings (const unsigned char *data, unsigned long data_len)
{
    const unsigned char *p = data;
    const unsigned char *end;
    int first_char, len, count;
    const char *eod_str = SUBFILE_FILTER_EOD;
    first_char = eod_str[0];
    len = strlen (eod_str);
    p = data;
    end = data + data_len - len + 1;
    count = 0;
    while (p < end) {
	p = memchr (p, first_char, end - p);
	if (!p)
	    break;
	if (memcmp (p, eod_str, len) == 0) {
	    count++;
	    p += len;
	}
    }
    return count;
}
static cairo_status_t
28
_cairo_ps_surface_emit_eps (cairo_ps_surface_t          *surface,
			    cairo_emit_surface_mode_t    mode,
			    cairo_emit_surface_params_t *params)
{
    cairo_status_t status;
28
    const unsigned char *eps_data = NULL;
    unsigned long eps_data_len;
28
    const unsigned char *eps_params_string = NULL;
    unsigned long eps_params_string_len;
28
    char *params_string = NULL;
    cairo_eps_params_t eps_params;
    cairo_matrix_t mat;
    double eps_width, eps_height;
28
    if (unlikely (params->src_surface->status))
	return params->src_surface->status;
    /* We only embed EPS with level 3 as we may use ReusableStreamDecode and we
     * don't know what level the EPS file requires. */
28
    if (surface->ps_level == CAIRO_PS_LEVEL_2)
	return CAIRO_INT_STATUS_UNSUPPORTED;
28
    cairo_surface_get_mime_data (params->src_surface, CAIRO_MIME_TYPE_EPS,
				 &eps_data, &eps_data_len);
28
    if (eps_data == NULL)
28
	return CAIRO_INT_STATUS_UNSUPPORTED;
    cairo_surface_get_mime_data (params->src_surface, CAIRO_MIME_TYPE_EPS_PARAMS,
				 &eps_params_string, &eps_params_string_len);
    if (eps_params_string == NULL)
	return CAIRO_INT_STATUS_UNSUPPORTED;
    /* ensure params_string is null terminated */
    params_string = _cairo_strndup ((const char *)eps_params_string, eps_params_string_len);
    if (unlikely (params_string == NULL))
	return _cairo_surface_set_error (&surface->base, CAIRO_STATUS_NO_MEMORY);
    status = _cairo_tag_parse_eps_params (params_string, &eps_params);
    if (unlikely(status))
	return status;
    /* At this point we know emitting EPS will succeed. */
    if (mode == CAIRO_EMIT_SURFACE_ANALYZE) {
	params->is_image = FALSE;
	params->approx_size = eps_data_len;
	surface->contains_eps = TRUE;
	/* Find number of occurrences of SUBFILE_FILTER_EOD in the EPS data.
	 * We will need it before emitting the data if a ReusableStream is used.
         */
	params->eod_count = count_eod_strings (eps_data, eps_data_len);
	return CAIRO_STATUS_SUCCESS;
    }
    surface->ps_level_used = CAIRO_PS_LEVEL_3;
    _cairo_output_stream_printf (surface->stream, "cairo_eps_begin\n");
    eps_width = eps_params.bbox.p2.x - eps_params.bbox.p1.x;
    eps_height = eps_params.bbox.p2.y - eps_params.bbox.p1.y;
    cairo_matrix_init_translate (&mat,
				 params->src_surface_extents->x,
				 params->src_surface_extents->y);
    cairo_matrix_scale (&mat,
			params->src_surface_extents->width/eps_width,
			params->src_surface_extents->height/eps_height);
    cairo_matrix_scale (&mat, 1, -1);
    cairo_matrix_translate (&mat, -eps_params.bbox.p1.x, -eps_params.bbox.p2.y);
    if (! _cairo_matrix_is_identity (&mat)) {
	_cairo_output_stream_printf (surface->stream, "[ ");
	_cairo_output_stream_print_matrix (surface->stream, &mat);
	_cairo_output_stream_printf (surface->stream, " ] concat\n");
    }
    _cairo_output_stream_printf (surface->stream,
				 "%f %f %f %f rectclip\n",
				 eps_params.bbox.p1.x,
				 eps_params.bbox.p1.y,
				 eps_width,
				 eps_height);
    _cairo_output_stream_printf (surface->stream,
				 "%%%%BeginDocument: Document%d\n",
				 params->src_surface->unique_id);
    _cairo_output_stream_write (surface->stream, eps_data, eps_data_len);
    _cairo_output_stream_printf (surface->stream, "%%%%EndDocument");
    _cairo_output_stream_printf (surface->stream, "\ncairo_eps_end\n");
    return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
8
_cairo_ps_surface_emit_recording_surface (cairo_ps_surface_t          *surface,
					  cairo_surface_t             *recording_surface,
					  unsigned int                 regions_id,
					  const cairo_rectangle_int_t *recording_extents,
					  cairo_bool_t                 subsurface)
{
    double old_width, old_height;
    cairo_rectangle_int_t old_surface_extents;
    cairo_bool_t old_surface_bounded;
    cairo_matrix_t old_cairo_to_ps;
    cairo_content_t old_content;
    cairo_surface_clipper_t old_clipper;
    cairo_int_status_t status;
8
    cairo_surface_t *free_me = NULL;
    unsigned int id;
    int i, recording_surf_stack_size;
    /* Prevent infinite recursion if the recording_surface references a recording
     * currently being emitted */
8
    recording_surf_stack_size = _cairo_array_num_elements (&surface->recording_surf_stack);
12
    for (i = 0; i < recording_surf_stack_size; i++) {
4
	_cairo_array_copy_element (&surface->recording_surf_stack, i, &id);
4
	if (id == recording_surface->unique_id)
	    return CAIRO_STATUS_SUCCESS;
    }
8
    id = recording_surface->unique_id;
8
    status = _cairo_array_append (&surface->recording_surf_stack, &id);
8
    if (unlikely (status))
	return status;
8
    if (_cairo_surface_is_snapshot (recording_surface))
8
	free_me = recording_surface = _cairo_surface_snapshot_get_target (recording_surface);
8
    old_content = surface->content;
8
    old_width = surface->width;
8
    old_height = surface->height;
8
    old_surface_extents = surface->surface_extents;
8
    old_surface_bounded = surface->surface_bounded;
8
    old_cairo_to_ps = surface->cairo_to_ps;
8
    old_clipper = surface->clipper;
8
    _cairo_surface_clipper_init (&surface->clipper,
				 _cairo_ps_surface_clipper_intersect_clip_path);
#if DEBUG_PS
    _cairo_output_stream_printf (surface->stream,
				 "%% _cairo_ps_surface_emit_recording_surface"
				 " x: %d, y: %d, w: %d, h: %d subsurface: %d\n",
				 recording_extents->x, recording_extents->y,
				 recording_extents->width, recording_extents->height,
				 subsurface);
#endif
8
    surface->width = recording_extents->width;
8
    surface->height = recording_extents->height;
8
    surface->surface_extents = *recording_extents;
8
    surface->current_pattern_is_solid_color = FALSE;
8
    _cairo_pdf_operators_reset (&surface->pdf_operators);
8
    cairo_matrix_init (&surface->cairo_to_ps, 1, 0, 0, 1, 0, 0);
8
    _cairo_pdf_operators_set_cairo_to_pdf_matrix (&surface->pdf_operators,
						  &surface->cairo_to_ps);
8
    _cairo_output_stream_printf (surface->stream, "  q\n");
8
    if (recording_surface->content == CAIRO_CONTENT_COLOR) {
	surface->content = CAIRO_CONTENT_COLOR;
	_cairo_output_stream_printf (surface->stream,
				     "  0 g %d %d %d %d rectfill\n",
				     recording_extents->x,
				     recording_extents->y,
				     recording_extents->width,
				     recording_extents->height);
    }
8
    status = _cairo_recording_surface_replay_region (recording_surface,
						     regions_id,
						     subsurface ? recording_extents : NULL,
						     &surface->base,
						     CAIRO_RECORDING_REGION_NATIVE);
8
    assert (status != CAIRO_INT_STATUS_UNSUPPORTED);
8
    if (unlikely (status))
	return status;
8
    status = _cairo_pdf_operators_flush (&surface->pdf_operators);
8
    if (unlikely (status))
	return status;
8
    _cairo_output_stream_printf (surface->stream, "  Q\n");
8
    _cairo_surface_clipper_reset (&surface->clipper);
8
    surface->clipper = old_clipper;
8
    surface->content = old_content;
8
    surface->width = old_width;
8
    surface->height = old_height;
8
    surface->surface_extents = old_surface_extents;
8
    surface->surface_bounded = old_surface_bounded;
8
    surface->current_pattern_is_solid_color = FALSE;
8
    _cairo_pdf_operators_reset (&surface->pdf_operators);
8
    surface->cairo_to_ps = old_cairo_to_ps;
8
    _cairo_pdf_operators_set_cairo_to_pdf_matrix (&surface->pdf_operators,
						  &surface->cairo_to_ps);
8
    cairo_surface_destroy (free_me);
8
    _cairo_array_truncate (&surface->recording_surf_stack, recording_surf_stack_size);
8
    return status;
}
static void
36
_cairo_ps_surface_flatten_transparency (cairo_ps_surface_t	*surface,
					const cairo_color_t	*color,
					double			*red,
					double			*green,
					double			*blue)
{
36
    *red   = color->red;
36
    *green = color->green;
36
    *blue  = color->blue;
36
    if (! CAIRO_COLOR_IS_OPAQUE (color)) {
12
	*red   *= color->alpha;
12
	*green *= color->alpha;
12
	*blue  *= color->alpha;
12
	if (surface->content == CAIRO_CONTENT_COLOR_ALPHA) {
12
	    double one_minus_alpha = 1. - color->alpha;
12
	    *red   += one_minus_alpha;
12
	    *green += one_minus_alpha;
12
	    *blue  += one_minus_alpha;
	}
    }
36
}
static void
36
_cairo_ps_surface_emit_solid_pattern (cairo_ps_surface_t    *surface,
				      cairo_solid_pattern_t *pattern)
{
    double red, green, blue;
36
    _cairo_ps_surface_flatten_transparency (surface, &pattern->color, &red, &green, &blue);
36
    if (color_is_gray (red, green, blue))
6
	_cairo_output_stream_printf (surface->stream,
				     "%f g\n",
				     red);
    else
30
	_cairo_output_stream_printf (surface->stream,
				     "%f %f %f rg\n",
				     red, green, blue);
36
}
/*
 * PS Forms are used for sources that have CAIRO_MIME_TYPE_UNIQUE_ID. They will be
 * emitted once in the PS header and can be rendered with the 'execform' operator.
 *
 * This function tries adding the source the form hash table. If the source does not
 * have CAIRO_MIME_TYPE_UNIQUE_ID, CAIRO_INT_STATUS_UNSUPPORTED is returned.
 * @source: [in] the source for the form
 * @params: [in] source parameters
 * @test: [in] if TRUE, test if form will be used (excludes size check)
 * @ps_form [out] the new or existing entry int the hash table.
 *                image or recording.
 */
static cairo_int_status_t
28
_cairo_ps_surface_use_form (cairo_ps_surface_t           *surface,
			    cairo_emit_surface_params_t  *params,
			    cairo_bool_t                  test,
			    cairo_ps_form_t             **ps_form)
{
    cairo_ps_form_t source_key;
    cairo_ps_form_t *source_entry;
28
    unsigned char *unique_id = NULL;
28
    unsigned long unique_id_length = 0;
    cairo_status_t status;
    long max_size;
28
    if (params->op != CAIRO_OPERATOR_OVER || params->stencil_mask)
20
	return CAIRO_INT_STATUS_UNSUPPORTED;
8
    if (params->src_surface->backend->type == CAIRO_SURFACE_TYPE_SUBSURFACE)
	return CAIRO_INT_STATUS_UNSUPPORTED;
8
    cairo_surface_get_mime_data (params->src_surface, CAIRO_MIME_TYPE_UNIQUE_ID,
				 (const unsigned char **) &source_key.unique_id,
				 &source_key.unique_id_length);
8
    if (source_key.unique_id == NULL || source_key.unique_id_length == 0)
8
	return CAIRO_INT_STATUS_UNSUPPORTED;
    if (test)
	return CAIRO_STATUS_SUCCESS;
    source_key.filter = params->filter;
    _cairo_ps_form_init_key (&source_key);
    source_entry = _cairo_hash_table_lookup (surface->forms, &source_key.base);
    if (source_entry) {
	_cairo_rectangle_union (&source_entry->required_extents, params->src_op_extents);
	*ps_form = source_entry;
	return CAIRO_STATUS_SUCCESS;
    }
    if (surface->ps_level == CAIRO_PS_LEVEL_3)
	max_size = MAX_L3_FORM_DATA;
    else
	max_size = MAX_L2_FORM_DATA;
    /* Don't add any more Forms if we exceed the form memory limit */
    if (surface->total_form_size + params->approx_size > max_size)
	return CAIRO_INT_STATUS_UNSUPPORTED;
    surface->total_form_size += params->approx_size;
    unique_id = _cairo_malloc (source_key.unique_id_length);
    if (unique_id == NULL)
	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
    unique_id_length = source_key.unique_id_length;
    memcpy (unique_id, source_key.unique_id, unique_id_length);
    source_entry = _cairo_calloc (sizeof (cairo_ps_form_t));
    if (source_entry == NULL) {
	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	goto fail;
    }
    source_entry->unique_id_length = unique_id_length;
    source_entry->unique_id = unique_id;
    source_entry->id = surface->num_forms++;
    source_entry->src_surface = cairo_surface_reference (params->src_surface);
    source_entry->regions_id = params->regions_id;
    if (_cairo_surface_is_recording (source_entry->src_surface) && source_entry->regions_id != 0)
	_cairo_recording_surface_region_array_reference (source_entry->src_surface, source_entry->regions_id);
    source_entry->src_surface_extents = *params->src_surface_extents;
    source_entry->src_surface_bounded = params->src_surface_bounded;
    source_entry->required_extents = *params->src_op_extents;
    source_entry->filter = params->filter;
    source_entry->is_image = params->is_image;
    _cairo_ps_form_init_key (source_entry);
    status = _cairo_hash_table_insert (surface->forms, &source_entry->base);
    if (unlikely(status))
	goto fail;
    *ps_form = source_entry;
    return CAIRO_STATUS_SUCCESS;
  fail:
    free (unique_id);
    free (source_entry);
    return status;
}
static cairo_int_status_t
28
_cairo_ps_surface_emit_form (cairo_ps_surface_t          *surface,
			     cairo_emit_surface_params_t *params,
			     cairo_bool_t                 test)
{
28
    cairo_ps_form_t *ps_form = NULL;
    cairo_status_t status;
28
    status = _cairo_ps_surface_use_form (surface,
					 params,
					 test,
					 &ps_form);
28
    if (test || status)
28
	return status;
    /* _cairo_ps_form_emit will use Level 3 if permitted by ps_level */
    if (surface->ps_level == CAIRO_PS_LEVEL_3)
	surface->ps_level_used = CAIRO_PS_LEVEL_3;
    _cairo_output_stream_printf (surface->stream,
				 "/cairoform-%d /Form findresource execform\n",
				 ps_form->id);
    return CAIRO_STATUS_SUCCESS;
}
/* Emit a surface. This function has three modes.
 *
 * CAIRO_EMIT_SURFACE_ANALYZE: This will determine the surface type to
 * be emitted and approximate size. is_image is set to TRUE if the
 * emitted surface is an image surface (including mime images). This
 * is used by the caller to setup the correct CTM. approx_size is set
 * to the approximate size of the emitted surface and is used as an
 * input by the emit mode.
 *
 * CAIRO_EMIT_SURFACE_EMIT: Emits the surface will be emitted. The
 * approx_size and the surface unique id values are used to determine
 * if a Form should be used. If a form is used, the exec form
 * operation is emitted and the surface is added to the forms hash
 * table.
 *
 * CAIRO_EMIT_SURFACE_EMIT_FORM: Emits the form definition for the surface.
 *
 * Usage is:
 * 1) Setup input params and call with ANALYZE.
 * 2) Setup CTM for surface and call with EMIT using same params struct.
 * The EMIT_FORM mode is used when emitting the form definitions.
 */
static cairo_int_status_t
28
_cairo_ps_surface_emit_surface (cairo_ps_surface_t          *surface,
				cairo_emit_surface_mode_t    mode,
				cairo_emit_surface_params_t *params)
{
    cairo_int_status_t status;
28
    cairo_output_stream_t *old_stream = NULL;
    cairo_bool_t use_form;
    /* Try emitting as a form. Returns unsupported if the surface is
     * deemed unsuitable for a form. */
28
    use_form = FALSE;
28
    if (mode == CAIRO_EMIT_SURFACE_ANALYZE || mode == CAIRO_EMIT_SURFACE_EMIT) {
28
	status = _cairo_ps_surface_emit_form (surface,
					      params,
					      mode == CAIRO_EMIT_SURFACE_ANALYZE);
28
	use_form = (status == CAIRO_INT_STATUS_SUCCESS);
28
	if (status != CAIRO_INT_STATUS_SUCCESS && status != CAIRO_INT_STATUS_UNSUPPORTED)
	    return status;
28
	if (mode == CAIRO_EMIT_SURFACE_EMIT && status == CAIRO_INT_STATUS_SUCCESS)
	    return status;
    }
28
    status = _cairo_ps_surface_emit_eps (surface, mode, params);
28
    if (status == CAIRO_INT_STATUS_SUCCESS) {
	params->is_image = FALSE;
	goto surface_emitted;
    }
28
    if (status != CAIRO_INT_STATUS_UNSUPPORTED)
	return status;
28
    status = _cairo_ps_surface_emit_jpeg_image (surface, mode, params);
28
    if (status == CAIRO_INT_STATUS_SUCCESS) {
	params->is_image = TRUE;
	goto surface_emitted;
    }
28
    if (status != CAIRO_INT_STATUS_UNSUPPORTED)
	return status;
28
    status = _cairo_ps_surface_emit_ccitt_image (surface, mode, params);
28
    if (status == CAIRO_INT_STATUS_SUCCESS) {
	params->is_image = TRUE;
	goto surface_emitted;
    }
28
    if (status != CAIRO_INT_STATUS_UNSUPPORTED)
	return status;
28
    if (mode == CAIRO_EMIT_SURFACE_ANALYZE) {
	/* Find size of image or recording surface by emitting to a memory stream */
14
	status = _cairo_pdf_operators_flush (&surface->pdf_operators);
14
	if (unlikely (status))
	    return status;
14
	old_stream = surface->stream;
14
	surface->stream = _cairo_memory_stream_create ();
14
	_cairo_pdf_operators_set_stream (&surface->pdf_operators, surface->stream);
    }
28
    if (params->src_surface->type == CAIRO_SURFACE_TYPE_RECORDING) {
8
	params->is_image = FALSE;
8
	if (params->src_surface->backend->type == CAIRO_SURFACE_TYPE_SUBSURFACE) {
	    cairo_surface_subsurface_t *sub = (cairo_surface_subsurface_t *) params->src_surface;
	    status = _cairo_ps_surface_emit_recording_surface (surface,
							       sub->target,
							       params->regions_id,
							       &sub->extents,
							       TRUE);
	} else {
8
	    status = _cairo_ps_surface_emit_recording_surface (surface,
							       params->src_surface,
							       params->regions_id,
							       params->src_op_extents,
							       FALSE);
	}
    } else {
20
	params->is_image = TRUE;
20
	status = _cairo_ps_surface_emit_image (surface, mode, params);
    }
28
    if (mode == CAIRO_EMIT_SURFACE_ANALYZE) {
	unsigned char *data;
	unsigned long length;
14
	status = _cairo_pdf_operators_flush (&surface->pdf_operators);
14
	if (unlikely (status))
	    return status;
14
	status = _cairo_memory_stream_destroy (surface->stream, &data, &length);
14
	free (data);
14
	surface->stream = old_stream;
14
	if (unlikely (status))
	    return status;
14
	params->approx_size = length;
14
	_cairo_pdf_operators_set_stream (&surface->pdf_operators,
					 surface->stream);
    }
14
  surface_emitted:
28
    return status;
}
static void
_cairo_ps_form_emit (void *entry, void *closure)
{
    cairo_ps_form_t *form = entry;
    cairo_ps_surface_t *surface = closure;
    cairo_emit_surface_params_t params;
    cairo_int_status_t status;
    cairo_output_stream_t *old_stream;
    params.src_surface = form->src_surface;
    params.regions_id = form->regions_id;
    params.op = CAIRO_OPERATOR_OVER;
    params.src_surface_extents = &form->src_surface_extents;
    params.src_surface_bounded = form->src_surface_bounded;
    params.src_op_extents = &form->required_extents;
    params.filter = form->filter;
    params.stencil_mask = FALSE;
    params.is_image = form->is_image;
    params.approx_size = 0;
    params.eod_count = 0;
    _cairo_output_stream_printf (surface->final_stream,
				 "%%%%BeginResource: form cairoform-%d\n",
				 form->id);
    _cairo_output_stream_printf (surface->final_stream,
				 "/cairo_paint_form-%d",
				 form->id);
    if (surface->ps_level == CAIRO_PS_LEVEL_3) {
	surface->paint_proc = FALSE;
	_cairo_output_stream_printf (surface->final_stream,
				     "\n"
				     "currentfile\n"
				     "<< /Filter /SubFileDecode\n"
				     "   /DecodeParms << /EODString (%s) /EODCount 0 >>\n"
				     ">> /ReusableStreamDecode filter\n",
				     SUBFILE_FILTER_EOD);
    } else {
	surface->paint_proc = TRUE;
	_cairo_output_stream_printf (surface->final_stream,
				     " {\n");
    }
    _cairo_output_stream_printf (surface->final_stream,
				 "5 dict begin\n");
    old_stream = surface->stream;
    surface->stream = surface->final_stream;
    _cairo_pdf_operators_set_stream (&surface->pdf_operators, surface->stream);
    status = _cairo_ps_surface_emit_surface (surface,
					     CAIRO_EMIT_SURFACE_EMIT_FORM,
					     &params);
    status = _cairo_pdf_operators_flush (&surface->pdf_operators);
    surface->stream = old_stream;
    _cairo_pdf_operators_set_stream (&surface->pdf_operators, surface->stream);
    _cairo_output_stream_printf (surface->final_stream,
				 "end\n");
    if (surface->ps_level == CAIRO_PS_LEVEL_3) {
	_cairo_output_stream_printf (surface->final_stream,
				     "%s\n"
				     "def\n",
				     SUBFILE_FILTER_EOD);
    } else {
	_cairo_output_stream_printf (surface->final_stream,
				     "} bind def\n");
    }
    _cairo_output_stream_printf (surface->final_stream,
				 "\n"
				 "/cairoform-%d\n"
				 "<<\n"
				 "  /FormType 1\n",
				 form->id);
    if (form->is_image) {
	_cairo_output_stream_printf (surface->final_stream,
				     "  /BBox [ 0 0 1 1 ]\n");
    } else {
	_cairo_output_stream_printf (surface->final_stream,
				     "  /BBox [ %d %d %d %d ]\n",
				     form->required_extents.x,
				     form->required_extents.y,
				     form->required_extents.x + form->required_extents.width,
				     form->required_extents.y + form->required_extents.height);
    }
    _cairo_output_stream_printf (surface->final_stream,
				 "  /Matrix [ 1 0 0 1 0 0 ]\n"
				 "  /PaintProc { pop cairo_paint_form-%d",
				 form->id);
    if (surface->ps_level == CAIRO_PS_LEVEL_3) {
	_cairo_output_stream_printf (surface->final_stream,
				     " dup 0 setfileposition cvx exec");
    }
    _cairo_output_stream_printf (surface->final_stream,
				 " } bind\n"
				 ">>\n"
				 "/Form defineresource pop\n");
    _cairo_output_stream_printf (surface->final_stream,
				 "%%%%EndResource\n");
    if (status)
	surface->base.status = status;
}
static void
14
_path_fixed_init_rectangle (cairo_path_fixed_t *path,
			    cairo_rectangle_int_t *rect)
{
    cairo_status_t status;
14
    _cairo_path_fixed_init (path);
14
    status = _cairo_path_fixed_move_to (path,
					_cairo_fixed_from_int (rect->x),
					_cairo_fixed_from_int (rect->y));
14
    assert (status == CAIRO_STATUS_SUCCESS);
14
    status = _cairo_path_fixed_rel_line_to (path,
					    _cairo_fixed_from_int (rect->width),
					    _cairo_fixed_from_int (0));
14
    assert (status == CAIRO_STATUS_SUCCESS);
14
    status = _cairo_path_fixed_rel_line_to (path,
					    _cairo_fixed_from_int (0),
					    _cairo_fixed_from_int (rect->height));
14
    assert (status == CAIRO_STATUS_SUCCESS);
28
    status = _cairo_path_fixed_rel_line_to (path,
14
					    _cairo_fixed_from_int (-rect->width),
					    _cairo_fixed_from_int (0));
14
    assert (status == CAIRO_STATUS_SUCCESS);
14
    status = _cairo_path_fixed_close_path (path);
14
    assert (status == CAIRO_STATUS_SUCCESS);
14
}
static cairo_status_t
14
_cairo_ps_surface_paint_surface (cairo_ps_surface_t     *surface,
				 const cairo_pattern_t  *pattern,
				 cairo_rectangle_int_t  *extents,
				 cairo_operator_t	 op,
				 cairo_bool_t            stencil_mask)
{
    cairo_rectangle_int_t src_surface_extents;
    cairo_bool_t src_surface_bounded;
    cairo_rectangle_int_t src_op_extents;
    cairo_surface_t *source_surface;
    double x_offset, y_offset;
    cairo_status_t status;
    cairo_matrix_t cairo_p2d, ps_p2d;
    cairo_path_fixed_t path;
    cairo_emit_surface_params_t params;
14
    cairo_image_surface_t *image = NULL;
14
    unsigned int region_id = 0;
14
    status = _cairo_pdf_operators_flush (&surface->pdf_operators);
14
    if (unlikely (status))
	return status;
14
    if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE) {
14
	cairo_surface_pattern_t *surface_pattern = (cairo_surface_pattern_t *) pattern;
14
	region_id = surface_pattern->region_array_id;
    }
14
    status = _cairo_ps_surface_acquire_source_surface_from_pattern (surface,
								    pattern,
								    extents,
								    &src_surface_extents,
								    &src_surface_bounded,
								    &src_op_extents,
								    &source_surface,
								    &x_offset,
								    &y_offset);
14
    if (unlikely (status))
	return status;
14
    if (pattern->extend == CAIRO_EXTEND_PAD &&
	pattern->type == CAIRO_PATTERN_TYPE_SURFACE &&
	((cairo_surface_pattern_t *)pattern)->surface->type == CAIRO_SURFACE_TYPE_IMAGE) {
	cairo_image_surface_t *img;
	img = (cairo_image_surface_t *) source_surface;
	status = _cairo_ps_surface_create_padded_image_from_image (surface,
								   img,
								   &pattern->matrix,
								   extents,
								   &image,
								   &src_surface_extents);
	if (unlikely (status))
	    goto release_source;
	x_offset = src_surface_extents.x;
	y_offset = src_surface_extents.y;
    }
14
    _path_fixed_init_rectangle (&path, extents);
14
    status = _cairo_pdf_operators_clip (&surface->pdf_operators,
					&path,
					CAIRO_FILL_RULE_WINDING);
14
    _cairo_path_fixed_fini (&path);
14
    if (unlikely (status))
	goto release_source;
14
    cairo_p2d = pattern->matrix;
14
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_FALLBACK) {
10
	double x_scale = cairo_p2d.xx;
10
	double y_scale = cairo_p2d.yy;
10
	_cairo_output_stream_printf (surface->stream,
				     "%% Fallback Image: x=%f y=%f w=%d h=%d ",
10
				     -cairo_p2d.x0/x_scale,
10
				     -cairo_p2d.y0/y_scale,
10
				     (int)(src_surface_extents.width/x_scale),
10
				     (int)(src_surface_extents.height/y_scale));
10
	if (x_scale == y_scale) {
10
	    _cairo_output_stream_printf (surface->stream,
					 "res=%fppi ",
					 x_scale*72);
	} else {
	    _cairo_output_stream_printf (surface->stream,
					 "res=%fx%fppi ",
					 x_scale*72,
					 y_scale*72);
	}
10
	_cairo_output_stream_printf (surface->stream,
				     "size=%ld\n",
10
				     (long)src_surface_extents.width * src_surface_extents.height * 3);
    } else {
4
	if (op == CAIRO_OPERATOR_SOURCE) {
	    _cairo_output_stream_printf (surface->stream,
					 "%d g %d %d %d %d rectfill\n",
					 surface->content == CAIRO_CONTENT_COLOR ? 0 : 1,
					 surface->surface_extents.x,
					 surface->surface_extents.y,
					 surface->surface_extents.width,
					 surface->surface_extents.height);
	}
    }
14
    status = cairo_matrix_invert (&cairo_p2d);
    /* cairo_pattern_set_matrix ensures the matrix is invertible */
14
    assert (status == CAIRO_STATUS_SUCCESS);
14
    ps_p2d = surface->cairo_to_ps;
14
    cairo_matrix_multiply (&ps_p2d, &cairo_p2d, &ps_p2d);
14
    cairo_matrix_translate (&ps_p2d, x_offset, y_offset);
14
    params.src_surface = image ? &image->base : source_surface;
14
    params.regions_id = image ? 0 : region_id;
14
    params.op = op;
14
    params.src_surface_extents = &src_surface_extents;
14
    params.src_surface_bounded = src_surface_bounded;
14
    params.src_op_extents = &src_op_extents;
14
    params.filter = pattern->filter;
14
    params.stencil_mask = stencil_mask;
14
    params.is_image = FALSE;
14
    params.approx_size = 0;
14
    status = _cairo_ps_surface_emit_surface (surface, CAIRO_EMIT_SURFACE_ANALYZE, &params);
14
    if (unlikely (status))
	goto release_source;
14
    if (params.is_image) {
10
	cairo_matrix_translate (&ps_p2d, 0.0, src_surface_extents.height);
10
	cairo_matrix_scale (&ps_p2d, 1.0, -1.0);
10
	cairo_matrix_scale (&ps_p2d, src_surface_extents.width, src_surface_extents.height);
    }
14
    if (! _cairo_matrix_is_identity (&ps_p2d)) {
12
	_cairo_output_stream_printf (surface->stream, "[ ");
12
	_cairo_output_stream_print_matrix (surface->stream, &ps_p2d);
12
	_cairo_output_stream_printf (surface->stream, " ] concat\n");
    }
14
    status = _cairo_ps_surface_emit_surface (surface, CAIRO_EMIT_SURFACE_EMIT, &params);
14
  release_source:
14
    if (image)
	cairo_surface_destroy (&image->base);
14
    _cairo_ps_surface_release_source_surface_from_pattern (surface, pattern, source_surface);
14
    return status;
}
static cairo_status_t
_cairo_ps_surface_emit_surface_pattern (cairo_ps_surface_t      *surface,
					cairo_pattern_t         *pattern,
					cairo_rectangle_int_t   *extents,
					cairo_operator_t	 op)
{
    cairo_status_t status;
    double xstep, ystep;
    cairo_rectangle_int_t pattern_extents;
    cairo_bool_t bounded;
    cairo_matrix_t cairo_p2d, ps_p2d;
    cairo_bool_t old_paint_proc;
    double x_offset, y_offset;
    cairo_surface_t *source_surface;
    cairo_image_surface_t *image = NULL;
    cairo_rectangle_int_t src_op_extents;
    cairo_emit_surface_params_t params;
    cairo_extend_t extend = cairo_pattern_get_extend (pattern);
    unsigned int region_id = 0;
    cairo_p2d = pattern->matrix;
    status = cairo_matrix_invert (&cairo_p2d);
    /* cairo_pattern_set_matrix ensures the matrix is invertible */
    assert (status == CAIRO_STATUS_SUCCESS);
    if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE) {
	cairo_surface_pattern_t *surface_pattern = (cairo_surface_pattern_t *) pattern;
	region_id = surface_pattern->region_array_id;
    }
    status = _cairo_ps_surface_acquire_source_surface_from_pattern (surface,
								    pattern,
								    extents,
								    &pattern_extents,
								    &bounded,
								    &src_op_extents,
								    &source_surface,
								    &x_offset, &y_offset);
    if (unlikely (status))
	return status;
    if (extend == CAIRO_EXTEND_PAD) {
	cairo_image_surface_t *img;
	assert (source_surface->type == CAIRO_SURFACE_TYPE_IMAGE);
	img = (cairo_image_surface_t *) source_surface;
	status = _cairo_ps_surface_create_padded_image_from_image (surface,
								   img,
								   &pattern->matrix,
								   extents,
								   &image,
								   &pattern_extents);
	if (unlikely (status))
	    goto release_source;
    }
    if (unlikely (status))
	goto release_source;
    if (!bounded)
    {
	extend = CAIRO_EXTEND_NONE;
	_cairo_rectangle_intersect (&pattern_extents, &src_op_extents);
    }
    switch (extend) {
    case CAIRO_EXTEND_PAD:
    case CAIRO_EXTEND_NONE:
    {
	/* In PS/PDF, (as far as I can tell), all patterns are
	 * repeating. So we support cairo's EXTEND_NONE semantics
	 * by setting the repeat step size to a size large enough
	 * to guarantee that no more than a single occurrence will
	 * be visible.
	 *
	 * First, map the surface extents into pattern space (since
	 * xstep and ystep are in pattern space).  Then use an upper
	 * bound on the length of the diagonal of the pattern image
	 * and the surface as repeat size.  This guarantees to never
	 * repeat visibly.
	 */
	double x1 = 0.0, y1 = 0.0;
	double x2 = surface->surface_extents.width;
	double y2 = surface->surface_extents.height;
	_cairo_matrix_transform_bounding_box (&pattern->matrix,
					      &x1, &y1, &x2, &y2,
					      NULL);
	/* Rather than computing precise bounds of the union, just
	 * add the surface extents unconditionally. We only
	 * required an answer that's large enough, we don't really
	 * care if it's not as tight as possible.*/
	xstep = ystep = ceil ((x2 - x1) + (y2 - y1) +
			      pattern_extents.width + pattern_extents.height);
	break;
    }
    case CAIRO_EXTEND_REPEAT:
	xstep = pattern_extents.width;
	ystep = pattern_extents.height;
	break;
    case CAIRO_EXTEND_REFLECT:
	xstep = pattern_extents.width*2;
	ystep = pattern_extents.height*2;
	break;
	/* All the rest (if any) should have been analyzed away, so these
	 * cases should be unreachable. */
    default:
	ASSERT_NOT_REACHED;
	xstep = 0;
	ystep = 0;
    }
    _cairo_output_stream_printf (surface->stream,
				 "/CairoPattern {\n"
				 "q %d %d %d %d rectclip\n",
				 pattern_extents.x, pattern_extents.y,
				 pattern_extents.width, pattern_extents.height);
    if (extend == CAIRO_EXTEND_REPEAT || extend == CAIRO_EXTEND_REFLECT)
	src_op_extents = pattern_extents;
    old_paint_proc = surface->paint_proc;
    surface->paint_proc = TRUE;
    params.src_surface = image ? &image->base : source_surface;
    params.regions_id = image ? 0 : region_id;
    params.op = op;
    params.src_surface_extents = &pattern_extents;
    params.src_surface_bounded = bounded;
    params.src_op_extents = &src_op_extents;
    params.filter = pattern->filter;
    params.stencil_mask = FALSE;
    params.is_image = FALSE;
    params.approx_size = 0;
    status = _cairo_ps_surface_emit_surface (surface, CAIRO_EMIT_SURFACE_ANALYZE, &params);
    if (unlikely (status))
	goto release_source;
    if (params.is_image) {
	_cairo_output_stream_printf (surface->stream,
				     "[ %d 0 0 %d 0 0 ] concat\n",
				     pattern_extents.width, pattern_extents.height);
    }
    if (op == CAIRO_OPERATOR_SOURCE) {
	_cairo_output_stream_printf (surface->stream,
				     "%d g %d %d %f %f rectfill\n",
				     surface->content == CAIRO_CONTENT_COLOR ? 0 : 1,
				     pattern_extents.x, pattern_extents.y,
				     xstep, ystep);
    }
    status = _cairo_ps_surface_emit_surface (surface, CAIRO_EMIT_SURFACE_EMIT, &params);
    if (unlikely (status))
	goto release_source;
    _cairo_output_stream_printf (surface->stream,
				 " Q } bind def\n");
    _cairo_output_stream_printf (surface->stream,
				 "<< /PatternType 1\n"
				 "   /PaintType 1\n"
				 "   /TilingType 1\n");
    _cairo_output_stream_printf (surface->stream,
				 "   /XStep %f /YStep %f\n",
				 xstep, ystep);
    if (extend == CAIRO_EXTEND_REFLECT) {
	cairo_matrix_t mat;
	_cairo_output_stream_printf (surface->stream,
				     "   /BBox [%d %d %d %d]\n"
				     "   /PaintProc {\n"
				     "      pop CairoPattern\n",
				     pattern_extents.x,
				     pattern_extents.y,
				     pattern_extents.x + pattern_extents.width*2,
				     pattern_extents.y + pattern_extents.height*2);
	cairo_matrix_init_translate (&mat, pattern_extents.x, pattern_extents.y);
	cairo_matrix_scale (&mat, -1, 1);
	cairo_matrix_translate (&mat, -2*pattern_extents.width, 0);
	cairo_matrix_translate (&mat, -pattern_extents.x, -pattern_extents.y);
	_cairo_output_stream_printf (surface->stream, "      q [");
	_cairo_output_stream_print_matrix (surface->stream, &mat);
	_cairo_output_stream_printf (surface->stream, "] concat CairoPattern Q\n");
	cairo_matrix_init_translate (&mat, pattern_extents.x, pattern_extents.y);
	cairo_matrix_scale (&mat, 1, -1);
	cairo_matrix_translate (&mat, 0, -2*pattern_extents.height);
	cairo_matrix_translate (&mat, -pattern_extents.x, -pattern_extents.y);
	_cairo_output_stream_printf (surface->stream, "      q [");
	_cairo_output_stream_print_matrix (surface->stream, &mat);
	_cairo_output_stream_printf (surface->stream, "] concat CairoPattern Q\n");
	cairo_matrix_init_translate (&mat, pattern_extents.x, pattern_extents.y);
	cairo_matrix_scale (&mat, -1, -1);
	cairo_matrix_translate (&mat, -2*pattern_extents.width, -2*pattern_extents.height);
	cairo_matrix_translate (&mat, -pattern_extents.x, -pattern_extents.y);
	_cairo_output_stream_printf (surface->stream, "      q [");
	_cairo_output_stream_print_matrix (surface->stream, &mat);
	_cairo_output_stream_printf (surface->stream, "] concat CairoPattern Q\n");
	_cairo_output_stream_printf (surface->stream, "   } bind\n");
    } else {
	if (op == CAIRO_OPERATOR_SOURCE) {
	    _cairo_output_stream_printf (surface->stream,
					 "   /BBox [0 0 %f %f]\n",
					 xstep, ystep);
	} else {
	    _cairo_output_stream_printf (surface->stream,
					 "   /BBox [%d %d %d %d]\n",
					 pattern_extents.x,
					 pattern_extents.y,
					 pattern_extents.x + pattern_extents.width,
					 pattern_extents.y + pattern_extents.height);
	}
	_cairo_output_stream_printf (surface->stream,
				     "   /PaintProc { pop CairoPattern }\n");
    }
    _cairo_output_stream_printf (surface->stream,
				 ">>\n");
    cairo_p2d = pattern->matrix;
    status = cairo_matrix_invert (&cairo_p2d);
    /* cairo_pattern_set_matrix ensures the matrix is invertible */
    assert (status == CAIRO_STATUS_SUCCESS);
    cairo_matrix_init_identity (&ps_p2d);
    cairo_matrix_multiply (&ps_p2d, &cairo_p2d, &ps_p2d);
    cairo_matrix_translate (&ps_p2d, x_offset, y_offset);
    if (((cairo_surface_pattern_t *)pattern)->surface->type != CAIRO_SURFACE_TYPE_RECORDING)
    {
	cairo_matrix_translate (&ps_p2d, 0.0, pattern_extents.height);
	cairo_matrix_scale (&ps_p2d, 1.0, -1.0);
    }
    _cairo_output_stream_printf (surface->stream, "[ ");
    _cairo_output_stream_print_matrix (surface->stream, &ps_p2d);
    _cairo_output_stream_printf (surface->stream,
				 " ]\n"
				 "makepattern setpattern\n");
    surface->paint_proc = old_paint_proc;
  release_source:
    if (image)
	cairo_surface_destroy (&image->base);
    _cairo_ps_surface_release_source_surface_from_pattern (surface, pattern, source_surface);
    return status;
}
typedef struct _cairo_ps_color_stop {
    double offset;
    double color[4];
} cairo_ps_color_stop_t;
static void
_cairo_ps_surface_emit_linear_colorgradient (cairo_ps_surface_t     *surface,
					     cairo_ps_color_stop_t  *stop1,
					     cairo_ps_color_stop_t  *stop2)
{
    _cairo_output_stream_printf (surface->stream,
				 "   << /FunctionType 2\n"
				 "      /Domain [ 0 1 ]\n"
				 "      /C0 [ %f %f %f ]\n"
				 "      /C1 [ %f %f %f ]\n"
				 "      /N 1\n"
				 "   >>\n",
				 stop1->color[0],
				 stop1->color[1],
				 stop1->color[2],
				 stop2->color[0],
				 stop2->color[1],
				 stop2->color[2]);
}
static void
_cairo_ps_surface_emit_stitched_colorgradient (cairo_ps_surface_t    *surface,
					       unsigned int 	      n_stops,
					       cairo_ps_color_stop_t  stops[])
{
    unsigned int i;
    _cairo_output_stream_printf (surface->stream,
				 "<< /FunctionType 3\n"
				 "   /Domain [ 0 1 ]\n"
				 "   /Functions [\n");
    for (i = 0; i < n_stops - 1; i++)
	_cairo_ps_surface_emit_linear_colorgradient (surface, &stops[i], &stops[i+1]);
    _cairo_output_stream_printf (surface->stream, "   ]\n");
    _cairo_output_stream_printf (surface->stream, "   /Bounds [ ");
    for (i = 1; i < n_stops-1; i++)
	_cairo_output_stream_printf (surface->stream, "%f ", stops[i].offset);
    _cairo_output_stream_printf (surface->stream, "]\n");
    _cairo_output_stream_printf (surface->stream, "   /Encode [ 1 1 %d { pop 0 1 } for ]\n",
				 n_stops - 1);
    _cairo_output_stream_printf (surface->stream, ">>\n");
}
static void
calc_gradient_color (cairo_ps_color_stop_t *new_stop,
		     cairo_ps_color_stop_t *stop1,
		     cairo_ps_color_stop_t *stop2)
{
    int i;
    double offset = stop1->offset / (stop1->offset + 1.0 - stop2->offset);
    for (i = 0; i < 4; i++)
	new_stop->color[i] = stop1->color[i] + offset*(stop2->color[i] - stop1->color[i]);
}
#define COLOR_STOP_EPSILON 1e-6
static cairo_status_t
_cairo_ps_surface_emit_pattern_stops (cairo_ps_surface_t       *surface,
				      cairo_gradient_pattern_t *pattern)
{
    cairo_ps_color_stop_t *allstops, *stops;
    unsigned int i, n_stops;
    allstops = _cairo_malloc_ab ((pattern->n_stops + 2), sizeof (cairo_ps_color_stop_t));
    if (unlikely (allstops == NULL))
	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
    stops = &allstops[1];
    n_stops = pattern->n_stops;
    for (i = 0; i < n_stops; i++) {
	cairo_gradient_stop_t *stop = &pattern->stops[i];
	stops[i].color[0] = stop->color.red;
	stops[i].color[1] = stop->color.green;
	stops[i].color[2] = stop->color.blue;
	stops[i].color[3] = stop->color.alpha;
	stops[i].offset = pattern->stops[i].offset;
    }
    if (pattern->base.extend == CAIRO_EXTEND_REPEAT ||
	pattern->base.extend == CAIRO_EXTEND_REFLECT)
    {
	if (stops[0].offset > COLOR_STOP_EPSILON) {
	    if (pattern->base.extend == CAIRO_EXTEND_REFLECT)
		memcpy (allstops, stops, sizeof (cairo_ps_color_stop_t));
	    else
		calc_gradient_color (&allstops[0], &stops[0], &stops[n_stops-1]);
	    stops = allstops;
	    n_stops++;
	}
	stops[0].offset = 0.0;
	if (stops[n_stops-1].offset < 1.0 - COLOR_STOP_EPSILON) {
	    if (pattern->base.extend == CAIRO_EXTEND_REFLECT) {
		memcpy (&stops[n_stops],
			&stops[n_stops - 1],
			sizeof (cairo_ps_color_stop_t));
	    } else {
		calc_gradient_color (&stops[n_stops], &stops[0], &stops[n_stops-1]);
	    }
	    n_stops++;
	}
	stops[n_stops-1].offset = 1.0;
    }
    for (i = 0; i < n_stops; i++) {
	double red, green, blue;
	cairo_color_t color;
	_cairo_color_init_rgba (&color,
				stops[i].color[0],
				stops[i].color[1],
				stops[i].color[2],
				stops[i].color[3]);
	_cairo_ps_surface_flatten_transparency (surface, &color,
						&red, &green, &blue);
	stops[i].color[0] = red;
	stops[i].color[1] = green;
	stops[i].color[2] = blue;
    }
    _cairo_output_stream_printf (surface->stream,
				 "/CairoFunction\n");
    if (stops[0].offset == stops[n_stops - 1].offset) {
	/*
	 * The first and the last stops have the same offset, but we
	 * don't want a function with an empty domain, because that
	 * would provoke underdefined behaviour from rasterisers.
	 * This can only happen with EXTEND_PAD, because EXTEND_NONE
	 * is optimised into a clear pattern in cairo-gstate, and
	 * REFLECT/REPEAT are always transformed to have the first
	 * stop at t=0 and the last stop at t=1.  Thus we want a step
	 * function going from the first color to the last one.
	 *
	 * This can be accomplished by stitching three functions:
	 *  - a constant first color function,
	 *  - a step from the first color to the last color (with empty domain)
	 *  - a constant last color function
	 */
	cairo_ps_color_stop_t pad_stops[4];
	assert (pattern->base.extend == CAIRO_EXTEND_PAD);
	pad_stops[0] = pad_stops[1] = stops[0];
	pad_stops[2] = pad_stops[3] = stops[n_stops - 1];
	pad_stops[0].offset = 0;
	pad_stops[3].offset = 1;
	_cairo_ps_surface_emit_stitched_colorgradient (surface, 4, pad_stops);
    } else if (n_stops == 2) {
	/* no need for stitched function */
	_cairo_ps_surface_emit_linear_colorgradient (surface, &stops[0], &stops[1]);
    } else {
	/* multiple stops: stitch. XXX possible optimization: regularly spaced
	 * stops do not require stitching. XXX */
	_cairo_ps_surface_emit_stitched_colorgradient (surface, n_stops, stops);
    }
    _cairo_output_stream_printf (surface->stream,
				 "def\n");
    free (allstops);
    return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_ps_surface_emit_repeating_function (cairo_ps_surface_t       *surface,
					   cairo_gradient_pattern_t *pattern,
					   int                       begin,
					   int                       end)
{
    _cairo_output_stream_printf (surface->stream,
				 "/CairoFunction\n"
				 "<< /FunctionType 3\n"
				 "   /Domain [ %d %d ]\n"
				 "   /Functions [ %d {CairoFunction} repeat ]\n"
				 "   /Bounds [ %d 1 %d {} for ]\n",
				 begin,
                                 end,
				 end - begin,
				 begin + 1,
				 end - 1);
    if (pattern->base.extend == CAIRO_EXTEND_REFLECT) {
	_cairo_output_stream_printf (surface->stream, "   /Encode [ %d 1 %d { 2 mod 0 eq {0 1} {1 0} ifelse } for ]\n",
				     begin,
				     end - 1);
    } else {
	_cairo_output_stream_printf (surface->stream, "   /Encode [ %d 1 %d { pop 0 1 } for ]\n",
				     begin,
				     end - 1);
    }
    _cairo_output_stream_printf (surface->stream, ">> def\n");
    return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_ps_surface_emit_gradient (cairo_ps_surface_t       *surface,
				 cairo_gradient_pattern_t *pattern,
				 cairo_bool_t              is_ps_pattern)
{
    cairo_matrix_t pat_to_ps;
    cairo_circle_double_t start, end;
    double domain[2];
    cairo_status_t status;
    assert (pattern->n_stops != 0);
    status = _cairo_ps_surface_emit_pattern_stops (surface, pattern);
    if (unlikely (status))
	return status;
    pat_to_ps = pattern->base.matrix;
    status = cairo_matrix_invert (&pat_to_ps);
    /* cairo_pattern_set_matrix ensures the matrix is invertible */
    assert (status == CAIRO_STATUS_SUCCESS);
    cairo_matrix_multiply (&pat_to_ps, &pat_to_ps, &surface->cairo_to_ps);
    if (pattern->base.extend == CAIRO_EXTEND_REPEAT ||
	pattern->base.extend == CAIRO_EXTEND_REFLECT)
    {
	double bounds_x1, bounds_x2, bounds_y1, bounds_y2;
	double x_scale, y_scale, tolerance;
	/* TODO: use tighter extents */
	bounds_x1 = 0;
	bounds_y1 = 0;
	bounds_x2 = surface->width;
	bounds_y2 = surface->height;
	_cairo_matrix_transform_bounding_box (&pattern->base.matrix,
					      &bounds_x1, &bounds_y1,
					      &bounds_x2, &bounds_y2,
					      NULL);
	x_scale = surface->base.x_resolution / surface->base.x_fallback_resolution;
	y_scale = surface->base.y_resolution / surface->base.y_fallback_resolution;
	tolerance = fabs (_cairo_matrix_compute_determinant (&pattern->base.matrix));
	tolerance /= _cairo_matrix_transformed_circle_major_axis (&pattern->base.matrix, 1);
	tolerance *= MIN (x_scale, y_scale);
	_cairo_gradient_pattern_box_to_parameter (pattern,
						  bounds_x1, bounds_y1,
						  bounds_x2, bounds_y2,
						  tolerance, domain);
    } else if (pattern->stops[0].offset == pattern->stops[pattern->n_stops - 1].offset) {
	/*
	 * If the first and the last stop offset are the same, then
	 * the color function is a step function.
	 * _cairo_ps_surface_emit_pattern_stops emits it as a stitched
	 * function no matter how many stops the pattern has.  The
	 * domain of the stitched function will be [0 1] in this case.
	 *
	 * This is done to avoid emitting degenerate gradients for
	 * EXTEND_PAD patterns having a step color function.
	 */
	domain[0] = 0.0;
	domain[1] = 1.0;
	assert (pattern->base.extend == CAIRO_EXTEND_PAD);
    } else {
	domain[0] = pattern->stops[0].offset;
	domain[1] = pattern->stops[pattern->n_stops - 1].offset;
    }
    /* PS requires the first and last stop to be the same as the
     * extreme coordinates. For repeating patterns this moves the
     * extreme coordinates out to the begin/end of the repeating
     * function. For non repeating patterns this may move the extreme
     * coordinates in if there are not stops at offset 0 and 1. */
    _cairo_gradient_pattern_interpolate (pattern, domain[0], &start);
    _cairo_gradient_pattern_interpolate (pattern, domain[1], &end);
    if (pattern->base.extend == CAIRO_EXTEND_REPEAT ||
	pattern->base.extend == CAIRO_EXTEND_REFLECT)
    {
	int repeat_begin, repeat_end;
	repeat_begin = floor (domain[0]);
	repeat_end = ceil (domain[1]);
	status = _cairo_ps_surface_emit_repeating_function (surface,
							    pattern,
							    repeat_begin,
							    repeat_end);
	if (unlikely (status))
	    return status;
    } else if (pattern->n_stops <= 2) {
	/* For EXTEND_NONE and EXTEND_PAD if there are only two stops a
	 * Type 2 function is used by itself without a stitching
	 * function. Type 2 functions always have the domain [0 1] */
	domain[0] = 0.0;
	domain[1] = 1.0;
    }
    if (is_ps_pattern) {
	_cairo_output_stream_printf (surface->stream,
				     "<< /PatternType 2\n"
				     "   /Shading\n");
    }
    if (pattern->base.type == CAIRO_PATTERN_TYPE_LINEAR) {
	_cairo_output_stream_printf (surface->stream,
				     "   << /ShadingType 2\n"
				     "      /ColorSpace /DeviceRGB\n"
				     "      /Coords [ %f %f %f %f ]\n",
				     start.center.x, start.center.y,
				     end.center.x, end.center.y);
    } else {
	_cairo_output_stream_printf (surface->stream,
				     "   << /ShadingType 3\n"
				     "      /ColorSpace /DeviceRGB\n"
				     "      /Coords [ %f %f %f %f %f %f ]\n",
				     start.center.x, start.center.y,
				     MAX (start.radius, 0),
				     end.center.x, end.center.y,
				     MAX (end.radius, 0));
    }
    if (pattern->base.extend != CAIRO_EXTEND_NONE) {
	_cairo_output_stream_printf (surface->stream,
                                     "      /Extend [ true true ]\n");
    } else {
	_cairo_output_stream_printf (surface->stream,
                                     "      /Extend [ false false ]\n");
    }
    if (domain[0] == 0.0 && domain[1] == 1.0) {
	_cairo_output_stream_printf (surface->stream,
				     "      /Function CairoFunction\n");
    } else {
	_cairo_output_stream_printf (surface->stream,
				     "      /Function <<\n"
				     "         /FunctionType 3\n"
				     "         /Domain [ 0 1 ]\n"
				     "         /Bounds [ ]\n"
				     "         /Encode [ %f %f ]\n"
				     "         /Functions [ CairoFunction ]\n"
				     "      >>\n",
				     domain[0], domain[1]);
    }
    _cairo_output_stream_printf (surface->stream,
				 "   >>\n");
    if (is_ps_pattern) {
	_cairo_output_stream_printf (surface->stream,
				     ">>\n"
				     "[ ");
    _cairo_output_stream_print_matrix (surface->stream, &pat_to_ps);
    _cairo_output_stream_printf (surface->stream, " ]\n"
				 "makepattern setpattern\n");
    } else {
	_cairo_output_stream_printf (surface->stream,
				     "shfill\n");
    }
    return status;
}
static cairo_status_t
_cairo_ps_surface_emit_mesh_pattern (cairo_ps_surface_t     *surface,
				     cairo_mesh_pattern_t   *pattern,
				     cairo_bool_t            is_ps_pattern)
{
    cairo_matrix_t pat_to_ps;
    cairo_status_t status;
    cairo_pdf_shading_t shading;
    int i;
    if (_cairo_array_num_elements (&pattern->patches) == 0)
        return CAIRO_INT_STATUS_NOTHING_TO_DO;
    pat_to_ps = pattern->base.matrix;
    status = cairo_matrix_invert (&pat_to_ps);
    /* cairo_pattern_set_matrix ensures the matrix is invertible */
    assert (status == CAIRO_STATUS_SUCCESS);
    cairo_matrix_multiply (&pat_to_ps, &pat_to_ps, &surface->cairo_to_ps);
    status = _cairo_pdf_shading_init_color (&shading, pattern);
    if (unlikely (status))
	return status;
    _cairo_output_stream_printf (surface->stream,
				 "currentfile\n"
				 "/ASCII85Decode filter /FlateDecode filter /ReusableStreamDecode filter\n");
    status = _cairo_ps_surface_emit_base85_string (surface,
						   shading.data,
						   shading.data_length,
						   CAIRO_PS_COMPRESS_DEFLATE,
						   FALSE);
    if (status)
	return status;
    _cairo_output_stream_printf (surface->stream,
				 "\n"
				 "/CairoData exch def\n");
    if (is_ps_pattern) {
	_cairo_output_stream_printf (surface->stream,
				     "<< /PatternType 2\n"
				     "   /Shading\n");
    }
    _cairo_output_stream_printf (surface->stream,
				 "   << /ShadingType %d\n"
				 "      /ColorSpace /DeviceRGB\n"
				 "      /DataSource CairoData\n"
				 "      /BitsPerCoordinate %d\n"
				 "      /BitsPerComponent %d\n"
				 "      /BitsPerFlag %d\n"
				 "      /Decode [",
				 shading.shading_type,
				 shading.bits_per_coordinate,
				 shading.bits_per_component,
				 shading.bits_per_flag);
    for (i = 0; i < shading.decode_array_length; i++)
	_cairo_output_stream_printf (surface->stream, "%f ", shading.decode_array[i]);
    _cairo_output_stream_printf (surface->stream,
				 "]\n"
				 "   >>\n");
    if (is_ps_pattern) {
	_cairo_output_stream_printf (surface->stream,
				     ">>\n"
				     "[ \n");
	_cairo_output_stream_print_matrix (surface->stream, &pat_to_ps);
	_cairo_output_stream_printf (surface->stream,
				     " ]\n"
				     "makepattern\n"
				     "setpattern\n");
    } else {
	_cairo_output_stream_printf (surface->stream, "shfill\n");
    }
    _cairo_output_stream_printf (surface->stream,
				 "currentdict /CairoData undef\n");
    _cairo_pdf_shading_fini (&shading);
    return status;
}
static cairo_status_t
36
_cairo_ps_surface_emit_pattern (cairo_ps_surface_t *surface,
				const cairo_pattern_t *pattern,
				cairo_rectangle_int_t *extents,
				cairo_operator_t       op)
{
    cairo_status_t status;
36
    if (pattern->type == CAIRO_PATTERN_TYPE_SOLID) {
36
	cairo_solid_pattern_t *solid = (cairo_solid_pattern_t *) pattern;
36
	if (surface->current_pattern_is_solid_color == FALSE ||
6
	    ! _cairo_color_equal (&surface->current_color, &solid->color))
	{
36
	    status = _cairo_pdf_operators_flush (&surface->pdf_operators);
36
	    if (unlikely (status))
		return status;
36
	    _cairo_ps_surface_emit_solid_pattern (surface, (cairo_solid_pattern_t *) pattern);
36
	    surface->current_pattern_is_solid_color = TRUE;
36
	    surface->current_color = solid->color;
	}
36
	return CAIRO_STATUS_SUCCESS;
    }
    surface->current_pattern_is_solid_color = FALSE;
    status = _cairo_pdf_operators_flush (&surface->pdf_operators);
    if (unlikely (status))
	    return status;
    switch (pattern->type) {
    case CAIRO_PATTERN_TYPE_SOLID:
	_cairo_ps_surface_emit_solid_pattern (surface, (cairo_solid_pattern_t *) pattern);
	break;
    case CAIRO_PATTERN_TYPE_SURFACE:
    case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
	status = _cairo_ps_surface_emit_surface_pattern (surface,
							 (cairo_pattern_t *)pattern,
							 extents,
							 op);
	if (unlikely (status))
	    return status;
	break;
    case CAIRO_PATTERN_TYPE_LINEAR:
    case CAIRO_PATTERN_TYPE_RADIAL:
	status = _cairo_ps_surface_emit_gradient (surface,
						  (cairo_gradient_pattern_t *) pattern,
						  TRUE);
	if (unlikely (status))
	    return status;
	break;
    case CAIRO_PATTERN_TYPE_MESH:
	status = _cairo_ps_surface_emit_mesh_pattern (surface,
						      (cairo_mesh_pattern_t *) pattern,
						      TRUE);
	if (unlikely (status))
	    return status;
	break;
    }
    return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_ps_surface_paint_gradient (cairo_ps_surface_t          *surface,
				  const cairo_pattern_t       *source,
				  const cairo_rectangle_int_t *extents)
{
    cairo_matrix_t pat_to_ps;
    cairo_status_t status;
    pat_to_ps = source->matrix;
    status = cairo_matrix_invert (&pat_to_ps);
    /* cairo_pattern_set_matrix ensures the matrix is invertible */
    assert (status == CAIRO_STATUS_SUCCESS);
    cairo_matrix_multiply (&pat_to_ps, &pat_to_ps, &surface->cairo_to_ps);
    if (! _cairo_matrix_is_identity (&pat_to_ps)) {
	_cairo_output_stream_printf (surface->stream, "[");
	_cairo_output_stream_print_matrix (surface->stream, &pat_to_ps);
	_cairo_output_stream_printf (surface->stream, "] concat\n");
    }
    if (source->type == CAIRO_PATTERN_TYPE_MESH) {
	status = _cairo_ps_surface_emit_mesh_pattern (surface,
						      (cairo_mesh_pattern_t *)source,
						      FALSE);
	if (unlikely (status))
	    return status;
    } else {
	status = _cairo_ps_surface_emit_gradient (surface,
						  (cairo_gradient_pattern_t *)source,
						  FALSE);
	if (unlikely (status))
	    return status;
    }
    return status;
}
static cairo_status_t
14
_cairo_ps_surface_paint_pattern (cairo_ps_surface_t           *surface,
				 const cairo_pattern_t        *source,
				 cairo_rectangle_int_t        *extents,
				 cairo_operator_t              op,
				 cairo_bool_t                  stencil_mask)
{
14
    switch (source->type) {
14
    case CAIRO_PATTERN_TYPE_SURFACE:
    case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
14
       return _cairo_ps_surface_paint_surface (surface,
                                               source,
                                               extents,
                                               op,
					       stencil_mask);
    case CAIRO_PATTERN_TYPE_LINEAR:
    case CAIRO_PATTERN_TYPE_RADIAL:
    case CAIRO_PATTERN_TYPE_MESH:
	return _cairo_ps_surface_paint_gradient (surface,
						 source,
						 extents);
    case CAIRO_PATTERN_TYPE_SOLID:
    default:
       ASSERT_NOT_REACHED;
       return CAIRO_STATUS_SUCCESS;
    }
}
static cairo_bool_t
50
_can_paint_pattern (const cairo_pattern_t *pattern)
{
50
    switch (pattern->type) {
36
    case CAIRO_PATTERN_TYPE_SOLID:
36
	return FALSE;
14
    case CAIRO_PATTERN_TYPE_SURFACE:
    case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
14
	return (pattern->extend == CAIRO_EXTEND_NONE ||
		pattern->extend == CAIRO_EXTEND_PAD);
    case CAIRO_PATTERN_TYPE_LINEAR:
    case CAIRO_PATTERN_TYPE_RADIAL:
    case CAIRO_PATTERN_TYPE_MESH:
	return TRUE;
    default:
	ASSERT_NOT_REACHED;
	return FALSE;
    }
}
static cairo_bool_t
224
_cairo_ps_surface_get_extents (void		       *abstract_surface,
			       cairo_rectangle_int_t   *rectangle)
{
224
    cairo_ps_surface_t *surface = abstract_surface;
224
    if (surface->surface_bounded)
224
	*rectangle = surface->surface_extents;
224
    return surface->surface_bounded;
}
static void
4
_cairo_ps_surface_get_font_options (void                  *abstract_surface,
				    cairo_font_options_t  *options)
{
4
    _cairo_font_options_init_default (options);
4
    cairo_font_options_set_hint_style (options, CAIRO_HINT_STYLE_NONE);
4
    cairo_font_options_set_hint_metrics (options, CAIRO_HINT_METRICS_OFF);
4
    cairo_font_options_set_antialias (options, CAIRO_ANTIALIAS_GRAY);
4
    _cairo_font_options_set_round_glyph_positions (options, CAIRO_ROUND_GLYPH_POS_OFF);
4
}
static cairo_int_status_t
50
_cairo_ps_surface_set_clip (cairo_ps_surface_t *surface,
			    cairo_composite_rectangles_t *composite)
{
50
    cairo_clip_t *clip = composite->clip;
50
    if (_cairo_composite_rectangles_can_reduce_clip (composite, clip))
16
	clip = NULL;
50
    if (clip == NULL) {
16
	if (_cairo_composite_rectangles_can_reduce_clip (composite,
							 surface->clipper.clip))
16
	    return CAIRO_STATUS_SUCCESS;
    }
34
    return _cairo_surface_clipper_set_clip (&surface->clipper, clip);
}
static cairo_int_status_t
27
_cairo_ps_surface_paint (void			*abstract_surface,
			 cairo_operator_t	 op,
			 const cairo_pattern_t	*source,
			 const cairo_clip_t	*clip)
{
27
    cairo_ps_surface_t *surface = abstract_surface;
27
    cairo_output_stream_t *stream = surface->stream;
    cairo_composite_rectangles_t extents;
    cairo_status_t status;
27
    status = _cairo_composite_rectangles_init_for_paint (&extents,
							 &surface->base,
							 op, source, clip);
27
    if (unlikely (status))
4
	return status;
23
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
9
	status = _cairo_ps_surface_analyze_operation (surface, op, source, NULL, &extents.bounded);
9
	goto cleanup_composite;
    }
14
    assert (_cairo_ps_surface_operation_supported (surface, op, source, NULL, &extents.bounded));
#if DEBUG_PS
    _cairo_output_stream_printf (stream,
				 "%% _cairo_ps_surface_paint\n");
#endif
14
    status = _cairo_ps_surface_set_clip (surface, &extents);
14
    if (unlikely (status))
	goto cleanup_composite;
14
    if (_can_paint_pattern (source)) {
14
	status = _cairo_pdf_operators_flush (&surface->pdf_operators);
14
	if (unlikely (status))
	    goto cleanup_composite;
14
	_cairo_output_stream_printf (stream, "q\n");
14
	status = _cairo_ps_surface_paint_pattern (surface,
						  source,
						  &extents.bounded, op, FALSE);
14
	if (unlikely (status))
	    goto cleanup_composite;
14
	_cairo_output_stream_printf (stream, "Q\n");
    } else {
	status = _cairo_ps_surface_emit_pattern (surface, source, &extents.bounded, op);
	if (unlikely (status))
	    goto cleanup_composite;
	_cairo_output_stream_printf (stream, "%d %d %d %d rectfill\n",
				     surface->surface_extents.x,
				     surface->surface_extents.y,
				     surface->surface_extents.width,
				     surface->surface_extents.height);
    }
23
cleanup_composite:
23
    _cairo_composite_rectangles_fini (&extents);
23
    return status;
}
static cairo_int_status_t
_cairo_ps_surface_mask (void			*abstract_surface,
			cairo_operator_t	 op,
			const cairo_pattern_t	*source,
			const cairo_pattern_t	*mask,
			const cairo_clip_t	*clip)
{
    cairo_ps_surface_t *surface = abstract_surface;
    cairo_output_stream_t *stream = surface->stream;
    cairo_composite_rectangles_t extents;
    cairo_status_t status;
    status = _cairo_composite_rectangles_init_for_mask (&extents,
							&surface->base,
							op, source, mask, clip);
    if (unlikely (status))
	return status;
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
	status = _cairo_ps_surface_analyze_operation (surface, op, source, mask, &extents.bounded);
	goto cleanup_composite;
    }
    assert (_cairo_ps_surface_operation_supported (surface, op, source, mask, &extents.bounded));
#if DEBUG_PS
    _cairo_output_stream_printf (stream,
				 "%% _cairo_ps_surface_mask\n");
#endif
    status = _cairo_ps_surface_set_clip (surface, &extents);
    if (unlikely (status))
	goto cleanup_composite;
    status = _cairo_ps_surface_emit_pattern (surface, source, &extents.bounded, op);
    if (unlikely (status))
	goto cleanup_composite;
    _cairo_output_stream_printf (stream, "q\n");
    status = _cairo_ps_surface_paint_pattern (surface,
					      mask,
					      &extents.bounded, op, TRUE);
    if (unlikely (status))
	goto cleanup_composite;
    _cairo_output_stream_printf (stream, "Q\n");
cleanup_composite:
    _cairo_composite_rectangles_fini (&extents);
    return status;
}
static cairo_int_status_t
_cairo_ps_surface_stroke (void			*abstract_surface,
			  cairo_operator_t	 op,
			  const cairo_pattern_t	*source,
			  const cairo_path_fixed_t	*path,
			  const cairo_stroke_style_t	*style,
			  const cairo_matrix_t	*ctm,
			  const cairo_matrix_t	*ctm_inverse,
			  double		 tolerance,
			  cairo_antialias_t	 antialias,
			  const cairo_clip_t		*clip)
{
    cairo_ps_surface_t *surface = abstract_surface;
    cairo_composite_rectangles_t extents;
    cairo_int_status_t status;
    status = _cairo_composite_rectangles_init_for_stroke (&extents,
							  &surface->base,
							  op, source,
							  path, style, ctm,
							  clip);
    if (unlikely (status))
	return status;
    /* use the more accurate extents */
    {
	cairo_rectangle_int_t r;
	cairo_box_t b;
	status = _cairo_path_fixed_stroke_extents (path, style,
						   ctm, ctm_inverse,
						   tolerance,
						   &r);
	if (unlikely (status))
	    goto cleanup_composite;
	_cairo_box_from_rectangle (&b, &r);
	status = _cairo_composite_rectangles_intersect_mask_extents (&extents, &b);
	if (unlikely (status))
	    goto cleanup_composite;
    }
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
	status = _cairo_ps_surface_analyze_operation (surface, op, source, NULL, &extents.bounded);
	goto cleanup_composite;
    }
    assert (_cairo_ps_surface_operation_supported (surface, op, source, NULL, &extents.bounded));
#if DEBUG_PS
    _cairo_output_stream_printf (surface->stream,
				 "%% _cairo_ps_surface_stroke\n");
#endif
    status = _cairo_ps_surface_set_clip (surface, &extents);
    if (unlikely (status))
	goto cleanup_composite;
    status = _cairo_ps_surface_emit_pattern (surface, source, &extents.bounded, op);
    if (unlikely (status))
	goto cleanup_composite;
    status = _cairo_pdf_operators_stroke (&surface->pdf_operators,
					  path,
					  style,
					  ctm,
					  ctm_inverse);
cleanup_composite:
    _cairo_composite_rectangles_fini (&extents);
    return status;
}
static cairo_int_status_t
72
_cairo_ps_surface_fill (void		*abstract_surface,
			cairo_operator_t	 op,
			const cairo_pattern_t	*source,
			const cairo_path_fixed_t*path,
			cairo_fill_rule_t	 fill_rule,
			double			 tolerance,
			cairo_antialias_t	 antialias,
			const cairo_clip_t		*clip)
{
72
    cairo_ps_surface_t *surface = abstract_surface;
    cairo_composite_rectangles_t extents;
    cairo_int_status_t status;
72
    status = _cairo_composite_rectangles_init_for_fill (&extents,
							&surface->base,
							op, source, path,
							clip);
72
    if (unlikely (status))
	return status;
    /* use the more accurate extents */
    {
	cairo_rectangle_int_t r;
	cairo_box_t b;
72
	_cairo_path_fixed_fill_extents (path,
					fill_rule,
					tolerance,
					&r);
72
	_cairo_box_from_rectangle (&b, &r);
72
	status = _cairo_composite_rectangles_intersect_mask_extents (&extents, &b);
72
	if (unlikely (status))
	    goto cleanup_composite;
    }
72
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
36
	status = _cairo_ps_surface_analyze_operation (surface, op, source, NULL, &extents.bounded);
36
	goto cleanup_composite;
    }
36
    assert (_cairo_ps_surface_operation_supported (surface, op, source, NULL, &extents.bounded));
#if DEBUG_PS
    _cairo_output_stream_printf (surface->stream,
				 "%% _cairo_ps_surface_fill\n");
#endif
36
    status = _cairo_pdf_operators_flush (&surface->pdf_operators);
36
    if (unlikely (status))
	goto cleanup_composite;
36
    status = _cairo_ps_surface_set_clip (surface, &extents);
36
    if (unlikely (status))
	goto cleanup_composite;
36
    if (_can_paint_pattern (source)) {
	_cairo_output_stream_printf (surface->stream, "q\n");
	status =  _cairo_pdf_operators_clip (&surface->pdf_operators,
					     path,
					     fill_rule);
	if (unlikely (status))
	    goto cleanup_composite;
	status = _cairo_ps_surface_paint_pattern (surface,
						  source,
						  &extents.bounded, op, FALSE);
	if (unlikely (status))
	    goto cleanup_composite;
	_cairo_output_stream_printf (surface->stream, "Q\n");
	_cairo_pdf_operators_reset (&surface->pdf_operators);
    } else {
36
	status = _cairo_ps_surface_emit_pattern (surface, source, &extents.bounded, op);
36
	if (unlikely (status))
	    goto cleanup_composite;
36
	status = _cairo_pdf_operators_fill (&surface->pdf_operators,
					    path,
					    fill_rule);
    }
72
cleanup_composite:
72
    _cairo_composite_rectangles_fini (&extents);
72
    return status;
}
static cairo_bool_t
_cairo_ps_surface_has_show_text_glyphs	(void			*abstract_surface)
{
    return TRUE;
}
static cairo_int_status_t
_cairo_ps_surface_show_text_glyphs (void		       *abstract_surface,
				    cairo_operator_t	        op,
				    const cairo_pattern_t      *source,
				    const char                 *utf8,
				    int                         utf8_len,
				    cairo_glyph_t	       *glyphs,
				    int			        num_glyphs,
				    const cairo_text_cluster_t *clusters,
				    int                         num_clusters,
				    cairo_text_cluster_flags_t  cluster_flags,
				    cairo_scaled_font_t	       *scaled_font,
				    const cairo_clip_t	       *clip)
{
    cairo_ps_surface_t *surface = abstract_surface;
    cairo_composite_rectangles_t extents;
    cairo_bool_t overlap;
    cairo_status_t status;
    status = _cairo_composite_rectangles_init_for_glyphs (&extents,
							  &surface->base,
							  op, source,
							  scaled_font,
							  glyphs, num_glyphs,
							  clip,
							  &overlap);
    if (unlikely (status))
	return status;
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
	status = _cairo_ps_surface_analyze_operation (surface, op, source, NULL, &extents.bounded);
	goto cleanup_composite;
    }
    assert (_cairo_ps_surface_operation_supported (surface, op, source, NULL, &extents.bounded));
#if DEBUG_PS
    _cairo_output_stream_printf (surface->stream,
				 "%% _cairo_ps_surface_show_glyphs\n");
#endif
    status = _cairo_ps_surface_set_clip (surface, &extents);
    if (unlikely (status))
	goto cleanup_composite;
    status = _cairo_ps_surface_emit_pattern (surface, source, &extents.bounded, op);
    if (unlikely (status))
	goto cleanup_composite;
    status = _cairo_pdf_operators_show_text_glyphs (&surface->pdf_operators,
						    utf8, utf8_len,
						    glyphs, num_glyphs,
						    clusters, num_clusters,
						    cluster_flags,
						    scaled_font);
cleanup_composite:
    _cairo_composite_rectangles_fini (&extents);
    return status;
}
static const char **
_cairo_ps_surface_get_supported_mime_types (void		 *abstract_surface)
{
    return _cairo_ps_supported_mime_types;
}
static cairo_int_status_t
11
_cairo_ps_surface_set_paginated_mode (void			*abstract_surface,
				      cairo_paginated_mode_t	 paginated_mode)
{
11
    cairo_ps_surface_t *surface = abstract_surface;
    cairo_status_t status;
11
    surface->paginated_mode = paginated_mode;
11
    if (paginated_mode == CAIRO_PAGINATED_MODE_RENDER) {
5
	surface->surface_extents.x = 0;
5
	surface->surface_extents.y = 0;
5
	surface->surface_extents.width  = ceil (surface->width);
5
	surface->surface_extents.height = ceil (surface->height);
5
	if (surface->clipper.clip != NULL)
	{
	    status = _cairo_pdf_operators_flush (&surface->pdf_operators);
	    _cairo_output_stream_printf (surface->stream, "Q q\n");
	    _cairo_surface_clipper_reset (&surface->clipper);
	}
    }
11
    return CAIRO_STATUS_SUCCESS;
}
static cairo_int_status_t
5
_cairo_ps_surface_set_bounding_box (void		*abstract_surface,
				    cairo_box_t		*analysis_bbox)
{
5
    cairo_ps_surface_t *surface = abstract_surface;
    int i, num_comments;
    char **comments;
    cairo_bool_t has_page_media, has_page_bbox;
    const char *page_media;
    cairo_rectangle_int_t page_bbox;
    cairo_point_int_t bbox_p1, bbox_p2; /* in PS coordinates */
5
    _cairo_box_round_to_rectangle (analysis_bbox, &page_bbox);
    /* convert to PS coordinates */
5
    bbox_p1.x = page_bbox.x;
5
    bbox_p1.y = ceil(surface->height) - (page_bbox.y + page_bbox.height);
5
    bbox_p2.x = page_bbox.x + page_bbox.width;
5
    bbox_p2.y = ceil(surface->height) - page_bbox.y;
5
    if (surface->num_pages == 1) {
5
	surface->document_bbox_p1 = bbox_p1;
5
	surface->document_bbox_p2 = bbox_p2;
    } else {
	if (bbox_p1.x < surface->document_bbox_p1.x)
	    surface->document_bbox_p1.x = bbox_p1.x;
	if (bbox_p1.y < surface->document_bbox_p1.y)
	    surface->document_bbox_p1.y = bbox_p1.y;
	if (bbox_p2.x < surface->document_bbox_p2.x)
	    surface->document_bbox_p2.x = bbox_p2.x;
	if (bbox_p2.y < surface->document_bbox_p2.y)
	    surface->document_bbox_p2.y = bbox_p2.y;
    }
5
    _cairo_output_stream_printf (surface->stream,
				 "%%%%Page: %d %d\n",
				 surface->num_pages,
				 surface->num_pages);
5
    _cairo_output_stream_printf (surface->stream,
				 "%%%%BeginPageSetup\n");
5
    has_page_media = FALSE;
5
    has_page_bbox = FALSE;
5
    num_comments = _cairo_array_num_elements (&surface->dsc_page_setup_comments);
5
    comments = _cairo_array_index (&surface->dsc_page_setup_comments, 0);
5
    for (i = 0; i < num_comments; i++) {
	_cairo_output_stream_printf (surface->stream,
				     "%s\n", comments[i]);
	if (strncmp (comments[i], "%%PageMedia:", 11) == 0)
	    has_page_media = TRUE;
	if (strncmp (comments[i], "%%PageBoundingBox:", 18) == 0)
	    has_page_bbox = TRUE;
	free (comments[i]);
	comments[i] = NULL;
    }
5
    _cairo_array_truncate (&surface->dsc_page_setup_comments, 0);
5
    if (!has_page_media && !surface->eps) {
5
	page_media = _cairo_ps_surface_get_page_media (surface);
5
	if (unlikely (page_media == NULL))
	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5
	_cairo_output_stream_printf (surface->stream,
				     "%%%%PageMedia: %s\n",
				     page_media);
    }
5
    if (!has_page_bbox) {
5
	_cairo_output_stream_printf (surface->stream,
				     "%%%%PageBoundingBox: %d %d %d %d\n",
				     bbox_p1.x,
				     bbox_p1.y,
				     bbox_p2.x,
				     bbox_p2.y);
    }
5
    if (!surface->eps) {
5
	_cairo_output_stream_printf (surface->stream,
				     "%f %f cairo_set_page_size\n",
				     ceil(surface->width),
				     ceil(surface->height));
    }
5
    _cairo_output_stream_printf (surface->stream,
                                 "%%%%EndPageSetup\n"
				 "q %d %d %d %d rectclip\n"
                                 "1 0 0 -1 0 %f cm q\n",
				 bbox_p1.x,
				 bbox_p1.y,
5
				 bbox_p2.x - bbox_p1.x,
5
				 bbox_p2.y - bbox_p1.y,
				 ceil(surface->height));
5
    surface->current_pattern_is_solid_color = FALSE;
5
    _cairo_pdf_operators_reset (&surface->pdf_operators);
5
    return _cairo_output_stream_get_status (surface->stream);
}
static cairo_bool_t
5
_cairo_ps_surface_supports_fine_grained_fallbacks (void	    *abstract_surface)
{
5
    return TRUE;
}
static const cairo_surface_backend_t cairo_ps_surface_backend = {
    CAIRO_SURFACE_TYPE_PS,
    _cairo_ps_surface_finish,
    _cairo_default_context_create,
    NULL, /* create similar: handled by wrapper */
    NULL, /* create similar image */
    NULL, /* map to image */
    NULL, /* unmap image */
    _cairo_surface_default_source,
    NULL, /* acquire_source_image */
    NULL, /* release_source_image */
    NULL, /* snapshot */
    NULL, /* cairo_ps_surface_copy_page */
    _cairo_ps_surface_show_page,
    _cairo_ps_surface_get_extents,
    _cairo_ps_surface_get_font_options,
    NULL, /* flush */
    NULL, /* mark_dirty_rectangle */
    /* Here are the drawing functions */
    _cairo_ps_surface_paint, /* paint */
    _cairo_ps_surface_mask,
    _cairo_ps_surface_stroke,
    _cairo_ps_surface_fill,
    NULL, /* fill-stroke */
    NULL, /* show_glyphs */
    _cairo_ps_surface_has_show_text_glyphs,
    _cairo_ps_surface_show_text_glyphs,
    _cairo_ps_surface_get_supported_mime_types,
};
static const cairo_paginated_surface_backend_t cairo_ps_surface_paginated_backend = {
    _cairo_ps_surface_start_page,
    _cairo_ps_surface_set_paginated_mode,
    _cairo_ps_surface_set_bounding_box,
    NULL, /* _cairo_ps_surface_has_fallback_images, */
    _cairo_ps_surface_supports_fine_grained_fallbacks,
};