Fix bug in _cairo_gl_has_extension
[platform/core/graphics/cairo.git] / src / cairo-pdf-surface.c
1 /* -*- Mode: c; tab-width: 8; c-basic-offset: 4; indent-tabs-mode: t; -*- */
2 /* cairo - a vector graphics library with display and print output
3  *
4  * Copyright © 2004 Red Hat, Inc
5  * Copyright © 2006 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  *      Kristian Høgsberg <krh@redhat.com>
38  *      Carl Worth <cworth@cworth.org>
39  *      Adrian Johnson <ajohnson@redneon.com>
40  */
41
42 #define _BSD_SOURCE /* for snprintf() */
43 #include "cairoint.h"
44
45 #include "cairo-pdf.h"
46 #include "cairo-pdf-surface-private.h"
47 #include "cairo-pdf-operators-private.h"
48 #include "cairo-pdf-shading-private.h"
49
50 #include "cairo-array-private.h"
51 #include "cairo-analysis-surface-private.h"
52 #include "cairo-composite-rectangles-private.h"
53 #include "cairo-default-context-private.h"
54 #include "cairo-error-private.h"
55 #include "cairo-image-surface-inline.h"
56 #include "cairo-image-info-private.h"
57 #include "cairo-recording-surface-private.h"
58 #include "cairo-output-stream-private.h"
59 #include "cairo-paginated-private.h"
60 #include "cairo-scaled-font-subsets-private.h"
61 #include "cairo-surface-clipper-private.h"
62 #include "cairo-surface-snapshot-inline.h"
63 #include "cairo-surface-subsurface-private.h"
64 #include "cairo-type3-glyph-surface-private.h"
65
66 #include <time.h>
67 #include <zlib.h>
68
69 /* Issues:
70  *
71  * - We embed an image in the stream each time it's composited.  We
72  *   could add generation counters to surfaces and remember the stream
73  *   ID for a particular generation for a particular surface.
74  *
75  * - Backend specific meta data.
76  */
77
78 /*
79  * Page Structure of the Generated PDF:
80  *
81  * Each page requiring fallbacks images contains a knockout group at
82  * the top level. The first operation of the knockout group paints a
83  * group containing all the supported drawing operations. Fallback
84  * images (if any) are painted in the knockout group. This ensures
85  * that fallback images do not composite with any content under the
86  * fallback images.
87  *
88  * Streams:
89  *
90  * This PDF surface has three types of streams:
91  *  - PDF Stream
92  *  - Content Stream
93  *  - Group Stream
94  *
95  * Calling _cairo_output_stream_printf (surface->output, ...) will
96  * write to the currently open stream.
97  *
98  * PDF Stream:
99  *   A PDF Stream may be opened and closed with the following functions:
100  *     _cairo_pdf_surface_open stream ()
101  *     _cairo_pdf_surface_close_stream ()
102  *
103  *   PDF Streams are written directly to the PDF file. They are used for
104  *   fonts, images and patterns.
105  *
106  * Content Stream:
107  *   The Content Stream is opened and closed with the following functions:
108  *     _cairo_pdf_surface_open_content_stream ()
109  *     _cairo_pdf_surface_close_content_stream ()
110  *
111  *   The Content Stream contains the text and graphics operators.
112  *
113  * Group Stream:
114  *   A Group Stream may be opened and closed with the following functions:
115  *     _cairo_pdf_surface_open_group ()
116  *     _cairo_pdf_surface_close_group ()
117  *
118  *   A Group Stream is a Form XObject. It is used for short sequences
119  *   of operators. As the content is very short the group is stored in
120  *   memory until it is closed. This allows some optimization such as
121  *   including the Resource dictionary and stream length inside the
122  *   XObject instead of using an indirect object.
123  */
124
125 /**
126  * SECTION:cairo-pdf
127  * @Title: PDF Surfaces
128  * @Short_Description: Rendering PDF documents
129  * @See_Also: #cairo_surface_t
130  *
131  * The PDF surface is used to render cairo graphics to Adobe
132  * PDF files and is a multi-page vector surface backend.
133  *
134  * The following mime types are supported: %CAIRO_MIME_TYPE_JPEG,
135  * %CAIRO_MIME_TYPE_JP2, %CAIRO_MIME_TYPE_UNIQUE_ID,
136  * %CAIRO_MIME_TYPE_JBIG2, %CAIRO_MIME_TYPE_JBIG2_GLOBAL,
137  * %CAIRO_MIME_TYPE_JBIG2_GLOBAL_ID.
138  *
139  * JBIG2 data in PDF must be in the embedded format as descibed in
140  * ISO/IEC 11544. Image specific JBIG2 data must be in
141  * %CAIRO_MIME_TYPE_JBIG2.  Any global segments in the JBIG2 data
142  * (segments with page association field set to 0) must be in
143  * %CAIRO_MIME_TYPE_JBIG2_GLOBAL. The global data may be shared by
144  * multiple images. All images sharing the same global data must set
145  * %CAIRO_MIME_TYPE_JBIG2_GLOBAL_ID to a unique identifer. At least
146  * one of the images must provide the global data using
147  * %CAIRO_MIME_TYPE_JBIG2_GLOBAL. The global data will only be
148  * embedded once but shared by all JBIG2 images with the same
149  * %CAIRO_MIME_TYPE_JBIG2_GLOBAL_ID.
150  **/
151
152 static cairo_bool_t
153 _cairo_pdf_surface_get_extents (void                    *abstract_surface,
154                                 cairo_rectangle_int_t   *rectangle);
155
156 /**
157  * CAIRO_HAS_PDF_SURFACE:
158  *
159  * Defined if the PDF surface backend is available.
160  * This macro can be used to conditionally compile backend-specific code.
161  *
162  * Since: 1.2
163  **/
164
165 static const cairo_pdf_version_t _cairo_pdf_versions[] =
166 {
167     CAIRO_PDF_VERSION_1_4,
168     CAIRO_PDF_VERSION_1_5
169 };
170
171 #define CAIRO_PDF_VERSION_LAST ARRAY_LENGTH (_cairo_pdf_versions)
172
173 static const char * _cairo_pdf_version_strings[CAIRO_PDF_VERSION_LAST] =
174 {
175     "PDF 1.4",
176     "PDF 1.5"
177 };
178
179 static const char *_cairo_pdf_supported_mime_types[] =
180 {
181     CAIRO_MIME_TYPE_JPEG,
182     CAIRO_MIME_TYPE_JP2,
183     CAIRO_MIME_TYPE_UNIQUE_ID,
184     CAIRO_MIME_TYPE_JBIG2,
185     CAIRO_MIME_TYPE_JBIG2_GLOBAL,
186     CAIRO_MIME_TYPE_JBIG2_GLOBAL_ID,
187     NULL
188 };
189
190 typedef struct _cairo_pdf_object {
191     long offset;
192 } cairo_pdf_object_t;
193
194 typedef struct _cairo_pdf_font {
195     unsigned int font_id;
196     unsigned int subset_id;
197     cairo_pdf_resource_t subset_resource;
198 } cairo_pdf_font_t;
199
200 typedef struct _cairo_pdf_rgb_linear_function {
201     cairo_pdf_resource_t resource;
202     double               color1[3];
203     double               color2[3];
204 } cairo_pdf_rgb_linear_function_t;
205
206 typedef struct _cairo_pdf_alpha_linear_function {
207     cairo_pdf_resource_t resource;
208     double               alpha1;
209     double               alpha2;
210 } cairo_pdf_alpha_linear_function_t;
211
212 static cairo_pdf_resource_t
213 _cairo_pdf_surface_new_object (cairo_pdf_surface_t *surface);
214
215 static void
216 _cairo_pdf_surface_clear (cairo_pdf_surface_t *surface);
217
218 static void
219 _cairo_pdf_smask_group_destroy (cairo_pdf_smask_group_t *group);
220
221 static cairo_int_status_t
222 _cairo_pdf_surface_add_font (unsigned int        font_id,
223                              unsigned int        subset_id,
224                              void               *closure);
225
226 static void
227 _cairo_pdf_group_resources_init (cairo_pdf_group_resources_t *res);
228
229 static cairo_int_status_t
230 _cairo_pdf_surface_open_stream (cairo_pdf_surface_t     *surface,
231                                 cairo_pdf_resource_t    *resource,
232                                 cairo_bool_t             compressed,
233                                 const char              *fmt,
234                                 ...) CAIRO_PRINTF_FORMAT(4, 5);
235 static cairo_int_status_t
236 _cairo_pdf_surface_close_stream (cairo_pdf_surface_t    *surface);
237
238 static cairo_int_status_t
239 _cairo_pdf_surface_write_page (cairo_pdf_surface_t *surface);
240
241 static void
242 _cairo_pdf_surface_write_pages (cairo_pdf_surface_t *surface);
243
244 static cairo_pdf_resource_t
245 _cairo_pdf_surface_write_info (cairo_pdf_surface_t *surface);
246
247 static cairo_pdf_resource_t
248 _cairo_pdf_surface_write_catalog (cairo_pdf_surface_t *surface);
249
250 static long
251 _cairo_pdf_surface_write_xref (cairo_pdf_surface_t *surface);
252
253 static cairo_int_status_t
254 _cairo_pdf_surface_write_page (cairo_pdf_surface_t *surface);
255
256 static cairo_int_status_t
257 _cairo_pdf_surface_emit_font_subsets (cairo_pdf_surface_t *surface);
258
259 static cairo_bool_t
260 _cairo_pdf_source_surface_equal (const void *key_a, const void *key_b);
261
262 static const cairo_surface_backend_t cairo_pdf_surface_backend;
263 static const cairo_paginated_surface_backend_t cairo_pdf_surface_paginated_backend;
264
265 static cairo_pdf_resource_t
266 _cairo_pdf_surface_new_object (cairo_pdf_surface_t *surface)
267 {
268     cairo_pdf_resource_t resource;
269     cairo_int_status_t status;
270     cairo_pdf_object_t object;
271
272     object.offset = _cairo_output_stream_get_position (surface->output);
273
274     status = _cairo_array_append (&surface->objects, &object);
275     if (unlikely (status)) {
276         resource.id = 0;
277         return resource;
278     }
279
280     resource = surface->next_available_resource;
281     surface->next_available_resource.id++;
282
283     return resource;
284 }
285
286 static void
287 _cairo_pdf_surface_update_object (cairo_pdf_surface_t   *surface,
288                                   cairo_pdf_resource_t   resource)
289 {
290     cairo_pdf_object_t *object;
291
292     object = _cairo_array_index (&surface->objects, resource.id - 1);
293     if (object)
294         object->offset = _cairo_output_stream_get_position (surface->output);
295 }
296
297 static void
298 _cairo_pdf_surface_set_size_internal (cairo_pdf_surface_t *surface,
299                                       double              width,
300                                       double              height)
301 {
302     surface->width = width;
303     surface->height = height;
304     cairo_matrix_init (&surface->cairo_to_pdf, 1, 0, 0, -1, 0, height);
305     _cairo_pdf_operators_set_cairo_to_pdf_matrix (&surface->pdf_operators,
306                                                   &surface->cairo_to_pdf);
307 }
308
309 static cairo_bool_t
310 _path_covers_bbox (cairo_pdf_surface_t *surface,
311                    cairo_path_fixed_t *path)
312 {
313     cairo_box_t box;
314
315     return _cairo_path_fixed_is_box (path, &box) &&
316            box.p1.x <= 0 &&
317            box.p1.y <= 0 &&
318            box.p2.x >= _cairo_fixed_from_double (surface->width) &&
319            box.p2.y >= _cairo_fixed_from_double (surface->height);
320 }
321
322 static cairo_status_t
323 _cairo_pdf_surface_clipper_intersect_clip_path (cairo_surface_clipper_t *clipper,
324                                                 cairo_path_fixed_t      *path,
325                                                 cairo_fill_rule_t       fill_rule,
326                                                 double                  tolerance,
327                                                 cairo_antialias_t       antialias)
328 {
329     cairo_pdf_surface_t *surface = cairo_container_of (clipper,
330                                                        cairo_pdf_surface_t,
331                                                        clipper);
332     cairo_int_status_t status;
333
334     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
335     if (unlikely (status))
336         return status;
337
338     if (path == NULL) {
339         _cairo_output_stream_printf (surface->output, "Q q\n");
340
341         surface->current_pattern_is_solid_color = FALSE;
342         _cairo_pdf_operators_reset (&surface->pdf_operators);
343
344         return CAIRO_STATUS_SUCCESS;
345     }
346
347     if (_path_covers_bbox (surface, path))
348         return CAIRO_STATUS_SUCCESS;
349
350     return _cairo_pdf_operators_clip (&surface->pdf_operators, path, fill_rule);
351 }
352
353 static cairo_surface_t *
354 _cairo_pdf_surface_create_for_stream_internal (cairo_output_stream_t    *output,
355                                                double                    width,
356                                                double                    height)
357 {
358     cairo_pdf_surface_t *surface;
359     cairo_status_t status, status_ignored;
360
361     surface = malloc (sizeof (cairo_pdf_surface_t));
362     if (unlikely (surface == NULL)) {
363         /* destroy stream on behalf of caller */
364         status = _cairo_output_stream_destroy (output);
365         return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
366     }
367
368     _cairo_surface_init (&surface->base,
369                          &cairo_pdf_surface_backend,
370                          NULL, /* device */
371                          CAIRO_CONTENT_COLOR_ALPHA);
372
373     surface->output = output;
374     surface->width = width;
375     surface->height = height;
376     cairo_matrix_init (&surface->cairo_to_pdf, 1, 0, 0, -1, 0, height);
377
378     _cairo_array_init (&surface->objects, sizeof (cairo_pdf_object_t));
379     _cairo_array_init (&surface->pages, sizeof (cairo_pdf_resource_t));
380     _cairo_array_init (&surface->rgb_linear_functions, sizeof (cairo_pdf_rgb_linear_function_t));
381     _cairo_array_init (&surface->alpha_linear_functions, sizeof (cairo_pdf_alpha_linear_function_t));
382     _cairo_array_init (&surface->fonts, sizeof (cairo_pdf_font_t));
383     _cairo_array_init (&surface->smask_groups, sizeof (cairo_pdf_smask_group_t *));
384     _cairo_array_init (&surface->knockout_group, sizeof (cairo_pdf_resource_t));
385
386     _cairo_array_init (&surface->page_patterns, sizeof (cairo_pdf_pattern_t));
387     _cairo_array_init (&surface->page_surfaces, sizeof (cairo_pdf_source_surface_t));
388     _cairo_array_init (&surface->jbig2_global, sizeof (cairo_pdf_jbig2_global_t));
389     surface->all_surfaces = _cairo_hash_table_create (_cairo_pdf_source_surface_equal);
390     if (unlikely (surface->all_surfaces == NULL)) {
391         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
392         goto BAIL0;
393     }
394
395     _cairo_pdf_group_resources_init (&surface->resources);
396
397     surface->font_subsets = _cairo_scaled_font_subsets_create_composite ();
398     if (! surface->font_subsets) {
399         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
400         goto BAIL1;
401     }
402
403     _cairo_scaled_font_subsets_enable_latin_subset (surface->font_subsets, TRUE);
404
405     surface->next_available_resource.id = 1;
406     surface->pages_resource = _cairo_pdf_surface_new_object (surface);
407     if (surface->pages_resource.id == 0) {
408         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
409         goto BAIL2;
410     }
411
412     surface->pdf_version = CAIRO_PDF_VERSION_1_5;
413     surface->compress_content = TRUE;
414     surface->pdf_stream.active = FALSE;
415     surface->pdf_stream.old_output = NULL;
416     surface->group_stream.active = FALSE;
417     surface->group_stream.stream = NULL;
418     surface->group_stream.mem_stream = NULL;
419
420     surface->paginated_mode = CAIRO_PAGINATED_MODE_ANALYZE;
421
422     surface->force_fallbacks = FALSE;
423     surface->select_pattern_gstate_saved = FALSE;
424     surface->current_pattern_is_solid_color = FALSE;
425     surface->current_operator = CAIRO_OPERATOR_OVER;
426     surface->header_emitted = FALSE;
427
428     _cairo_surface_clipper_init (&surface->clipper,
429                                  _cairo_pdf_surface_clipper_intersect_clip_path);
430
431     _cairo_pdf_operators_init (&surface->pdf_operators,
432                                surface->output,
433                                &surface->cairo_to_pdf,
434                                surface->font_subsets,
435                                FALSE);
436     _cairo_pdf_operators_set_font_subsets_callback (&surface->pdf_operators,
437                                                     _cairo_pdf_surface_add_font,
438                                                     surface);
439     _cairo_pdf_operators_enable_actual_text(&surface->pdf_operators, TRUE);
440
441     surface->paginated_surface =  _cairo_paginated_surface_create (
442                                           &surface->base,
443                                           CAIRO_CONTENT_COLOR_ALPHA,
444                                           &cairo_pdf_surface_paginated_backend);
445
446     status = surface->paginated_surface->status;
447     if (status == CAIRO_STATUS_SUCCESS) {
448         /* paginated keeps the only reference to surface now, drop ours */
449         cairo_surface_destroy (&surface->base);
450         return surface->paginated_surface;
451     }
452
453 BAIL2:
454     _cairo_scaled_font_subsets_destroy (surface->font_subsets);
455 BAIL1:
456     _cairo_hash_table_destroy (surface->all_surfaces);
457 BAIL0:
458     _cairo_array_fini (&surface->objects);
459     free (surface);
460
461     /* destroy stream on behalf of caller */
462     status_ignored = _cairo_output_stream_destroy (output);
463
464     return _cairo_surface_create_in_error (status);
465 }
466
467 /**
468  * cairo_pdf_surface_create_for_stream:
469  * @write_func: a #cairo_write_func_t to accept the output data, may be %NULL
470  *              to indicate a no-op @write_func. With a no-op @write_func,
471  *              the surface may be queried or used as a source without
472  *              generating any temporary files.
473  * @closure: the closure argument for @write_func
474  * @width_in_points: width of the surface, in points (1 point == 1/72.0 inch)
475  * @height_in_points: height of the surface, in points (1 point == 1/72.0 inch)
476  *
477  * Creates a PDF surface of the specified size in points to be written
478  * incrementally to the stream represented by @write_func and @closure.
479  *
480  * Return value: a pointer to the newly created surface. The caller
481  * owns the surface and should call cairo_surface_destroy() when done
482  * with it.
483  *
484  * This function always returns a valid pointer, but it will return a
485  * pointer to a "nil" surface if an error such as out of memory
486  * occurs. You can use cairo_surface_status() to check for this.
487  *
488  * Since: 1.2
489  **/
490 cairo_surface_t *
491 cairo_pdf_surface_create_for_stream (cairo_write_func_t          write_func,
492                                      void                       *closure,
493                                      double                      width_in_points,
494                                      double                      height_in_points)
495 {
496     cairo_output_stream_t *output;
497
498     output = _cairo_output_stream_create (write_func, NULL, closure);
499     if (_cairo_output_stream_get_status (output))
500         return _cairo_surface_create_in_error (_cairo_output_stream_destroy (output));
501
502     return _cairo_pdf_surface_create_for_stream_internal (output,
503                                                           width_in_points,
504                                                           height_in_points);
505 }
506
507 /**
508  * cairo_pdf_surface_create:
509  * @filename: a filename for the PDF output (must be writable), %NULL may be
510  *            used to specify no output. This will generate a PDF surface that
511  *            may be queried and used as a source, without generating a
512  *            temporary file.
513  * @width_in_points: width of the surface, in points (1 point == 1/72.0 inch)
514  * @height_in_points: height of the surface, in points (1 point == 1/72.0 inch)
515  *
516  * Creates a PDF surface of the specified size in points to be written
517  * to @filename.
518  *
519  * Return value: a pointer to the newly created surface. The caller
520  * owns the surface and should call cairo_surface_destroy() when done
521  * with it.
522  *
523  * This function always returns a valid pointer, but it will return a
524  * pointer to a "nil" surface if an error such as out of memory
525  * occurs. You can use cairo_surface_status() to check for this.
526  *
527  * Since: 1.2
528  **/
529 cairo_surface_t *
530 cairo_pdf_surface_create (const char            *filename,
531                           double                 width_in_points,
532                           double                 height_in_points)
533 {
534     cairo_output_stream_t *output;
535
536     output = _cairo_output_stream_create_for_filename (filename);
537     if (_cairo_output_stream_get_status (output))
538         return _cairo_surface_create_in_error (_cairo_output_stream_destroy (output));
539
540     return _cairo_pdf_surface_create_for_stream_internal (output,
541                                                           width_in_points,
542                                                           height_in_points);
543 }
544
545 static cairo_bool_t
546 _cairo_surface_is_pdf (cairo_surface_t *surface)
547 {
548     return surface->backend == &cairo_pdf_surface_backend;
549 }
550
551 /* If the abstract_surface is a paginated surface, and that paginated
552  * surface's target is a pdf_surface, then set pdf_surface to that
553  * target. Otherwise return FALSE.
554  */
555 static cairo_bool_t
556 _extract_pdf_surface (cairo_surface_t            *surface,
557                       cairo_pdf_surface_t       **pdf_surface)
558 {
559     cairo_surface_t *target;
560     cairo_status_t status_ignored;
561
562     if (surface->status)
563         return FALSE;
564     if (surface->finished) {
565         status_ignored = _cairo_surface_set_error (surface,
566                                                    _cairo_error (CAIRO_STATUS_SURFACE_FINISHED));
567         return FALSE;
568     }
569
570     if (! _cairo_surface_is_paginated (surface)) {
571         status_ignored = _cairo_surface_set_error (surface,
572                                                    _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH));
573         return FALSE;
574     }
575
576     target = _cairo_paginated_surface_get_target (surface);
577     if (target->status) {
578         status_ignored = _cairo_surface_set_error (surface,
579                                                    target->status);
580         return FALSE;
581     }
582     if (target->finished) {
583         status_ignored = _cairo_surface_set_error (surface,
584                                                    _cairo_error (CAIRO_STATUS_SURFACE_FINISHED));
585         return FALSE;
586     }
587
588     if (! _cairo_surface_is_pdf (target)) {
589         status_ignored = _cairo_surface_set_error (surface,
590                                                    _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH));
591         return FALSE;
592     }
593
594     *pdf_surface = (cairo_pdf_surface_t *) target;
595     return TRUE;
596 }
597
598 /**
599  * cairo_pdf_surface_restrict_to_version:
600  * @surface: a PDF #cairo_surface_t
601  * @version: PDF version
602  *
603  * Restricts the generated PDF file to @version. See cairo_pdf_get_versions()
604  * for a list of available version values that can be used here.
605  *
606  * This function should only be called before any drawing operations
607  * have been performed on the given surface. The simplest way to do
608  * this is to call this function immediately after creating the
609  * surface.
610  *
611  * Since: 1.10
612  **/
613 void
614 cairo_pdf_surface_restrict_to_version (cairo_surface_t          *abstract_surface,
615                                        cairo_pdf_version_t       version)
616 {
617     cairo_pdf_surface_t *surface = NULL; /* hide compiler warning */
618
619     if (! _extract_pdf_surface (abstract_surface, &surface))
620         return;
621
622     if (version < CAIRO_PDF_VERSION_LAST)
623         surface->pdf_version = version;
624
625     _cairo_pdf_operators_enable_actual_text(&surface->pdf_operators,
626                                             version >= CAIRO_PDF_VERSION_1_5);
627 }
628
629 /**
630  * cairo_pdf_get_versions:
631  * @versions: supported version list
632  * @num_versions: list length
633  *
634  * Used to retrieve the list of supported versions. See
635  * cairo_pdf_surface_restrict_to_version().
636  *
637  * Since: 1.10
638  **/
639 void
640 cairo_pdf_get_versions (cairo_pdf_version_t const       **versions,
641                         int                              *num_versions)
642 {
643     if (versions != NULL)
644         *versions = _cairo_pdf_versions;
645
646     if (num_versions != NULL)
647         *num_versions = CAIRO_PDF_VERSION_LAST;
648 }
649
650 /**
651  * cairo_pdf_version_to_string:
652  * @version: a version id
653  *
654  * Get the string representation of the given @version id. This function
655  * will return %NULL if @version isn't valid. See cairo_pdf_get_versions()
656  * for a way to get the list of valid version ids.
657  *
658  * Return value: the string associated to given version.
659  *
660  * Since: 1.10
661  **/
662 const char *
663 cairo_pdf_version_to_string (cairo_pdf_version_t version)
664 {
665     if (version >= CAIRO_PDF_VERSION_LAST)
666         return NULL;
667
668     return _cairo_pdf_version_strings[version];
669 }
670
671 /**
672  * cairo_pdf_surface_set_size:
673  * @surface: a PDF #cairo_surface_t
674  * @width_in_points: new surface width, in points (1 point == 1/72.0 inch)
675  * @height_in_points: new surface height, in points (1 point == 1/72.0 inch)
676  *
677  * Changes the size of a PDF surface for the current (and
678  * subsequent) pages.
679  *
680  * This function should only be called before any drawing operations
681  * have been performed on the current page. The simplest way to do
682  * this is to call this function immediately after creating the
683  * surface or immediately after completing a page with either
684  * cairo_show_page() or cairo_copy_page().
685  *
686  * Since: 1.2
687  **/
688 void
689 cairo_pdf_surface_set_size (cairo_surface_t     *surface,
690                             double               width_in_points,
691                             double               height_in_points)
692 {
693     cairo_pdf_surface_t *pdf_surface = NULL; /* hide compiler warning */
694     cairo_status_t status;
695
696     if (! _extract_pdf_surface (surface, &pdf_surface))
697         return;
698
699     _cairo_pdf_surface_set_size_internal (pdf_surface,
700                                           width_in_points,
701                                           height_in_points);
702     status = _cairo_paginated_surface_set_size (pdf_surface->paginated_surface,
703                                                 width_in_points,
704                                                 height_in_points);
705     if (status)
706         status = _cairo_surface_set_error (surface, status);
707 }
708
709 static void
710 _cairo_pdf_surface_clear (cairo_pdf_surface_t *surface)
711 {
712     int i, size;
713     cairo_pdf_pattern_t *pattern;
714     cairo_pdf_source_surface_t *src_surface;
715     cairo_pdf_smask_group_t *group;
716
717     size = _cairo_array_num_elements (&surface->page_patterns);
718     for (i = 0; i < size; i++) {
719         pattern = (cairo_pdf_pattern_t *) _cairo_array_index (&surface->page_patterns, i);
720         if (pattern)
721             cairo_pattern_destroy (pattern->pattern);
722     }
723     _cairo_array_truncate (&surface->page_patterns, 0);
724
725     size = _cairo_array_num_elements (&surface->page_surfaces);
726     for (i = 0; i < size; i++) {
727         src_surface = (cairo_pdf_source_surface_t *) _cairo_array_index (&surface->page_surfaces, i);
728         if (src_surface)
729             cairo_surface_destroy (src_surface->surface);
730     }
731     _cairo_array_truncate (&surface->page_surfaces, 0);
732
733     size = _cairo_array_num_elements (&surface->smask_groups);
734     for (i = 0; i < size; i++) {
735         _cairo_array_copy_element (&surface->smask_groups, i, &group);
736         _cairo_pdf_smask_group_destroy (group);
737     }
738     _cairo_array_truncate (&surface->smask_groups, 0);
739     _cairo_array_truncate (&surface->knockout_group, 0);
740 }
741
742 static void
743 _cairo_pdf_group_resources_init (cairo_pdf_group_resources_t *res)
744 {
745     int i;
746
747     for (i = 0; i < CAIRO_NUM_OPERATORS; i++)
748         res->operators[i] = FALSE;
749
750     _cairo_array_init (&res->alphas, sizeof (double));
751     _cairo_array_init (&res->smasks, sizeof (cairo_pdf_resource_t));
752     _cairo_array_init (&res->patterns, sizeof (cairo_pdf_resource_t));
753     _cairo_array_init (&res->shadings, sizeof (cairo_pdf_resource_t));
754     _cairo_array_init (&res->xobjects, sizeof (cairo_pdf_resource_t));
755     _cairo_array_init (&res->fonts, sizeof (cairo_pdf_font_t));
756 }
757
758 static void
759 _cairo_pdf_group_resources_fini (cairo_pdf_group_resources_t *res)
760 {
761     _cairo_array_fini (&res->alphas);
762     _cairo_array_fini (&res->smasks);
763     _cairo_array_fini (&res->patterns);
764     _cairo_array_fini (&res->shadings);
765     _cairo_array_fini (&res->xobjects);
766     _cairo_array_fini (&res->fonts);
767 }
768
769 static void
770 _cairo_pdf_group_resources_clear (cairo_pdf_group_resources_t *res)
771 {
772     int i;
773
774     for (i = 0; i < CAIRO_NUM_OPERATORS; i++)
775         res->operators[i] = FALSE;
776
777     _cairo_array_truncate (&res->alphas, 0);
778     _cairo_array_truncate (&res->smasks, 0);
779     _cairo_array_truncate (&res->patterns, 0);
780     _cairo_array_truncate (&res->shadings, 0);
781     _cairo_array_truncate (&res->xobjects, 0);
782     _cairo_array_truncate (&res->fonts, 0);
783 }
784
785 static void
786 _cairo_pdf_surface_add_operator (cairo_pdf_surface_t *surface,
787                                  cairo_operator_t     op)
788 {
789     cairo_pdf_group_resources_t *res = &surface->resources;
790
791     res->operators[op] = TRUE;
792 }
793
794 static cairo_int_status_t
795 _cairo_pdf_surface_add_alpha (cairo_pdf_surface_t *surface,
796                               double               alpha,
797                               int                 *index)
798 {
799     int num_alphas, i;
800     double other;
801     cairo_int_status_t status;
802     cairo_pdf_group_resources_t *res = &surface->resources;
803
804     num_alphas = _cairo_array_num_elements (&res->alphas);
805     for (i = 0; i < num_alphas; i++) {
806         _cairo_array_copy_element (&res->alphas, i, &other);
807         if (alpha == other) {
808             *index = i;
809             return CAIRO_STATUS_SUCCESS;
810         }
811     }
812
813     status = _cairo_array_append (&res->alphas, &alpha);
814     if (unlikely (status))
815         return status;
816
817     *index = _cairo_array_num_elements (&res->alphas) - 1;
818
819     return CAIRO_STATUS_SUCCESS;
820 }
821
822 static cairo_int_status_t
823 _cairo_pdf_surface_add_smask (cairo_pdf_surface_t  *surface,
824                               cairo_pdf_resource_t  smask)
825 {
826     return _cairo_array_append (&(surface->resources.smasks), &smask);
827 }
828
829 static cairo_int_status_t
830 _cairo_pdf_surface_add_pattern (cairo_pdf_surface_t  *surface,
831                                 cairo_pdf_resource_t  pattern)
832 {
833     return _cairo_array_append (&(surface->resources.patterns), &pattern);
834 }
835
836 static cairo_int_status_t
837 _cairo_pdf_surface_add_shading (cairo_pdf_surface_t  *surface,
838                                 cairo_pdf_resource_t  shading)
839 {
840     return _cairo_array_append (&(surface->resources.shadings), &shading);
841 }
842
843
844 static cairo_int_status_t
845 _cairo_pdf_surface_add_xobject (cairo_pdf_surface_t  *surface,
846                                 cairo_pdf_resource_t  xobject)
847 {
848     return _cairo_array_append (&(surface->resources.xobjects), &xobject);
849 }
850
851 static cairo_int_status_t
852 _cairo_pdf_surface_add_font (unsigned int        font_id,
853                              unsigned int        subset_id,
854                              void               *closure)
855 {
856     cairo_pdf_surface_t *surface = closure;
857     cairo_pdf_font_t font;
858     int num_fonts, i;
859     cairo_int_status_t status;
860     cairo_pdf_group_resources_t *res = &surface->resources;
861
862     num_fonts = _cairo_array_num_elements (&res->fonts);
863     for (i = 0; i < num_fonts; i++) {
864         _cairo_array_copy_element (&res->fonts, i, &font);
865         if (font.font_id == font_id &&
866             font.subset_id == subset_id)
867             return CAIRO_STATUS_SUCCESS;
868     }
869
870     num_fonts = _cairo_array_num_elements (&surface->fonts);
871     for (i = 0; i < num_fonts; i++) {
872         _cairo_array_copy_element (&surface->fonts, i, &font);
873         if (font.font_id == font_id &&
874             font.subset_id == subset_id)
875             return _cairo_array_append (&res->fonts, &font);
876     }
877
878     font.font_id = font_id;
879     font.subset_id = subset_id;
880     font.subset_resource = _cairo_pdf_surface_new_object (surface);
881     if (font.subset_resource.id == 0)
882         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
883
884     status = _cairo_array_append (&surface->fonts, &font);
885     if (unlikely (status))
886         return status;
887
888     return _cairo_array_append (&res->fonts, &font);
889 }
890
891 static cairo_pdf_resource_t
892 _cairo_pdf_surface_get_font_resource (cairo_pdf_surface_t *surface,
893                                       unsigned int         font_id,
894                                       unsigned int         subset_id)
895 {
896     cairo_pdf_font_t font;
897     int num_fonts, i;
898
899     num_fonts = _cairo_array_num_elements (&surface->fonts);
900     for (i = 0; i < num_fonts; i++) {
901         _cairo_array_copy_element (&surface->fonts, i, &font);
902         if (font.font_id == font_id && font.subset_id == subset_id)
903             return font.subset_resource;
904     }
905
906     font.subset_resource.id = 0;
907     return font.subset_resource;
908 }
909
910 static const char *
911 _cairo_operator_to_pdf_blend_mode (cairo_operator_t op)
912 {
913     switch (op) {
914     /* The extend blend mode operators */
915     case CAIRO_OPERATOR_MULTIPLY:       return "Multiply";
916     case CAIRO_OPERATOR_SCREEN:         return "Screen";
917     case CAIRO_OPERATOR_OVERLAY:        return "Overlay";
918     case CAIRO_OPERATOR_DARKEN:         return "Darken";
919     case CAIRO_OPERATOR_LIGHTEN:        return "Lighten";
920     case CAIRO_OPERATOR_COLOR_DODGE:    return "ColorDodge";
921     case CAIRO_OPERATOR_COLOR_BURN:     return "ColorBurn";
922     case CAIRO_OPERATOR_HARD_LIGHT:     return "HardLight";
923     case CAIRO_OPERATOR_SOFT_LIGHT:     return "SoftLight";
924     case CAIRO_OPERATOR_DIFFERENCE:     return "Difference";
925     case CAIRO_OPERATOR_EXCLUSION:      return "Exclusion";
926     case CAIRO_OPERATOR_HSL_HUE:        return "Hue";
927     case CAIRO_OPERATOR_HSL_SATURATION: return "Saturation";
928     case CAIRO_OPERATOR_HSL_COLOR:      return "Color";
929     case CAIRO_OPERATOR_HSL_LUMINOSITY: return "Luminosity";
930
931     default:
932     /* The original Porter-Duff set */
933     case CAIRO_OPERATOR_CLEAR:
934     case CAIRO_OPERATOR_SOURCE:
935     case CAIRO_OPERATOR_OVER:
936     case CAIRO_OPERATOR_IN:
937     case CAIRO_OPERATOR_OUT:
938     case CAIRO_OPERATOR_ATOP:
939     case CAIRO_OPERATOR_DEST:
940     case CAIRO_OPERATOR_DEST_OVER:
941     case CAIRO_OPERATOR_DEST_IN:
942     case CAIRO_OPERATOR_DEST_OUT:
943     case CAIRO_OPERATOR_DEST_ATOP:
944     case CAIRO_OPERATOR_XOR:
945     case CAIRO_OPERATOR_ADD:
946     case CAIRO_OPERATOR_SATURATE:
947         return "Normal";
948     }
949 }
950
951 static void
952 _cairo_pdf_surface_emit_group_resources (cairo_pdf_surface_t         *surface,
953                                          cairo_pdf_group_resources_t *res)
954 {
955     int num_alphas, num_smasks, num_resources, i;
956     double alpha;
957     cairo_pdf_resource_t *smask, *pattern, *shading, *xobject;
958     cairo_pdf_font_t *font;
959
960     _cairo_output_stream_printf (surface->output, "<<\n");
961
962     num_alphas = _cairo_array_num_elements (&res->alphas);
963     num_smasks = _cairo_array_num_elements (&res->smasks);
964     if (num_alphas > 0 || num_smasks > 0) {
965         _cairo_output_stream_printf (surface->output,
966                                      "   /ExtGState <<\n");
967
968         for (i = 0; i < CAIRO_NUM_OPERATORS; i++) {
969             if (res->operators[i]) {
970                 _cairo_output_stream_printf (surface->output,
971                                              "      /b%d << /BM /%s >>\n",
972                                              i, _cairo_operator_to_pdf_blend_mode(i));
973             }
974         }
975
976         for (i = 0; i < num_alphas; i++) {
977             _cairo_array_copy_element (&res->alphas, i, &alpha);
978             _cairo_output_stream_printf (surface->output,
979                                          "      /a%d << /CA %f /ca %f >>\n",
980                                          i, alpha, alpha);
981         }
982
983         for (i = 0; i < num_smasks; i++) {
984             smask = _cairo_array_index (&res->smasks, i);
985             if (smask == NULL)
986                 return;
987             _cairo_output_stream_printf (surface->output,
988                                          "      /s%d %d 0 R\n",
989                                          smask->id, smask->id);
990         }
991
992         _cairo_output_stream_printf (surface->output,
993                                      "   >>\n");
994     }
995
996     num_resources = _cairo_array_num_elements (&res->patterns);
997     if (num_resources > 0) {
998         _cairo_output_stream_printf (surface->output,
999                                      "   /Pattern <<");
1000         for (i = 0; i < num_resources; i++) {
1001             pattern = _cairo_array_index (&res->patterns, i);
1002             if (pattern == NULL)
1003                 return;
1004             _cairo_output_stream_printf (surface->output,
1005                                          " /p%d %d 0 R",
1006                                          pattern->id, pattern->id);
1007         }
1008
1009         _cairo_output_stream_printf (surface->output,
1010                                      " >>\n");
1011     }
1012
1013     num_resources = _cairo_array_num_elements (&res->shadings);
1014     if (num_resources > 0) {
1015         _cairo_output_stream_printf (surface->output,
1016                                      "   /Shading <<");
1017         for (i = 0; i < num_resources; i++) {
1018             shading = _cairo_array_index (&res->shadings, i);
1019             if (shading == NULL)
1020                 return;
1021             _cairo_output_stream_printf (surface->output,
1022                                          " /sh%d %d 0 R",
1023                                          shading->id, shading->id);
1024         }
1025
1026         _cairo_output_stream_printf (surface->output,
1027                                      " >>\n");
1028     }
1029
1030     num_resources = _cairo_array_num_elements (&res->xobjects);
1031     if (num_resources > 0) {
1032         _cairo_output_stream_printf (surface->output,
1033                                      "   /XObject <<");
1034
1035         for (i = 0; i < num_resources; i++) {
1036             xobject = _cairo_array_index (&res->xobjects, i);
1037             if (xobject == NULL)
1038                 return;
1039             _cairo_output_stream_printf (surface->output,
1040                                          " /x%d %d 0 R",
1041                                          xobject->id, xobject->id);
1042         }
1043
1044         _cairo_output_stream_printf (surface->output,
1045                                      " >>\n");
1046     }
1047
1048     num_resources = _cairo_array_num_elements (&res->fonts);
1049     if (num_resources > 0) {
1050         _cairo_output_stream_printf (surface->output,"   /Font <<\n");
1051         for (i = 0; i < num_resources; i++) {
1052             font = _cairo_array_index (&res->fonts, i);
1053             if (font == NULL)
1054                 return;
1055
1056             _cairo_output_stream_printf (surface->output,
1057                                          "      /f-%d-%d %d 0 R\n",
1058                                          font->font_id,
1059                                          font->subset_id,
1060                                          font->subset_resource.id);
1061         }
1062         _cairo_output_stream_printf (surface->output, "   >>\n");
1063     }
1064
1065     _cairo_output_stream_printf (surface->output,
1066                                  ">>\n");
1067 }
1068
1069 static cairo_pdf_smask_group_t *
1070 _cairo_pdf_surface_create_smask_group (cairo_pdf_surface_t          *surface,
1071                                        const cairo_rectangle_int_t  *extents)
1072 {
1073     cairo_pdf_smask_group_t     *group;
1074
1075     group = calloc (1, sizeof (cairo_pdf_smask_group_t));
1076     if (unlikely (group == NULL)) {
1077         _cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
1078         return NULL;
1079     }
1080
1081     group->group_res = _cairo_pdf_surface_new_object (surface);
1082     if (group->group_res.id == 0) {
1083         _cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
1084         free (group);
1085         return NULL;
1086     }
1087     group->width = surface->width;
1088     group->height = surface->height;
1089     if (extents != NULL) {
1090         group->extents = *extents;
1091     } else {
1092         group->extents.x = 0;
1093         group->extents.y = 0;
1094         group->extents.width = surface->width;
1095         group->extents.height = surface->height;
1096     }
1097
1098     return group;
1099 }
1100
1101 static void
1102 _cairo_pdf_smask_group_destroy (cairo_pdf_smask_group_t *group)
1103 {
1104   if(group != NULL)
1105   {
1106     if (group->operation == PDF_FILL || group->operation == PDF_STROKE)
1107       _cairo_path_fixed_fini (&group->path);
1108     if (group->source)
1109       cairo_pattern_destroy (group->source);
1110     if (group->mask)
1111       cairo_pattern_destroy (group->mask);
1112     free (group->utf8);
1113     free (group->glyphs);
1114     free (group->clusters);
1115     if (group->scaled_font)
1116       cairo_scaled_font_destroy (group->scaled_font);
1117     free (group);
1118   }
1119 }
1120
1121 static cairo_int_status_t
1122 _cairo_pdf_surface_add_smask_group (cairo_pdf_surface_t     *surface,
1123                                     cairo_pdf_smask_group_t *group)
1124 {
1125     return _cairo_array_append (&surface->smask_groups, &group);
1126 }
1127
1128 static cairo_bool_t
1129 _cairo_pdf_source_surface_equal (const void *key_a, const void *key_b)
1130 {
1131     const cairo_pdf_source_surface_entry_t *a = key_a;
1132     const cairo_pdf_source_surface_entry_t *b = key_b;
1133
1134     if (a->interpolate != b->interpolate)
1135         return FALSE;
1136
1137     if (a->unique_id && b->unique_id && a->unique_id_length == b->unique_id_length)
1138         return (memcmp (a->unique_id, b->unique_id, a->unique_id_length) == 0);
1139
1140     return (a->id == b->id);
1141 }
1142
1143 static void
1144 _cairo_pdf_source_surface_init_key (cairo_pdf_source_surface_entry_t *key)
1145 {
1146     if (key->unique_id && key->unique_id_length > 0) {
1147         key->base.hash = _cairo_hash_bytes (_CAIRO_HASH_INIT_VALUE,
1148                                             key->unique_id, key->unique_id_length);
1149     } else {
1150         key->base.hash = key->id;
1151     }
1152 }
1153
1154 static cairo_int_status_t
1155 _cairo_pdf_surface_acquire_source_image_from_pattern (cairo_pdf_surface_t          *surface,
1156                                                       const cairo_pattern_t        *pattern,
1157                                                       cairo_image_surface_t       **image,
1158                                                       void                        **image_extra)
1159 {
1160     switch (pattern->type) {
1161     case CAIRO_PATTERN_TYPE_SURFACE: {
1162         cairo_surface_pattern_t *surf_pat = (cairo_surface_pattern_t *) pattern;
1163         return _cairo_surface_acquire_source_image (surf_pat->surface, image, image_extra);
1164     } break;
1165
1166     case CAIRO_PATTERN_TYPE_RASTER_SOURCE: {
1167         cairo_surface_t *surf;
1168         surf = _cairo_raster_source_pattern_acquire (pattern, &surface->base, NULL);
1169         if (!surf)
1170             return CAIRO_INT_STATUS_UNSUPPORTED;
1171         assert (_cairo_surface_is_image (surf));
1172         *image = (cairo_image_surface_t *) surf;
1173     } break;
1174
1175     case CAIRO_PATTERN_TYPE_SOLID:
1176     case CAIRO_PATTERN_TYPE_LINEAR:
1177     case CAIRO_PATTERN_TYPE_RADIAL:
1178     case CAIRO_PATTERN_TYPE_MESH:
1179     default:
1180         ASSERT_NOT_REACHED;
1181         break;
1182     }
1183
1184     return CAIRO_STATUS_SUCCESS;
1185 }
1186
1187 static void
1188 _cairo_pdf_surface_release_source_image_from_pattern (cairo_pdf_surface_t          *surface,
1189                                                       const cairo_pattern_t        *pattern,
1190                                                       cairo_image_surface_t        *image,
1191                                                       void                         *image_extra)
1192 {
1193     switch (pattern->type) {
1194     case CAIRO_PATTERN_TYPE_SURFACE: {
1195         cairo_surface_pattern_t *surf_pat = (cairo_surface_pattern_t *) pattern;
1196         _cairo_surface_release_source_image (surf_pat->surface, image, image_extra);
1197     } break;
1198
1199     case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
1200         _cairo_raster_source_pattern_release (pattern, &image->base);
1201         break;
1202
1203     case CAIRO_PATTERN_TYPE_SOLID:
1204     case CAIRO_PATTERN_TYPE_LINEAR:
1205     case CAIRO_PATTERN_TYPE_RADIAL:
1206     case CAIRO_PATTERN_TYPE_MESH:
1207     default:
1208
1209         ASSERT_NOT_REACHED;
1210         break;
1211     }
1212 }
1213
1214 static cairo_int_status_t
1215 _get_jbig2_image_info (cairo_surface_t           *source,
1216                        cairo_image_info_t        *info,
1217                        const unsigned char      **mime_data,
1218                        unsigned long             *mime_data_length)
1219 {
1220     cairo_surface_get_mime_data (source, CAIRO_MIME_TYPE_JBIG2,
1221                                  mime_data, mime_data_length);
1222     if (*mime_data == NULL)
1223         return CAIRO_INT_STATUS_UNSUPPORTED;
1224
1225     return _cairo_image_info_get_jbig2_info (info, *mime_data, *mime_data_length);
1226 }
1227
1228 static cairo_int_status_t
1229 _get_jpx_image_info (cairo_surface_t             *source,
1230                      cairo_image_info_t         *info,
1231                      const unsigned char        **mime_data,
1232                      unsigned long               *mime_data_length)
1233 {
1234     cairo_surface_get_mime_data (source, CAIRO_MIME_TYPE_JP2,
1235                                  mime_data, mime_data_length);
1236     if (*mime_data == NULL)
1237         return CAIRO_INT_STATUS_UNSUPPORTED;
1238
1239     return _cairo_image_info_get_jpx_info (info, *mime_data, *mime_data_length);
1240 }
1241
1242 static cairo_int_status_t
1243 _get_jpeg_image_info (cairo_surface_t            *source,
1244                       cairo_image_info_t         *info,
1245                       const unsigned char       **mime_data,
1246                       unsigned long              *mime_data_length)
1247 {
1248     cairo_surface_get_mime_data (source, CAIRO_MIME_TYPE_JPEG,
1249                                  mime_data, mime_data_length);
1250     if (*mime_data == NULL)
1251         return CAIRO_INT_STATUS_UNSUPPORTED;
1252
1253     return _cairo_image_info_get_jpeg_info (info, *mime_data, *mime_data_length);
1254 }
1255
1256 static cairo_int_status_t
1257 _get_source_surface_size (cairo_surface_t         *source,
1258                           int                     *width,
1259                           int                     *height,
1260                           cairo_rectangle_int_t   *extents)
1261 {
1262     cairo_int_status_t status;
1263     cairo_image_info_t info;
1264     const unsigned char *mime_data;
1265     unsigned long mime_data_length;
1266
1267     if (source->type == CAIRO_SURFACE_TYPE_RECORDING) {
1268         if (source->backend->type == CAIRO_SURFACE_TYPE_SUBSURFACE) {
1269              cairo_surface_subsurface_t *sub = (cairo_surface_subsurface_t *) source;
1270
1271              *extents = sub->extents;
1272              *width  = extents->width;
1273              *height = extents->height;
1274         } else {
1275             cairo_surface_t *free_me = NULL;
1276             cairo_rectangle_int_t surf_extents;
1277             cairo_box_t box;
1278             cairo_bool_t bounded;
1279
1280             if (_cairo_surface_is_snapshot (source))
1281                 free_me = source = _cairo_surface_snapshot_get_target (source);
1282
1283             status = _cairo_recording_surface_get_ink_bbox ((cairo_recording_surface_t *)source,
1284                                                             &box, NULL);
1285             if (unlikely (status)) {
1286                 cairo_surface_destroy (free_me);
1287                 return status;
1288             }
1289
1290             bounded = _cairo_surface_get_extents (source, &surf_extents);
1291             cairo_surface_destroy (free_me);
1292
1293             *width = surf_extents.width;
1294             *height = surf_extents.height;
1295
1296             _cairo_box_round_to_rectangle (&box, extents);
1297         }
1298
1299         return CAIRO_STATUS_SUCCESS;
1300     }
1301
1302     extents->x = 0;
1303     extents->y = 0;
1304
1305     status = _get_jbig2_image_info (source, &info, &mime_data, &mime_data_length);
1306     if (status != CAIRO_INT_STATUS_UNSUPPORTED) {
1307         *width = info.width;
1308         *height = info.height;
1309         extents->width = info.width;
1310         extents->height = info.height;
1311         return status;
1312     }
1313
1314     status = _get_jpx_image_info (source, &info, &mime_data, &mime_data_length);
1315     if (status != CAIRO_INT_STATUS_UNSUPPORTED) {
1316         *width = info.width;
1317         *height = info.height;
1318         extents->width = info.width;
1319         extents->height = info.height;
1320         return status;
1321     }
1322
1323     status = _get_jpeg_image_info (source, &info, &mime_data, &mime_data_length);
1324     if (status != CAIRO_INT_STATUS_UNSUPPORTED) {
1325         *width = info.width;
1326         *height = info.height;
1327         extents->width = info.width;
1328         extents->height = info.height;
1329         return status;
1330     }
1331
1332     if (! _cairo_surface_get_extents (source, extents))
1333         return CAIRO_INT_STATUS_UNSUPPORTED;
1334
1335     *width = extents->width;
1336     *height = extents->height;
1337
1338     return CAIRO_STATUS_SUCCESS;
1339 }
1340
1341 /**
1342  * _cairo_pdf_surface_add_source_surface:
1343  * @surface: the pdf surface
1344  * @source_surface: A #cairo_surface_t to use as the source surface
1345  * @source_pattern: A #cairo_pattern_t of type SURFACE or RASTER_SOURCE to use as the source
1346  * @op: the operator used to composite this source
1347  * @filter: filter type of the source pattern
1348  * @stencil_mask: if true, the surface will be written to the PDF as an /ImageMask
1349  * @smask: if true, only the alpha channel will be written (images only)
1350  * @extents: extents of the operation that is using this source
1351  * @smask_res: if not NULL, the image written will specify this resource as the smask for the image (images only)
1352  * @surface_res: return PDF resource number of the surface
1353  * @width: returns width of surface
1354  * @height: returns height of surface
1355  * @x_offset: x offset of surface
1356  * @t_offset: y offset of surface
1357  * @source_extents: returns extents of source (either ink extents or extents needed to cover @extents)
1358  *
1359  * Add surface or raster_source pattern to list of surfaces to be
1360  * written to the PDF file when the current page is finished. Returns
1361  * a PDF resource to reference the image. A hash table of all images
1362  * in the PDF files (keyed by CAIRO_MIME_TYPE_UNIQUE_ID or surface
1363  * unique_id) to ensure surfaces with the same id are only written
1364  * once to the PDF file.
1365  *
1366  * Only one of @source_pattern or @source_surface is to be
1367  * specified. Set the other to NULL.
1368  **/
1369 static cairo_int_status_t
1370 _cairo_pdf_surface_add_source_surface (cairo_pdf_surface_t          *surface,
1371                                        cairo_surface_t              *source_surface,
1372                                        const cairo_pattern_t        *source_pattern,
1373                                        cairo_operator_t              op,
1374                                        cairo_filter_t                filter,
1375                                        cairo_bool_t                  stencil_mask,
1376                                        cairo_bool_t                  smask,
1377                                        const cairo_rectangle_int_t  *extents,
1378                                        cairo_pdf_resource_t         *smask_res,
1379                                        cairo_pdf_resource_t         *surface_res,
1380                                        int                          *width,
1381                                        int                          *height,
1382                                        double                       *x_offset,
1383                                        double                       *y_offset,
1384                                        cairo_rectangle_int_t        *source_extents)
1385 {
1386     cairo_pdf_source_surface_t src_surface;
1387     cairo_pdf_source_surface_entry_t surface_key;
1388     cairo_pdf_source_surface_entry_t *surface_entry;
1389     cairo_int_status_t status;
1390     cairo_bool_t interpolate;
1391     unsigned char *unique_id = NULL;
1392     unsigned long unique_id_length = 0;
1393     cairo_image_surface_t *image;
1394     void *image_extra;
1395
1396     switch (filter) {
1397     default:
1398     case CAIRO_FILTER_GOOD:
1399     case CAIRO_FILTER_BEST:
1400     case CAIRO_FILTER_BILINEAR:
1401         interpolate = TRUE;
1402         break;
1403     case CAIRO_FILTER_FAST:
1404     case CAIRO_FILTER_NEAREST:
1405     case CAIRO_FILTER_GAUSSIAN:
1406         interpolate = FALSE;
1407         break;
1408     }
1409
1410     *x_offset = 0;
1411     *y_offset = 0;
1412     if (source_pattern) {
1413         if (source_pattern->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE) {
1414             status = _cairo_pdf_surface_acquire_source_image_from_pattern (surface, source_pattern,
1415                                                                            &image, &image_extra);
1416             if (unlikely (status))
1417                 return status;
1418             source_surface = &image->base;
1419             cairo_surface_get_device_offset (source_surface, x_offset, y_offset);
1420         } else {
1421             cairo_surface_pattern_t *surface_pattern = (cairo_surface_pattern_t *) source_pattern;
1422             source_surface = surface_pattern->surface;
1423         }
1424     }
1425
1426     surface_key.id  = source_surface->unique_id;
1427     surface_key.interpolate = interpolate;
1428     cairo_surface_get_mime_data (source_surface, CAIRO_MIME_TYPE_UNIQUE_ID,
1429                                  (const unsigned char **) &surface_key.unique_id,
1430                                  &surface_key.unique_id_length);
1431     _cairo_pdf_source_surface_init_key (&surface_key);
1432     surface_entry = _cairo_hash_table_lookup (surface->all_surfaces, &surface_key.base);
1433     if (surface_entry) {
1434         *surface_res = surface_entry->surface_res;
1435         *width = surface_entry->width;
1436         *height = surface_entry->height;
1437         *source_extents = surface_entry->extents;
1438         status = CAIRO_STATUS_SUCCESS;
1439     } else {
1440         status = _get_source_surface_size (source_surface,
1441                                            width,
1442                                            height,
1443                                            source_extents);
1444         if (unlikely(status))
1445             goto release_source;
1446
1447         if (surface_key.unique_id && surface_key.unique_id_length > 0) {
1448             unique_id = _cairo_malloc (surface_key.unique_id_length);
1449             if (unique_id == NULL) {
1450                 status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1451                 goto release_source;
1452             }
1453
1454             unique_id_length = surface_key.unique_id_length;
1455             memcpy (unique_id, surface_key.unique_id, unique_id_length);
1456         } else {
1457             unique_id = NULL;
1458             unique_id_length = 0;
1459         }
1460     }
1461
1462 release_source:
1463     if (source_pattern && source_pattern->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE)
1464         _cairo_pdf_surface_release_source_image_from_pattern (surface, source_pattern, image, image_extra);
1465
1466     if (status || surface_entry)
1467         return status;
1468
1469     surface_entry = malloc (sizeof (cairo_pdf_source_surface_entry_t));
1470     if (surface_entry == NULL) {
1471         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1472         goto fail1;
1473     }
1474
1475     surface_entry->id = surface_key.id;
1476     surface_entry->operator = op;
1477     surface_entry->interpolate = interpolate;
1478     surface_entry->stencil_mask = stencil_mask;
1479     surface_entry->smask = smask;
1480     surface_entry->unique_id_length = unique_id_length;
1481     surface_entry->unique_id = unique_id;
1482     surface_entry->width = *width;
1483     surface_entry->height = *height;
1484     surface_entry->extents = *source_extents;
1485     if (smask_res)
1486         surface_entry->smask_res = *smask_res;
1487     else
1488         surface_entry->smask_res.id = 0;
1489     _cairo_pdf_source_surface_init_key (surface_entry);
1490
1491     src_surface.hash_entry = surface_entry;
1492     if (source_pattern && source_pattern->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE) {
1493         src_surface.type = CAIRO_PATTERN_TYPE_RASTER_SOURCE;
1494         src_surface.surface = NULL;
1495         status = _cairo_pattern_create_copy (&src_surface.raster_pattern, source_pattern);
1496         if (unlikely (status))
1497             goto fail2;
1498
1499     } else {
1500         src_surface.type = CAIRO_PATTERN_TYPE_SURFACE;
1501         src_surface.surface = cairo_surface_reference (source_surface);
1502         src_surface.raster_pattern = NULL;
1503     }
1504
1505     surface_entry->surface_res = _cairo_pdf_surface_new_object (surface);
1506     if (surface_entry->surface_res.id == 0) {
1507         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1508         goto fail3;
1509     }
1510
1511     status = _cairo_array_append (&surface->page_surfaces, &src_surface);
1512     if (unlikely (status))
1513         goto fail3;
1514
1515     status = _cairo_hash_table_insert (surface->all_surfaces,
1516                                        &surface_entry->base);
1517     if (unlikely(status))
1518         goto fail3;
1519
1520     *surface_res = surface_entry->surface_res;
1521
1522     return status;
1523
1524 fail3:
1525     if (source_pattern && source_pattern->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE)
1526         cairo_pattern_destroy (src_surface.raster_pattern);
1527     else
1528         cairo_surface_destroy (src_surface.surface);
1529
1530 fail2:
1531     free (surface_entry);
1532
1533 fail1:
1534     free (unique_id);
1535
1536     return status;
1537 }
1538
1539 static cairo_int_status_t
1540 _cairo_pdf_surface_add_pdf_pattern_or_shading (cairo_pdf_surface_t         *surface,
1541                                                const cairo_pattern_t       *pattern,
1542                                                cairo_operator_t             op,
1543                                                const cairo_rectangle_int_t *extents,
1544                                                cairo_bool_t                 is_shading,
1545                                                cairo_pdf_resource_t        *pattern_res,
1546                                                cairo_pdf_resource_t        *gstate_res)
1547 {
1548     cairo_pdf_pattern_t pdf_pattern;
1549     cairo_int_status_t status;
1550
1551     pdf_pattern.is_shading = is_shading;
1552     pdf_pattern.operator = op;
1553
1554     /* Solid colors are emitted into the content stream */
1555     if (pattern->type == CAIRO_PATTERN_TYPE_SOLID) {
1556         pattern_res->id = 0;
1557         gstate_res->id = 0;
1558         return CAIRO_INT_STATUS_SUCCESS;
1559     }
1560
1561     status = _cairo_pattern_create_copy (&pdf_pattern.pattern, pattern);
1562     if (unlikely (status))
1563         return status;
1564
1565     pdf_pattern.pattern_res = _cairo_pdf_surface_new_object (surface);
1566     if (pdf_pattern.pattern_res.id == 0) {
1567         cairo_pattern_destroy (pdf_pattern.pattern);
1568         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1569     }
1570
1571     pdf_pattern.gstate_res.id = 0;
1572
1573     /* gradient patterns require an smask object to implement transparency */
1574     if (pattern->type == CAIRO_PATTERN_TYPE_LINEAR ||
1575         pattern->type == CAIRO_PATTERN_TYPE_RADIAL ||
1576         pattern->type == CAIRO_PATTERN_TYPE_MESH)
1577     {
1578         double min_alpha;
1579
1580         _cairo_pattern_alpha_range (pattern, &min_alpha, NULL);
1581         if (! CAIRO_ALPHA_IS_OPAQUE (min_alpha)) {
1582             pdf_pattern.gstate_res = _cairo_pdf_surface_new_object (surface);
1583             if (pdf_pattern.gstate_res.id == 0) {
1584                 cairo_pattern_destroy (pdf_pattern.pattern);
1585                 return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1586             }
1587         }
1588     }
1589
1590     pdf_pattern.width  = surface->width;
1591     pdf_pattern.height = surface->height;
1592     if (extents != NULL) {
1593         pdf_pattern.extents = *extents;
1594     } else {
1595         pdf_pattern.extents.x = 0;
1596         pdf_pattern.extents.y = 0;
1597         pdf_pattern.extents.width  = surface->width;
1598         pdf_pattern.extents.height = surface->height;
1599     }
1600
1601     *pattern_res = pdf_pattern.pattern_res;
1602     *gstate_res = pdf_pattern.gstate_res;
1603
1604     status = _cairo_array_append (&surface->page_patterns, &pdf_pattern);
1605     if (unlikely (status)) {
1606         cairo_pattern_destroy (pdf_pattern.pattern);
1607         return status;
1608     }
1609
1610     return CAIRO_INT_STATUS_SUCCESS;
1611 }
1612
1613 /* Get BBox in PDF coordinates from extents in cairo coordinates */
1614 static void
1615 _get_bbox_from_extents (double                       surface_height,
1616                        const cairo_rectangle_int_t *extents,
1617                        cairo_box_double_t          *bbox)
1618 {
1619     bbox->p1.x = extents->x;
1620     bbox->p1.y = surface_height - (extents->y + extents->height);
1621     bbox->p2.x = extents->x + extents->width;
1622     bbox->p2.y = surface_height - extents->y;
1623 }
1624
1625 static cairo_int_status_t
1626 _cairo_pdf_surface_add_pdf_shading (cairo_pdf_surface_t         *surface,
1627                                     const cairo_pattern_t       *pattern,
1628                                     cairo_operator_t             op,
1629                                     const cairo_rectangle_int_t *extents,
1630                                     cairo_pdf_resource_t        *shading_res,
1631                                     cairo_pdf_resource_t        *gstate_res)
1632 {
1633     return _cairo_pdf_surface_add_pdf_pattern_or_shading (surface,
1634                                                           pattern,
1635                                                           op,
1636                                                           extents,
1637                                                           TRUE,
1638                                                           shading_res,
1639                                                           gstate_res);
1640 }
1641
1642 static cairo_int_status_t
1643 _cairo_pdf_surface_add_pdf_pattern (cairo_pdf_surface_t         *surface,
1644                                     const cairo_pattern_t       *pattern,
1645                                     cairo_operator_t             op,
1646                                     const cairo_rectangle_int_t *extents,
1647                                     cairo_pdf_resource_t        *pattern_res,
1648                                     cairo_pdf_resource_t        *gstate_res)
1649 {
1650     return _cairo_pdf_surface_add_pdf_pattern_or_shading (surface,
1651                                                           pattern,
1652                                                           op,
1653                                                           extents,
1654                                                           FALSE,
1655                                                           pattern_res,
1656                                                           gstate_res);
1657 }
1658
1659 static cairo_int_status_t
1660 _cairo_pdf_surface_open_stream (cairo_pdf_surface_t     *surface,
1661                                 cairo_pdf_resource_t    *resource,
1662                                 cairo_bool_t             compressed,
1663                                 const char              *fmt,
1664                                 ...)
1665 {
1666     va_list ap;
1667     cairo_pdf_resource_t self, length;
1668     cairo_output_stream_t *output = NULL;
1669
1670     if (resource) {
1671         self = *resource;
1672         _cairo_pdf_surface_update_object (surface, self);
1673     } else {
1674         self = _cairo_pdf_surface_new_object (surface);
1675         if (self.id == 0)
1676             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1677     }
1678
1679     length = _cairo_pdf_surface_new_object (surface);
1680     if (length.id == 0)
1681         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1682
1683     if (compressed) {
1684         output = _cairo_deflate_stream_create (surface->output);
1685         if (_cairo_output_stream_get_status (output))
1686             return _cairo_output_stream_destroy (output);
1687     }
1688
1689     surface->pdf_stream.active = TRUE;
1690     surface->pdf_stream.self = self;
1691     surface->pdf_stream.length = length;
1692     surface->pdf_stream.compressed = compressed;
1693     surface->current_pattern_is_solid_color = FALSE;
1694     surface->current_operator = CAIRO_OPERATOR_OVER;
1695     _cairo_pdf_operators_reset (&surface->pdf_operators);
1696
1697     _cairo_output_stream_printf (surface->output,
1698                                  "%d 0 obj\n"
1699                                  "<< /Length %d 0 R\n",
1700                                  surface->pdf_stream.self.id,
1701                                  surface->pdf_stream.length.id);
1702     if (compressed)
1703         _cairo_output_stream_printf (surface->output,
1704                                      "   /Filter /FlateDecode\n");
1705
1706     if (fmt != NULL) {
1707         va_start (ap, fmt);
1708         _cairo_output_stream_vprintf (surface->output, fmt, ap);
1709         va_end (ap);
1710     }
1711
1712     _cairo_output_stream_printf (surface->output,
1713                                  ">>\n"
1714                                  "stream\n");
1715
1716     surface->pdf_stream.start_offset = _cairo_output_stream_get_position (surface->output);
1717
1718     if (compressed) {
1719         assert (surface->pdf_stream.old_output == NULL);
1720         surface->pdf_stream.old_output = surface->output;
1721         surface->output = output;
1722         _cairo_pdf_operators_set_stream (&surface->pdf_operators, surface->output);
1723     }
1724
1725     return _cairo_output_stream_get_status (surface->output);
1726 }
1727
1728 static cairo_int_status_t
1729 _cairo_pdf_surface_close_stream (cairo_pdf_surface_t *surface)
1730 {
1731     cairo_int_status_t status;
1732     long length;
1733
1734     if (! surface->pdf_stream.active)
1735         return CAIRO_INT_STATUS_SUCCESS;
1736
1737     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
1738
1739     if (surface->pdf_stream.compressed) {
1740         cairo_int_status_t status2;
1741
1742         status2 = _cairo_output_stream_destroy (surface->output);
1743         if (likely (status == CAIRO_INT_STATUS_SUCCESS))
1744             status = status2;
1745
1746         surface->output = surface->pdf_stream.old_output;
1747         _cairo_pdf_operators_set_stream (&surface->pdf_operators, surface->output);
1748         surface->pdf_stream.old_output = NULL;
1749     }
1750
1751     length = _cairo_output_stream_get_position (surface->output) -
1752         surface->pdf_stream.start_offset;
1753     _cairo_output_stream_printf (surface->output,
1754                                  "\n"
1755                                  "endstream\n"
1756                                  "endobj\n");
1757
1758     _cairo_pdf_surface_update_object (surface,
1759                                       surface->pdf_stream.length);
1760     _cairo_output_stream_printf (surface->output,
1761                                  "%d 0 obj\n"
1762                                  "   %ld\n"
1763                                  "endobj\n",
1764                                  surface->pdf_stream.length.id,
1765                                  length);
1766
1767     surface->pdf_stream.active = FALSE;
1768
1769     if (likely (status == CAIRO_INT_STATUS_SUCCESS))
1770         status = _cairo_output_stream_get_status (surface->output);
1771
1772     return status;
1773 }
1774
1775 static void
1776 _cairo_pdf_surface_write_memory_stream (cairo_pdf_surface_t         *surface,
1777                                         cairo_output_stream_t       *mem_stream,
1778                                         cairo_pdf_resource_t         resource,
1779                                         cairo_pdf_group_resources_t *resources,
1780                                         cairo_bool_t                 is_knockout_group,
1781                                         const cairo_box_double_t    *bbox)
1782 {
1783     _cairo_pdf_surface_update_object (surface, resource);
1784
1785     _cairo_output_stream_printf (surface->output,
1786                                  "%d 0 obj\n"
1787                                  "<< /Type /XObject\n"
1788                                  "   /Length %d\n",
1789                                  resource.id,
1790                                  _cairo_memory_stream_length (mem_stream));
1791
1792     if (surface->compress_content) {
1793         _cairo_output_stream_printf (surface->output,
1794                                      "   /Filter /FlateDecode\n");
1795     }
1796
1797     _cairo_output_stream_printf (surface->output,
1798                                  "   /Subtype /Form\n"
1799                                  "   /BBox [ %f %f %f %f ]\n"
1800                                  "   /Group <<\n"
1801                                  "      /Type /Group\n"
1802                                  "      /S /Transparency\n"
1803                                  "      /I true\n"
1804                                  "      /CS /DeviceRGB\n",
1805                                  bbox->p1.x, bbox->p1.y, bbox->p2.x, bbox->p2.y);
1806
1807     if (is_knockout_group)
1808         _cairo_output_stream_printf (surface->output,
1809                                      "      /K true\n");
1810
1811     _cairo_output_stream_printf (surface->output,
1812                                  "   >>\n"
1813                                  "   /Resources\n");
1814     _cairo_pdf_surface_emit_group_resources (surface, resources);
1815     _cairo_output_stream_printf (surface->output,
1816                                  ">>\n"
1817                                  "stream\n");
1818     _cairo_memory_stream_copy (mem_stream, surface->output);
1819     _cairo_output_stream_printf (surface->output,
1820                                  "endstream\n"
1821                                  "endobj\n");
1822 }
1823
1824 static cairo_int_status_t
1825 _cairo_pdf_surface_open_group (cairo_pdf_surface_t         *surface,
1826                                const cairo_box_double_t    *bbox,
1827                                cairo_pdf_resource_t        *resource)
1828 {
1829     cairo_int_status_t status;
1830
1831     assert (surface->pdf_stream.active == FALSE);
1832     assert (surface->group_stream.active == FALSE);
1833
1834     surface->group_stream.active = TRUE;
1835     surface->current_pattern_is_solid_color = FALSE;
1836     surface->current_operator = CAIRO_OPERATOR_OVER;
1837     _cairo_pdf_operators_reset (&surface->pdf_operators);
1838
1839     surface->group_stream.mem_stream = _cairo_memory_stream_create ();
1840
1841     if (surface->compress_content) {
1842         surface->group_stream.stream =
1843             _cairo_deflate_stream_create (surface->group_stream.mem_stream);
1844     } else {
1845         surface->group_stream.stream = surface->group_stream.mem_stream;
1846     }
1847     status = _cairo_output_stream_get_status (surface->group_stream.stream);
1848
1849     surface->group_stream.old_output = surface->output;
1850     surface->output = surface->group_stream.stream;
1851     _cairo_pdf_operators_set_stream (&surface->pdf_operators, surface->output);
1852     _cairo_pdf_group_resources_clear (&surface->resources);
1853
1854     if (resource) {
1855         surface->group_stream.resource = *resource;
1856     } else {
1857         surface->group_stream.resource = _cairo_pdf_surface_new_object (surface);
1858         if (surface->group_stream.resource.id == 0)
1859             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1860     }
1861     surface->group_stream.is_knockout = FALSE;
1862     surface->group_stream.bbox = *bbox;
1863
1864     return status;
1865 }
1866
1867 static cairo_int_status_t
1868 _cairo_pdf_surface_open_knockout_group (cairo_pdf_surface_t         *surface,
1869                                         const cairo_box_double_t    *bbox)
1870 {
1871     cairo_int_status_t status;
1872
1873     status = _cairo_pdf_surface_open_group (surface, bbox, NULL);
1874     if (unlikely (status))
1875         return status;
1876
1877     surface->group_stream.is_knockout = TRUE;
1878
1879     return CAIRO_INT_STATUS_SUCCESS;
1880 }
1881
1882 static cairo_int_status_t
1883 _cairo_pdf_surface_close_group (cairo_pdf_surface_t *surface,
1884                                 cairo_pdf_resource_t *group)
1885 {
1886     cairo_int_status_t status = CAIRO_INT_STATUS_SUCCESS, status2;
1887
1888     assert (surface->pdf_stream.active == FALSE);
1889     assert (surface->group_stream.active == TRUE);
1890
1891     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
1892     if (unlikely (status))
1893         return status;
1894
1895     if (surface->compress_content) {
1896         status = _cairo_output_stream_destroy (surface->group_stream.stream);
1897         surface->group_stream.stream = NULL;
1898
1899         _cairo_output_stream_printf (surface->group_stream.mem_stream,
1900                                      "\n");
1901     }
1902     surface->output = surface->group_stream.old_output;
1903     _cairo_pdf_operators_set_stream (&surface->pdf_operators, surface->output);
1904     surface->group_stream.active = FALSE;
1905     _cairo_pdf_surface_write_memory_stream (surface,
1906                                             surface->group_stream.mem_stream,
1907                                             surface->group_stream.resource,
1908                                             &surface->resources,
1909                                             surface->group_stream.is_knockout,
1910                                             &surface->group_stream.bbox);
1911     if (group)
1912         *group = surface->group_stream.resource;
1913
1914     status2 = _cairo_output_stream_destroy (surface->group_stream.mem_stream);
1915     if (status == CAIRO_INT_STATUS_SUCCESS)
1916         status = status2;
1917
1918     surface->group_stream.mem_stream = NULL;
1919     surface->group_stream.stream = NULL;
1920
1921     return status;
1922 }
1923
1924 static cairo_int_status_t
1925 _cairo_pdf_surface_open_content_stream (cairo_pdf_surface_t       *surface,
1926                                         const cairo_box_double_t  *bbox,
1927                                         cairo_pdf_resource_t      *resource,
1928                                         cairo_bool_t               is_form,
1929                                         cairo_bool_t               is_group)
1930 {
1931     cairo_int_status_t status;
1932
1933     assert (surface->pdf_stream.active == FALSE);
1934     assert (surface->group_stream.active == FALSE);
1935
1936     surface->content_resources = _cairo_pdf_surface_new_object (surface);
1937     if (surface->content_resources.id == 0)
1938         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1939
1940     if (is_form) {
1941         assert (bbox != NULL);
1942
1943         if (is_group) {
1944             status =
1945                 _cairo_pdf_surface_open_stream (surface,
1946                                                 resource,
1947                                                 surface->compress_content,
1948                                                 "   /Type /XObject\n"
1949                                                 "   /Subtype /Form\n"
1950                                                 "   /BBox [ %f %f %f %f ]\n"
1951                                                 "   /Group <<\n"
1952                                                 "      /Type /Group\n"
1953                                                 "      /S /Transparency\n"
1954                                                 "      /I true\n"
1955                                                 "      /CS /DeviceRGB\n"
1956                                                 "   >>\n"
1957                                                 "   /Resources %d 0 R\n",
1958                                                 bbox->p1.x,
1959                                                 bbox->p1.y,
1960                                                 bbox->p2.x,
1961                                                 bbox->p2.y,
1962                                                 surface->content_resources.id);
1963         } else {
1964             status =
1965                 _cairo_pdf_surface_open_stream (surface,
1966                                                 resource,
1967                                                 surface->compress_content,
1968                                                 "   /Type /XObject\n"
1969                                                 "   /Subtype /Form\n"
1970                                                 "   /BBox [ %f %f %f %f ]\n"
1971                                                 "   /Resources %d 0 R\n",
1972                                                 bbox->p1.x,
1973                                                 bbox->p1.y,
1974                                                 bbox->p2.x,
1975                                                 bbox->p2.y,
1976                                                 surface->content_resources.id);
1977         }
1978     } else {
1979         status =
1980             _cairo_pdf_surface_open_stream (surface,
1981                                             resource,
1982                                             surface->compress_content,
1983                                             NULL);
1984     }
1985     if (unlikely (status))
1986         return status;
1987
1988     surface->content = surface->pdf_stream.self;
1989
1990     _cairo_output_stream_printf (surface->output, "q\n");
1991
1992     return _cairo_output_stream_get_status (surface->output);
1993 }
1994
1995 static cairo_int_status_t
1996 _cairo_pdf_surface_close_content_stream (cairo_pdf_surface_t *surface)
1997 {
1998     cairo_int_status_t status;
1999
2000     assert (surface->pdf_stream.active == TRUE);
2001     assert (surface->group_stream.active == FALSE);
2002
2003     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
2004     if (unlikely (status))
2005         return status;
2006
2007     _cairo_output_stream_printf (surface->output, "Q\n");
2008     status = _cairo_pdf_surface_close_stream (surface);
2009     if (unlikely (status))
2010         return status;
2011
2012     _cairo_pdf_surface_update_object (surface, surface->content_resources);
2013     _cairo_output_stream_printf (surface->output,
2014                                  "%d 0 obj\n",
2015                                  surface->content_resources.id);
2016     _cairo_pdf_surface_emit_group_resources (surface, &surface->resources);
2017     _cairo_output_stream_printf (surface->output,
2018                                  "endobj\n");
2019
2020     return _cairo_output_stream_get_status (surface->output);
2021 }
2022
2023 static void
2024 _cairo_pdf_source_surface_entry_pluck (void *entry, void *closure)
2025 {
2026     cairo_pdf_source_surface_entry_t *surface_entry = entry;
2027     cairo_hash_table_t *patterns = closure;
2028
2029     _cairo_hash_table_remove (patterns, &surface_entry->base);
2030     free (surface_entry->unique_id);
2031
2032     free (surface_entry);
2033 }
2034
2035 static cairo_status_t
2036 _cairo_pdf_surface_finish (void *abstract_surface)
2037 {
2038     cairo_pdf_surface_t *surface = abstract_surface;
2039     long offset;
2040     cairo_pdf_resource_t info, catalog;
2041     cairo_status_t status, status2;
2042     int size, i;
2043     cairo_pdf_jbig2_global_t *global;
2044
2045     status = surface->base.status;
2046     if (status == CAIRO_STATUS_SUCCESS)
2047         status = _cairo_pdf_surface_emit_font_subsets (surface);
2048
2049     _cairo_pdf_surface_write_pages (surface);
2050
2051     info = _cairo_pdf_surface_write_info (surface);
2052     if (info.id == 0 && status == CAIRO_STATUS_SUCCESS)
2053         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2054
2055     catalog = _cairo_pdf_surface_write_catalog (surface);
2056     if (catalog.id == 0 && status == CAIRO_STATUS_SUCCESS)
2057         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2058
2059     offset = _cairo_pdf_surface_write_xref (surface);
2060     if (offset == -1)
2061         status =  _cairo_error (CAIRO_STATUS_INVALID_INDEX);
2062
2063     _cairo_output_stream_printf (surface->output,
2064                                  "trailer\n"
2065                                  "<< /Size %d\n"
2066                                  "   /Root %d 0 R\n"
2067                                  "   /Info %d 0 R\n"
2068                                  ">>\n",
2069                                  surface->next_available_resource.id,
2070                                  catalog.id,
2071                                  info.id);
2072
2073     _cairo_output_stream_printf (surface->output,
2074                                  "startxref\n"
2075                                  "%ld\n"
2076                                  "%%%%EOF\n",
2077                                  offset);
2078
2079     /* pdf_operators has already been flushed when the last stream was
2080      * closed so we should never be writing anything here - however,
2081      * the stream may itself be in an error state. */
2082     status2 = _cairo_pdf_operators_fini (&surface->pdf_operators);
2083     if (status == CAIRO_STATUS_SUCCESS)
2084         status = status2;
2085
2086     /* close any active streams still open due to fatal errors */
2087     status2 = _cairo_pdf_surface_close_stream (surface);
2088     if (status == CAIRO_STATUS_SUCCESS)
2089         status = status2;
2090
2091     if (surface->group_stream.stream != NULL) {
2092         status2 = _cairo_output_stream_destroy (surface->group_stream.stream);
2093         if (status == CAIRO_STATUS_SUCCESS)
2094             status = status2;
2095     }
2096     if (surface->group_stream.mem_stream != NULL) {
2097         status2 = _cairo_output_stream_destroy (surface->group_stream.mem_stream);
2098         if (status == CAIRO_STATUS_SUCCESS)
2099             status = status2;
2100     }
2101     if (surface->pdf_stream.active)
2102         surface->output = surface->pdf_stream.old_output;
2103     if (surface->group_stream.active)
2104         surface->output = surface->group_stream.old_output;
2105
2106     /* and finish the pdf surface */
2107     status2 = _cairo_output_stream_destroy (surface->output);
2108     if (status == CAIRO_STATUS_SUCCESS)
2109         status = status2;
2110
2111     _cairo_pdf_surface_clear (surface);
2112     _cairo_pdf_group_resources_fini (&surface->resources);
2113
2114     _cairo_array_fini (&surface->objects);
2115     _cairo_array_fini (&surface->pages);
2116     _cairo_array_fini (&surface->rgb_linear_functions);
2117     _cairo_array_fini (&surface->alpha_linear_functions);
2118     _cairo_array_fini (&surface->page_patterns);
2119     _cairo_array_fini (&surface->page_surfaces);
2120     _cairo_hash_table_foreach (surface->all_surfaces,
2121                                _cairo_pdf_source_surface_entry_pluck,
2122                                surface->all_surfaces);
2123     _cairo_hash_table_destroy (surface->all_surfaces);
2124     _cairo_array_fini (&surface->smask_groups);
2125     _cairo_array_fini (&surface->fonts);
2126     _cairo_array_fini (&surface->knockout_group);
2127
2128     if (surface->font_subsets) {
2129         _cairo_scaled_font_subsets_destroy (surface->font_subsets);
2130         surface->font_subsets = NULL;
2131     }
2132
2133     size = _cairo_array_num_elements (&surface->jbig2_global);
2134     for (i = 0; i < size; i++) {
2135         global = (cairo_pdf_jbig2_global_t *) _cairo_array_index (&surface->jbig2_global, i);
2136         free(global->id);
2137         if (!global->emitted)
2138             return _cairo_error (CAIRO_STATUS_JBIG2_GLOBAL_MISSING);
2139     }
2140     _cairo_array_fini (&surface->jbig2_global);
2141
2142     _cairo_array_truncate (&surface->page_surfaces, 0);
2143
2144     _cairo_surface_clipper_reset (&surface->clipper);
2145
2146     return status;
2147 }
2148
2149 static cairo_int_status_t
2150 _cairo_pdf_surface_start_page (void *abstract_surface)
2151 {
2152     cairo_pdf_surface_t *surface = abstract_surface;
2153
2154     /* Document header */
2155     if (! surface->header_emitted) {
2156         const char *version;
2157
2158         switch (surface->pdf_version) {
2159         case CAIRO_PDF_VERSION_1_4:
2160             version = "1.4";
2161             break;
2162         default:
2163         case CAIRO_PDF_VERSION_1_5:
2164             version = "1.5";
2165             break;
2166         }
2167
2168         _cairo_output_stream_printf (surface->output,
2169                                      "%%PDF-%s\n", version);
2170         _cairo_output_stream_printf (surface->output,
2171                                      "%%%c%c%c%c\n", 181, 237, 174, 251);
2172         surface->header_emitted = TRUE;
2173     }
2174
2175     _cairo_pdf_group_resources_clear (&surface->resources);
2176
2177     return CAIRO_STATUS_SUCCESS;
2178 }
2179
2180 static cairo_int_status_t
2181 _cairo_pdf_surface_has_fallback_images (void            *abstract_surface,
2182                                         cairo_bool_t     has_fallbacks)
2183 {
2184     cairo_int_status_t status;
2185     cairo_pdf_surface_t *surface = abstract_surface;
2186     cairo_box_double_t bbox;
2187
2188     surface->has_fallback_images = has_fallbacks;
2189     bbox.p1.x = 0;
2190     bbox.p1.y = 0;
2191     bbox.p2.x = surface->width;
2192     bbox.p2.y = surface->height;
2193     status = _cairo_pdf_surface_open_content_stream (surface, &bbox, NULL, has_fallbacks, has_fallbacks);
2194     if (unlikely (status))
2195         return status;
2196
2197     return CAIRO_STATUS_SUCCESS;
2198 }
2199
2200 static cairo_bool_t
2201 _cairo_pdf_surface_supports_fine_grained_fallbacks (void *abstract_surface)
2202 {
2203     return TRUE;
2204 }
2205
2206 static cairo_int_status_t
2207 _cairo_pdf_surface_add_padded_image_surface (cairo_pdf_surface_t          *surface,
2208                                              const cairo_pattern_t        *source,
2209                                              const cairo_rectangle_int_t  *extents,
2210                                              cairo_pdf_resource_t         *surface_res,
2211                                              int                          *width,
2212                                              int                          *height,
2213                                              double                       *x_offset,
2214                                              double                       *y_offset)
2215 {
2216     cairo_image_surface_t *image;
2217     cairo_surface_t *pad_image;
2218     void *image_extra;
2219     cairo_int_status_t status;
2220     int w, h;
2221     cairo_rectangle_int_t extents2;
2222     cairo_box_t box;
2223     cairo_rectangle_int_t rect;
2224     cairo_surface_pattern_t pad_pattern;
2225
2226     status = _cairo_pdf_surface_acquire_source_image_from_pattern (surface, source,
2227                                                                    &image, &image_extra);
2228     if (unlikely (status))
2229         return status;
2230
2231     pad_image = &image->base;
2232
2233     /* get the operation extents in pattern space */
2234     _cairo_box_from_rectangle (&box, extents);
2235     _cairo_matrix_transform_bounding_box_fixed (&source->matrix, &box, NULL);
2236     _cairo_box_round_to_rectangle (&box, &rect);
2237
2238     /* Check if image needs padding to fill extents */
2239     w = image->width;
2240     h = image->height;
2241     if (_cairo_fixed_integer_ceil(box.p1.x) < 0 ||
2242         _cairo_fixed_integer_ceil(box.p1.y) < 0 ||
2243         _cairo_fixed_integer_floor(box.p2.x) > w ||
2244         _cairo_fixed_integer_floor(box.p2.y) > h)
2245     {
2246         pad_image = _cairo_image_surface_create_with_content (image->base.content,
2247                                                               rect.width,
2248                                                               rect.height);
2249         if (pad_image->status) {
2250             status = pad_image->status;
2251             goto BAIL;
2252         }
2253
2254         _cairo_pattern_init_for_surface (&pad_pattern, &image->base);
2255         cairo_matrix_init_translate (&pad_pattern.base.matrix, rect.x, rect.y);
2256         pad_pattern.base.extend = CAIRO_EXTEND_PAD;
2257         status = _cairo_surface_paint (pad_image,
2258                                        CAIRO_OPERATOR_SOURCE, &pad_pattern.base,
2259                                        NULL);
2260         _cairo_pattern_fini (&pad_pattern.base);
2261         if (unlikely (status))
2262             goto BAIL;
2263     }
2264
2265     status = _cairo_pdf_surface_add_source_surface (surface,
2266                                                     pad_image,
2267                                                     NULL,
2268                                                     FALSE,
2269                                                     source->filter,
2270                                                     FALSE,
2271                                                     FALSE,
2272                                                     extents,
2273                                                     NULL,
2274                                                     surface_res,
2275                                                     width,
2276                                                     height,
2277                                                     x_offset,
2278                                                     y_offset,
2279                                                     &extents2);
2280     if (unlikely (status))
2281         goto BAIL;
2282
2283     if (pad_image != &image->base) {
2284         /* If using a padded image, replace _add_source_surface
2285          * x/y_offset with padded image offset. Note:
2286          * _add_source_surface only sets a non zero x/y_offset for
2287          * RASTER_SOURCE patterns. _add_source_surface will always set
2288          * x/y_offset to 0 for surfaces so we can ignore the returned
2289          * offset and replace it with the offset required for the
2290          * padded image */
2291         *x_offset = rect.x;
2292         *y_offset = rect.y;
2293     }
2294
2295 BAIL:
2296     if (pad_image != &image->base)
2297         cairo_surface_destroy (pad_image);
2298
2299     _cairo_pdf_surface_release_source_image_from_pattern (surface, source, image, image_extra);
2300
2301     return status;
2302 }
2303
2304 /* Emit alpha channel from the image into stream_res.
2305  */
2306 static cairo_int_status_t
2307 _cairo_pdf_surface_emit_smask (cairo_pdf_surface_t      *surface,
2308                                cairo_image_surface_t    *image,
2309                                cairo_bool_t              stencil_mask,
2310                                cairo_bool_t              interpolate,
2311                                cairo_pdf_resource_t     *stream_res)
2312 {
2313     cairo_int_status_t status = CAIRO_STATUS_SUCCESS;
2314     char *alpha;
2315     unsigned long alpha_size;
2316     uint32_t *pixel32;
2317     uint8_t *pixel8;
2318     int i, x, y, bit, a;
2319     cairo_image_transparency_t transparency;
2320
2321     /* This is the only image format we support, which simplifies things. */
2322     assert (image->format == CAIRO_FORMAT_ARGB32 ||
2323             image->format == CAIRO_FORMAT_RGB24 ||
2324             image->format == CAIRO_FORMAT_A8 ||
2325             image->format == CAIRO_FORMAT_A1 );
2326
2327     transparency = _cairo_image_analyze_transparency (image);
2328     if (stencil_mask) {
2329         assert (transparency == CAIRO_IMAGE_IS_OPAQUE ||
2330                 transparency == CAIRO_IMAGE_HAS_BILEVEL_ALPHA);
2331     } else {
2332         assert (transparency != CAIRO_IMAGE_IS_OPAQUE);
2333     }
2334
2335     if (transparency == CAIRO_IMAGE_HAS_BILEVEL_ALPHA || transparency == CAIRO_IMAGE_IS_OPAQUE) {
2336         alpha_size = (image->width + 7) / 8 * image->height;
2337         alpha = _cairo_malloc_ab ((image->width+7) / 8, image->height);
2338     } else {
2339         alpha_size = image->height * image->width;
2340         alpha = _cairo_malloc_ab (image->height, image->width);
2341     }
2342
2343     if (unlikely (alpha == NULL)) {
2344         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2345         goto CLEANUP;
2346     }
2347
2348     i = 0;
2349     for (y = 0; y < image->height; y++) {
2350         if (transparency == CAIRO_IMAGE_IS_OPAQUE) {
2351             for (x = 0; x < (image->width + 7) / 8; x++)
2352                 alpha[i++] = 0xff;
2353         } else if (image->format == CAIRO_FORMAT_A1) {
2354             pixel8 = (uint8_t *) (image->data + y * image->stride);
2355
2356             for (x = 0; x < (image->width + 7) / 8; x++, pixel8++) {
2357                 a = *pixel8;
2358                 a = CAIRO_BITSWAP8_IF_LITTLE_ENDIAN (a);
2359                 alpha[i++] = a;
2360             }
2361         } else {
2362             pixel8 = (uint8_t *) (image->data + y * image->stride);
2363             pixel32 = (uint32_t *) (image->data + y * image->stride);
2364             bit = 7;
2365             for (x = 0; x < image->width; x++) {
2366                 if (image->format == CAIRO_FORMAT_ARGB32) {
2367                     a = (*pixel32 & 0xff000000) >> 24;
2368                     pixel32++;
2369                 } else {
2370                     a = *pixel8;
2371                     pixel8++;
2372                 }
2373
2374                 if (transparency == CAIRO_IMAGE_HAS_ALPHA) {
2375                     alpha[i++] = a;
2376                 } else { /* transparency == CAIRO_IMAGE_HAS_BILEVEL_ALPHA or CAIRO_IMAGE_IS_OPAQUE */
2377                     if (bit == 7)
2378                         alpha[i] = 0;
2379                     if (a != 0)
2380                         alpha[i] |= (1 << bit);
2381                     bit--;
2382                     if (bit < 0) {
2383                         bit = 7;
2384                         i++;
2385                     }
2386                 }
2387             }
2388             if (bit != 7)
2389                 i++;
2390         }
2391     }
2392
2393     if (stencil_mask) {
2394         status = _cairo_pdf_surface_open_stream (surface,
2395                                                  stream_res,
2396                                                  TRUE,
2397                                                  "   /Type /XObject\n"
2398                                                  "   /Subtype /Image\n"
2399                                                  "   /ImageMask true\n"
2400                                                  "   /Width %d\n"
2401                                                  "   /Height %d\n"
2402                                                  "   /Interpolate %s\n"
2403                                                  "   /BitsPerComponent 1\n"
2404                                                  "   /Decode [1 0]\n",
2405                                                  image->width, image->height,
2406                                                  interpolate ? "true" : "false");
2407     } else {
2408         status = _cairo_pdf_surface_open_stream (surface,
2409                                                  stream_res,
2410                                                  TRUE,
2411                                                  "   /Type /XObject\n"
2412                                                  "   /Subtype /Image\n"
2413                                                  "   /Width %d\n"
2414                                                  "   /Height %d\n"
2415                                                  "   /ColorSpace /DeviceGray\n"
2416                                                  "   /Interpolate %s\n"
2417                                                  "   /BitsPerComponent %d\n",
2418                                                  image->width, image->height,
2419                                                  interpolate ? "true" : "false",
2420                                                  transparency == CAIRO_IMAGE_HAS_ALPHA ? 8 : 1);
2421     }
2422     if (unlikely (status))
2423         goto CLEANUP_ALPHA;
2424
2425     _cairo_output_stream_write (surface->output, alpha, alpha_size);
2426     status = _cairo_pdf_surface_close_stream (surface);
2427
2428  CLEANUP_ALPHA:
2429     free (alpha);
2430  CLEANUP:
2431     return status;
2432 }
2433
2434 /**
2435  * _cairo_pdf_surface_emit_image:
2436  * @surface: the pdf surface
2437  * @image_surf: The image to write
2438  * @surface_entry: Contains image resource, smask resource, interpolate and stencil mask parameters.
2439  *
2440  * Emit an image stream using the @image_res resource and write out
2441  * the image data from @image_surf. If @smask_res is not null, @smask_res will
2442  * be specified as the smask for the image. Otherwise emit the an smask if
2443  * the image is requires one.
2444  **/
2445 static cairo_int_status_t
2446 _cairo_pdf_surface_emit_image (cairo_pdf_surface_t              *surface,
2447                                cairo_image_surface_t            *image_surf,
2448                                cairo_pdf_source_surface_entry_t *surface_entry)
2449 {
2450     cairo_int_status_t status = CAIRO_STATUS_SUCCESS;
2451     char *data;
2452     unsigned long data_size;
2453     uint32_t *pixel;
2454     int i, x, y, bit;
2455     cairo_pdf_resource_t smask = {0}; /* squelch bogus compiler warning */
2456     cairo_bool_t need_smask;
2457     cairo_image_color_t color;
2458     cairo_image_surface_t *image;
2459     cairo_image_transparency_t transparency;
2460     char smask_buf[30];
2461
2462     image  = image_surf;
2463     if (image->format != CAIRO_FORMAT_RGB24 &&
2464         image->format != CAIRO_FORMAT_ARGB32 &&
2465         image->format != CAIRO_FORMAT_A8 &&
2466         image->format != CAIRO_FORMAT_A1)
2467     {
2468         cairo_surface_t *surf;
2469         cairo_surface_pattern_t pattern;
2470
2471         surf = _cairo_image_surface_create_with_content (image_surf->base.content,
2472                                                          image_surf->width,
2473                                                          image_surf->height);
2474         image = (cairo_image_surface_t *) surf;
2475         if (surf->status) {
2476             status = surf->status;
2477             goto CLEANUP;
2478         }
2479
2480         _cairo_pattern_init_for_surface (&pattern, &image_surf->base);
2481         status = _cairo_surface_paint (surf,
2482                                        CAIRO_OPERATOR_SOURCE, &pattern.base,
2483                                        NULL);
2484         _cairo_pattern_fini (&pattern.base);
2485         if (unlikely (status))
2486             goto CLEANUP;
2487     }
2488
2489     if (surface_entry->smask || surface_entry->stencil_mask) {
2490         return _cairo_pdf_surface_emit_smask (surface, image,
2491                                               surface_entry->stencil_mask,
2492                                               surface_entry->interpolate,
2493                                               &surface_entry->surface_res);
2494     }
2495
2496     color = _cairo_image_analyze_color (image);
2497     switch (color) {
2498         default:
2499         case CAIRO_IMAGE_UNKNOWN_COLOR:
2500             ASSERT_NOT_REACHED;
2501         case CAIRO_IMAGE_IS_COLOR:
2502             data_size = image->height * image->width * 3;
2503             data = _cairo_malloc_abc (image->width, image->height, 3);
2504             break;
2505
2506         case CAIRO_IMAGE_IS_GRAYSCALE:
2507             data_size = image->height * image->width;
2508             data = _cairo_malloc_ab (image->width, image->height);
2509             break;
2510         case CAIRO_IMAGE_IS_MONOCHROME:
2511             data_size = (image->width + 7) / 8 * image->height;
2512             data = _cairo_malloc_ab ((image->width+7) / 8, image->height);
2513             break;
2514     }
2515     if (unlikely (data == NULL)) {
2516         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2517         goto CLEANUP;
2518     }
2519
2520     i = 0;
2521     for (y = 0; y < image->height; y++) {
2522         pixel = (uint32_t *) (image->data + y * image->stride);
2523
2524         bit = 7;
2525         for (x = 0; x < image->width; x++, pixel++) {
2526             int r, g, b;
2527
2528             /* XXX: We're un-premultiplying alpha here. My reading of the PDF
2529              * specification suggests that we should be able to avoid having
2530              * to do this by filling in the SMask's Matte dictionary
2531              * appropriately, but my attempts to do that so far have
2532              * failed. */
2533             if (image->format == CAIRO_FORMAT_ARGB32) {
2534                 uint8_t a;
2535                 a = (*pixel & 0xff000000) >> 24;
2536                 if (a == 0) {
2537                     r = g = b = 0;
2538                 } else {
2539                     r = (((*pixel & 0xff0000) >> 16) * 255 + a / 2) / a;
2540                     g = (((*pixel & 0x00ff00) >>  8) * 255 + a / 2) / a;
2541                     b = (((*pixel & 0x0000ff) >>  0) * 255 + a / 2) / a;
2542                 }
2543             } else if (image->format == CAIRO_FORMAT_RGB24) {
2544                 r = (*pixel & 0x00ff0000) >> 16;
2545                 g = (*pixel & 0x0000ff00) >>  8;
2546                 b = (*pixel & 0x000000ff) >>  0;
2547             } else {
2548                 r = g = b = 0;
2549             }
2550
2551             switch (color) {
2552                 case CAIRO_IMAGE_IS_COLOR:
2553                 case CAIRO_IMAGE_UNKNOWN_COLOR:
2554                     data[i++] = r;
2555                     data[i++] = g;
2556                     data[i++] = b;
2557                     break;
2558
2559                 case CAIRO_IMAGE_IS_GRAYSCALE:
2560                     data[i++] = r;
2561                     break;
2562
2563                 case CAIRO_IMAGE_IS_MONOCHROME:
2564                     if (bit == 7)
2565                         data[i] = 0;
2566                     if (r != 0)
2567                         data[i] |= (1 << bit);
2568                     bit--;
2569                     if (bit < 0) {
2570                         bit = 7;
2571                         i++;
2572                     }
2573                     break;
2574             }
2575         }
2576         if (bit != 7)
2577             i++;
2578     }
2579
2580     if (surface_entry->smask_res.id != 0) {
2581         need_smask = TRUE;
2582         smask = surface_entry->smask_res;
2583     } else {
2584         need_smask = FALSE;
2585         if (image->format == CAIRO_FORMAT_ARGB32 ||
2586             image->format == CAIRO_FORMAT_A8 ||
2587             image->format == CAIRO_FORMAT_A1)
2588         {
2589             transparency = _cairo_image_analyze_transparency (image);
2590             if (transparency != CAIRO_IMAGE_IS_OPAQUE) {
2591                 need_smask = TRUE;
2592                 smask = _cairo_pdf_surface_new_object (surface);
2593                 if (smask.id == 0) {
2594                     status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2595                     goto CLEANUP_RGB;
2596                 }
2597
2598                 status = _cairo_pdf_surface_emit_smask (surface, image, FALSE, surface_entry->interpolate, &smask);
2599                 if (unlikely (status))
2600                     goto CLEANUP_RGB;
2601             }
2602         }
2603     }
2604
2605     if (need_smask)
2606         snprintf(smask_buf, sizeof(smask_buf), "   /SMask %d 0 R\n", smask.id);
2607     else
2608         smask_buf[0] = 0;
2609
2610     status = _cairo_pdf_surface_open_stream (surface,
2611                                              &surface_entry->surface_res,
2612                                              TRUE,
2613                                              "   /Type /XObject\n"
2614                                              "   /Subtype /Image\n"
2615                                              "   /Width %d\n"
2616                                              "   /Height %d\n"
2617                                              "   /ColorSpace %s\n"
2618                                              "   /Interpolate %s\n"
2619                                              "   /BitsPerComponent %d\n"
2620                                              "%s",
2621                                              image->width,
2622                                              image->height,
2623                                              color == CAIRO_IMAGE_IS_COLOR ? "/DeviceRGB" : "/DeviceGray",
2624                                              surface_entry->interpolate ? "true" : "false",
2625                                              color == CAIRO_IMAGE_IS_MONOCHROME? 1 : 8,
2626                                              smask_buf);
2627     if (unlikely (status))
2628         goto CLEANUP_RGB;
2629
2630 #undef IMAGE_DICTIONARY
2631
2632     _cairo_output_stream_write (surface->output, data, data_size);
2633     status = _cairo_pdf_surface_close_stream (surface);
2634
2635 CLEANUP_RGB:
2636     free (data);
2637 CLEANUP:
2638     if (image != image_surf)
2639         cairo_surface_destroy (&image->base);
2640
2641     return status;
2642 }
2643
2644 static cairo_int_status_t
2645 _cairo_pdf_surface_lookup_jbig2_global (cairo_pdf_surface_t       *surface,
2646                                         const unsigned char       *global_id,
2647                                         unsigned long              global_id_length,
2648                                         cairo_pdf_jbig2_global_t **entry)
2649 {
2650     cairo_pdf_jbig2_global_t global;
2651     int size, i;
2652     cairo_int_status_t status;
2653
2654     size = _cairo_array_num_elements (&surface->jbig2_global);
2655     for (i = 0; i < size; i++) {
2656         *entry = (cairo_pdf_jbig2_global_t *) _cairo_array_index (&surface->jbig2_global, i);
2657         if ((*entry)->id && global_id && (*entry)->id_length == global_id_length
2658             && memcmp((*entry)->id, global_id, global_id_length) == 0) {
2659             return CAIRO_STATUS_SUCCESS;
2660         }
2661     }
2662
2663     global.id = malloc(global_id_length);
2664     if (unlikely (global.id == NULL)) {
2665         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2666     }
2667
2668     memcpy (global.id, global_id, global_id_length);
2669     global.id_length = global_id_length;
2670     global.res = _cairo_pdf_surface_new_object (surface);
2671     if (global.res.id == 0) {
2672         free(global.id);
2673         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2674     }
2675
2676     global.emitted = FALSE;
2677     status = _cairo_array_append (&surface->jbig2_global, &global);
2678     if (unlikely(status))
2679         return status;
2680
2681     size = _cairo_array_num_elements (&surface->jbig2_global);
2682     *entry = (cairo_pdf_jbig2_global_t *) _cairo_array_index (&surface->jbig2_global, size - 1);
2683     return CAIRO_STATUS_SUCCESS;
2684 }
2685
2686 static cairo_int_status_t
2687 _cairo_pdf_surface_emit_jbig2_image (cairo_pdf_surface_t              *surface,
2688                                      cairo_surface_t                  *source,
2689                                      cairo_pdf_source_surface_entry_t *surface_entry)
2690 {
2691     cairo_int_status_t status;
2692     const unsigned char *mime_data;
2693     unsigned long mime_data_length;
2694     cairo_image_info_t info;
2695     const unsigned char *global_id;
2696     unsigned long global_id_length;
2697     const unsigned char *global_data;
2698     unsigned long global_data_length;
2699     cairo_pdf_jbig2_global_t *global_entry = NULL; /* hide compiler warning */
2700     char smask_buf[30];
2701     char decode_parms_buf[100];
2702
2703     cairo_surface_get_mime_data (source, CAIRO_MIME_TYPE_JBIG2,
2704                                  &mime_data, &mime_data_length);
2705     if (mime_data == NULL)
2706         return CAIRO_INT_STATUS_UNSUPPORTED;
2707
2708     status = _cairo_image_info_get_jbig2_info (&info, mime_data, mime_data_length);
2709     if (status)
2710         return status;
2711
2712     cairo_surface_get_mime_data (source, CAIRO_MIME_TYPE_JBIG2_GLOBAL_ID,
2713                                  &global_id, &global_id_length);
2714     if (global_id && global_id_length > 0) {
2715         status = _cairo_pdf_surface_lookup_jbig2_global (surface, global_id, global_id_length, &global_entry);
2716         if (unlikely(status))
2717             return status;
2718
2719         if (!global_entry->emitted) {
2720             cairo_surface_get_mime_data (source, CAIRO_MIME_TYPE_JBIG2_GLOBAL,
2721                                          &global_data, &global_data_length);
2722             if (global_data) {
2723                 status = _cairo_pdf_surface_open_stream (surface, &global_entry->res, FALSE, NULL);
2724                 if (unlikely(status))
2725                     return status;
2726
2727                 _cairo_output_stream_write (surface->output, global_data, global_data_length);
2728                 status = _cairo_pdf_surface_close_stream (surface);
2729                 if (unlikely(status))
2730                     return status;
2731
2732                 global_entry->emitted = TRUE;
2733             }
2734         }
2735
2736         snprintf(decode_parms_buf, sizeof(decode_parms_buf),
2737                  "   /DecodeParms << /JBIG2Globals %d 0 R >>\n", global_entry->res.id);
2738     } else {
2739         decode_parms_buf[0] = 0;
2740     }
2741
2742     if (surface_entry->smask_res.id)
2743         snprintf(smask_buf, sizeof(smask_buf), "   /SMask %d 0 R\n", surface_entry->smask_res.id);
2744     else
2745         smask_buf[0] = 0;
2746
2747     if (surface_entry->stencil_mask) {
2748         status = _cairo_pdf_surface_open_stream (surface,
2749                                                  &surface_entry->surface_res,
2750                                                  FALSE,
2751                                                  "   /Type /XObject\n"
2752                                                  "   /Subtype /Image\n"
2753                                                  "   /ImageMask true\n"
2754                                                  "   /Width %d\n"
2755                                                  "   /Height %d\n"
2756                                                  "   /Interpolate %s\n"
2757                                                  "   /BitsPerComponent 1\n"
2758                                                  "   /Decode [1 0]\n"
2759                                                  "   /Filter /JPXDecode\n"
2760                                                  "%s",
2761                                                  info.width,
2762                                                  info.height,
2763                                                  surface_entry->interpolate ? "true" : "false",
2764                                                  decode_parms_buf);
2765     } else {
2766         status = _cairo_pdf_surface_open_stream (surface,
2767                                                  &surface_entry->surface_res,
2768                                                  FALSE,
2769                                                  "   /Type /XObject\n"
2770                                                  "   /Subtype /Image\n"
2771                                                  "   /Width %d\n"
2772                                                  "   /Height %d\n"
2773                                                  "   /ColorSpace /DeviceGray\n"
2774                                                  "   /BitsPerComponent 1\n"
2775                                                  "   /Interpolate %s\n"
2776                                                  "%s"
2777                                                  "   /Filter /JBIG2Decode\n"
2778                                                  "%s",
2779                                                  info.width,
2780                                                  info.height,
2781                                                  surface_entry->interpolate ? "true" : "false",
2782                                                  smask_buf,
2783                                                  decode_parms_buf);
2784     }
2785     if (unlikely(status))
2786         return status;
2787
2788     _cairo_output_stream_write (surface->output, mime_data, mime_data_length);
2789     status = _cairo_pdf_surface_close_stream (surface);
2790
2791     return status;
2792 }
2793
2794 static cairo_int_status_t
2795 _cairo_pdf_surface_emit_jpx_image (cairo_pdf_surface_t              *surface,
2796                                    cairo_surface_t                  *source,
2797                                    cairo_pdf_source_surface_entry_t *surface_entry)
2798 {
2799     cairo_int_status_t status;
2800     const unsigned char *mime_data;
2801     unsigned long mime_data_length;
2802     cairo_image_info_t info;
2803     char smask_buf[30];
2804
2805     if (surface->pdf_version < CAIRO_PDF_VERSION_1_5)
2806         return CAIRO_INT_STATUS_UNSUPPORTED;
2807
2808     cairo_surface_get_mime_data (source, CAIRO_MIME_TYPE_JP2,
2809                                  &mime_data, &mime_data_length);
2810     if (mime_data == NULL)
2811         return CAIRO_INT_STATUS_UNSUPPORTED;
2812
2813     status = _cairo_image_info_get_jpx_info (&info, mime_data, mime_data_length);
2814     if (status)
2815         return status;
2816
2817     if ((surface_entry->smask || surface_entry->stencil_mask) && info.num_components != 1)
2818         return CAIRO_INT_STATUS_UNSUPPORTED;
2819
2820     if ((surface_entry->stencil_mask) && info.bits_per_component != 1)
2821         return CAIRO_INT_STATUS_UNSUPPORTED;
2822
2823     if (surface_entry->smask_res.id)
2824         snprintf(smask_buf, sizeof(smask_buf), "   /SMask %d 0 R\n", surface_entry->smask_res.id);
2825     else
2826         smask_buf[0] = 0;
2827
2828     if (surface_entry->stencil_mask) {
2829         status = _cairo_pdf_surface_open_stream (surface,
2830                                                  &surface_entry->surface_res,
2831                                                  FALSE,
2832                                                  "   /Type /XObject\n"
2833                                                  "   /Subtype /Image\n"
2834                                                  "   /ImageMask true\n"
2835                                                  "   /Width %d\n"
2836                                                  "   /Height %d\n"
2837                                                  "   /Interpolate %s\n"
2838                                                  "   /BitsPerComponent 1\n"
2839                                                  "   /Decode [1 0]\n"
2840                                                  "   /Filter /JPXDecode\n",
2841                                                  info.width,
2842                                                  info.height,
2843                                                  surface_entry->interpolate ? "true" : "false");
2844     } else {
2845         status = _cairo_pdf_surface_open_stream (surface,
2846                                                  &surface_entry->surface_res,
2847                                                  FALSE,
2848                                                  "   /Type /XObject\n"
2849                                                  "   /Subtype /Image\n"
2850                                                  "   /Width %d\n"
2851                                                  "   /Height %d\n"
2852                                                  "   /Interpolate %s\n"
2853                                                  "%s"
2854                                                  "   /Filter /JPXDecode\n",
2855                                                  info.width,
2856                                                  info.height,
2857                                                  surface_entry->interpolate ? "true" : "false",
2858                                                  smask_buf);
2859     }
2860     if (status)
2861         return status;
2862
2863     _cairo_output_stream_write (surface->output, mime_data, mime_data_length);
2864     status = _cairo_pdf_surface_close_stream (surface);
2865
2866     return status;
2867 }
2868
2869 static cairo_int_status_t
2870 _cairo_pdf_surface_emit_jpeg_image (cairo_pdf_surface_t              *surface,
2871                                     cairo_surface_t                  *source,
2872                                     cairo_pdf_source_surface_entry_t *surface_entry)
2873 {
2874     cairo_int_status_t status;
2875     const unsigned char *mime_data;
2876     unsigned long mime_data_length;
2877     cairo_image_info_t info;
2878     const char *colorspace;
2879     char smask_buf[30];
2880
2881     cairo_surface_get_mime_data (source, CAIRO_MIME_TYPE_JPEG,
2882                                  &mime_data, &mime_data_length);
2883     if (unlikely (source->status))
2884         return source->status;
2885     if (mime_data == NULL)
2886         return CAIRO_INT_STATUS_UNSUPPORTED;
2887
2888     status = _cairo_image_info_get_jpeg_info (&info, mime_data, mime_data_length);
2889     if (unlikely (status))
2890         return status;
2891
2892     if ((surface_entry->smask || surface_entry->stencil_mask) && info.num_components != 1)
2893         return CAIRO_INT_STATUS_UNSUPPORTED;
2894
2895     if ((surface_entry->stencil_mask) && info.bits_per_component != 1)
2896         return CAIRO_INT_STATUS_UNSUPPORTED;
2897
2898     switch (info.num_components) {
2899         case 1:
2900             colorspace = "/DeviceGray";
2901             break;
2902         case 3:
2903             colorspace = "/DeviceRGB";
2904             break;
2905         case 4:
2906             colorspace = "/DeviceCMYK";
2907             break;
2908         default:
2909             return CAIRO_INT_STATUS_UNSUPPORTED;
2910     }
2911
2912     if (surface_entry->smask_res.id)
2913         snprintf(smask_buf, sizeof(smask_buf), "   /SMask %d 0 R\n", surface_entry->smask_res.id);
2914     else
2915         smask_buf[0] = 0;
2916
2917     if (surface_entry->stencil_mask) {
2918         status = _cairo_pdf_surface_open_stream (surface,
2919                                                  &surface_entry->surface_res,
2920                                                  FALSE,
2921                                                  "   /Type /XObject\n"
2922                                                  "   /Subtype /Image\n"
2923                                                  "   /ImageMask true\n"
2924                                                  "   /Width %d\n"
2925                                                  "   /Height %d\n"
2926                                                  "   /Interpolate %s\n"
2927                                                  "   /BitsPerComponent 1\n"
2928                                                  "   /Decode [1 0]\n"
2929                                                  "   /Filter /DCTDecode\n",
2930                                                  info.width,
2931                                                  info.height,
2932                                                  surface_entry->interpolate ? "true" : "false");
2933     } else {
2934         status = _cairo_pdf_surface_open_stream (surface,
2935                                                  &surface_entry->surface_res,
2936                                                  FALSE,
2937                                                  "   /Type /XObject\n"
2938                                                  "   /Subtype /Image\n"
2939                                                  "   /Width %d\n"
2940                                                  "   /Height %d\n"
2941                                                  "   /ColorSpace %s\n"
2942                                                  "   /Interpolate %s\n"
2943                                                  "   /BitsPerComponent %d\n"
2944                                                  "%s"
2945                                                  "   /Filter /DCTDecode\n",
2946                                                  info.width,
2947                                                  info.height,
2948                                                  colorspace,
2949                                                  surface_entry->interpolate ? "true" : "false",
2950                                                  info.bits_per_component,
2951                                                  smask_buf);
2952     }
2953     if (unlikely (status))
2954         return status;
2955
2956     _cairo_output_stream_write (surface->output, mime_data, mime_data_length);
2957     status = _cairo_pdf_surface_close_stream (surface);
2958
2959     return status;
2960 }
2961
2962 static cairo_int_status_t
2963 _cairo_pdf_surface_emit_image_surface (cairo_pdf_surface_t        *surface,
2964                                        cairo_pdf_source_surface_t *source)
2965 {
2966     cairo_image_surface_t *image;
2967     void *image_extra;
2968     cairo_int_status_t status;
2969
2970     if (source->type == CAIRO_PATTERN_TYPE_SURFACE) {
2971         status = _cairo_pdf_surface_emit_jbig2_image (surface, source->surface, source->hash_entry);
2972         if (status != CAIRO_INT_STATUS_UNSUPPORTED)
2973             return status;
2974
2975         status = _cairo_pdf_surface_emit_jpx_image (surface, source->surface, source->hash_entry);
2976         if (status != CAIRO_INT_STATUS_UNSUPPORTED)
2977             return status;
2978
2979         status = _cairo_pdf_surface_emit_jpeg_image (surface, source->surface, source->hash_entry);
2980         if (status != CAIRO_INT_STATUS_UNSUPPORTED)
2981             return status;
2982     }
2983
2984     if (source->type == CAIRO_PATTERN_TYPE_SURFACE) {
2985         status = _cairo_surface_acquire_source_image (source->surface, &image, &image_extra);
2986     } else {
2987         status = _cairo_pdf_surface_acquire_source_image_from_pattern (surface, source->raster_pattern,
2988                                                                        &image, &image_extra);
2989     }
2990     if (unlikely (status))
2991         return status;
2992
2993     status = _cairo_pdf_surface_emit_image (surface,
2994                                             image,
2995                                             source->hash_entry);
2996
2997     if (source->type == CAIRO_PATTERN_TYPE_SURFACE)
2998         _cairo_surface_release_source_image (source->surface, image, image_extra);
2999     else
3000         _cairo_pdf_surface_release_source_image_from_pattern (surface, source->raster_pattern,
3001                                                               image, image_extra);
3002
3003     return status;
3004 }
3005
3006 static cairo_int_status_t
3007 _cairo_pdf_surface_emit_recording_surface (cairo_pdf_surface_t        *surface,
3008                                            cairo_pdf_source_surface_t *pdf_source)
3009 {
3010     double old_width, old_height;
3011     cairo_paginated_mode_t old_paginated_mode;
3012     cairo_surface_clipper_t old_clipper;
3013     cairo_box_double_t bbox;
3014     cairo_int_status_t status;
3015     int alpha = 0;
3016     cairo_surface_t *free_me = NULL;
3017     cairo_surface_t *source;
3018     const cairo_rectangle_int_t *extents;
3019     int width;
3020     int height;
3021     cairo_bool_t is_subsurface;
3022     cairo_bool_t transparency_group;
3023     cairo_recording_surface_t *recording;
3024
3025     assert (pdf_source->type == CAIRO_PATTERN_TYPE_SURFACE);
3026     extents = &pdf_source->hash_entry->extents;
3027     width = pdf_source->hash_entry->width;
3028     height = pdf_source->hash_entry->height;
3029     is_subsurface = FALSE;
3030     source = pdf_source->surface;
3031     if (_cairo_surface_is_snapshot (source)) {
3032         free_me = source = _cairo_surface_snapshot_get_target (source);
3033     } else if (source->backend->type == CAIRO_SURFACE_TYPE_SUBSURFACE) {
3034         cairo_surface_subsurface_t *sub = (cairo_surface_subsurface_t *) source;
3035
3036         source = sub->target;
3037         extents = &sub->extents;
3038         width = extents->width;
3039         height = extents->height;
3040         is_subsurface = TRUE;
3041     }
3042
3043     assert (source->type == CAIRO_SURFACE_TYPE_RECORDING);
3044     recording = (cairo_recording_surface_t *) source;
3045
3046     old_width = surface->width;
3047     old_height = surface->height;
3048     old_paginated_mode = surface->paginated_mode;
3049     old_clipper = surface->clipper;
3050     _cairo_surface_clipper_init (&surface->clipper,
3051                                  _cairo_pdf_surface_clipper_intersect_clip_path);
3052
3053     _cairo_pdf_surface_set_size_internal (surface, width, height);
3054
3055     /* Patterns are emitted after fallback images. The paginated mode
3056      * needs to be set to _RENDER while the recording surface is replayed
3057      * back to this surface.
3058      */
3059     surface->paginated_mode = CAIRO_PAGINATED_MODE_RENDER;
3060     _cairo_pdf_group_resources_clear (&surface->resources);
3061     _get_bbox_from_extents (height, extents, &bbox);
3062
3063     /* We can optimize away the transparency group allowing the viewer
3064      * to replay the group in place when all operators are OVER and the
3065      * recording contains only opaque and/or clear alpha.
3066      */
3067     transparency_group = !(pdf_source->hash_entry->operator == CAIRO_OPERATOR_OVER &&
3068                            _cairo_recording_surface_has_only_bilevel_alpha (recording) &&
3069                            _cairo_recording_surface_has_only_op_over (recording));
3070     status = _cairo_pdf_surface_open_content_stream (surface, &bbox, &pdf_source->hash_entry->surface_res,
3071                                                      TRUE, transparency_group);
3072     if (unlikely (status))
3073         goto err;
3074
3075     if (source->content == CAIRO_CONTENT_COLOR) {
3076         status = _cairo_pdf_surface_add_alpha (surface, 1.0, &alpha);
3077         if (unlikely (status))
3078             goto err;
3079
3080         _cairo_output_stream_printf (surface->output,
3081                                      "q /a%d gs 0 0 0 rg 0 0 %f %f re f Q\n",
3082                                      alpha,
3083                                      surface->width,
3084                                      surface->height);
3085     }
3086
3087     status = _cairo_recording_surface_replay_region (source,
3088                                                      is_subsurface ? extents : NULL,
3089                                                      &surface->base,
3090                                                      CAIRO_RECORDING_REGION_NATIVE);
3091     assert (status != CAIRO_INT_STATUS_UNSUPPORTED);
3092     if (unlikely (status))
3093         goto err;
3094
3095     status = _cairo_pdf_surface_close_content_stream (surface);
3096
3097     _cairo_surface_clipper_reset (&surface->clipper);
3098     surface->clipper = old_clipper;
3099     _cairo_pdf_surface_set_size_internal (surface,
3100                                           old_width,
3101                                           old_height);
3102     surface->paginated_mode = old_paginated_mode;
3103
3104 err:
3105     cairo_surface_destroy (free_me);
3106     return status;
3107 }
3108
3109 static cairo_int_status_t
3110 _cairo_pdf_surface_emit_surface (cairo_pdf_surface_t        *surface,
3111                                  cairo_pdf_source_surface_t *src_surface)
3112 {
3113     if (src_surface->type == CAIRO_PATTERN_TYPE_SURFACE &&
3114         src_surface->surface->type == CAIRO_SURFACE_TYPE_RECORDING)
3115         return _cairo_pdf_surface_emit_recording_surface (surface, src_surface);
3116
3117     return _cairo_pdf_surface_emit_image_surface (surface, src_surface);
3118 }
3119
3120 static cairo_int_status_t
3121 _cairo_pdf_surface_emit_surface_pattern (cairo_pdf_surface_t    *surface,
3122                                          cairo_pdf_pattern_t    *pdf_pattern)
3123 {
3124     cairo_pattern_t *pattern = pdf_pattern->pattern;
3125     cairo_int_status_t status;
3126     cairo_pdf_resource_t pattern_resource = {0};
3127     cairo_matrix_t cairo_p2d, pdf_p2d;
3128     cairo_extend_t extend = cairo_pattern_get_extend (pattern);
3129     double xstep, ystep;
3130     cairo_rectangle_int_t pattern_extents;
3131     int pattern_width = 0; /* squelch bogus compiler warning */
3132     int pattern_height = 0; /* squelch bogus compiler warning */
3133     double x_offset;
3134     double y_offset;
3135     char draw_surface[200];
3136     cairo_box_double_t     bbox;
3137
3138     if (pattern->extend == CAIRO_EXTEND_PAD) {
3139         status = _cairo_pdf_surface_add_padded_image_surface (surface,
3140                                                               pattern,
3141                                                               &pdf_pattern->extents,
3142                                                               &pattern_resource,
3143                                                               &pattern_width,
3144                                                               &pattern_height,
3145                                                               &x_offset,
3146                                                               &y_offset);
3147         pattern_extents.x = 0;
3148         pattern_extents.y = 0;
3149         pattern_extents.width = pattern_width;
3150         pattern_extents.height = pattern_height;
3151     } else {
3152         status = _cairo_pdf_surface_add_source_surface (surface,
3153                                                         NULL,
3154                                                         pattern,
3155                                                         pdf_pattern->operator,
3156                                                         pattern->filter,
3157                                                         FALSE,
3158                                                         FALSE,
3159                                                         &pdf_pattern->extents,
3160                                                         NULL,
3161                                                         &pattern_resource,
3162                                                         &pattern_width,
3163                                                         &pattern_height,
3164                                                         &x_offset,
3165                                                         &y_offset,
3166                                                         &pattern_extents);
3167     }
3168     if (unlikely (status))
3169         return status;
3170
3171     switch (extend) {
3172     case CAIRO_EXTEND_PAD:
3173     case CAIRO_EXTEND_NONE:
3174     {
3175         /* In PS/PDF, (as far as I can tell), all patterns are
3176          * repeating. So we support cairo's EXTEND_NONE semantics
3177          * by setting the repeat step size to a size large enough
3178          * to guarantee that no more than a single occurrence will
3179          * be visible.
3180          *
3181          * First, map the surface extents into pattern space (since
3182          * xstep and ystep are in pattern space).  Then use an upper
3183          * bound on the length of the diagonal of the pattern image
3184          * and the surface as repeat size.  This guarantees to never
3185          * repeat visibly.
3186          */
3187         double x1 = 0.0, y1 = 0.0;
3188         double x2 = surface->width, y2 = surface->height;
3189         _cairo_matrix_transform_bounding_box (&pattern->matrix,
3190                                               &x1, &y1, &x2, &y2,
3191                                               NULL);
3192
3193         /* Rather than computing precise bounds of the union, just
3194          * add the surface extents unconditionally. We only
3195          * required an answer that's large enough, we don't really
3196          * care if it's not as tight as possible.*/
3197         xstep = ystep = ceil ((x2 - x1) + (y2 - y1) +
3198                               pattern_width + pattern_height);
3199     }
3200     break;
3201     case CAIRO_EXTEND_REPEAT:
3202         xstep = pattern_width;
3203         ystep = pattern_height;
3204         break;
3205     case CAIRO_EXTEND_REFLECT:
3206         pattern_extents.x = 0;
3207         pattern_extents.y = 0;
3208         pattern_extents.width = pattern_width*2;
3209         pattern_extents.height = pattern_height*2;
3210         xstep = pattern_width*2;
3211         ystep = pattern_height*2;
3212         break;
3213         /* All the rest (if any) should have been analyzed away, so this
3214          * case should be unreachable. */
3215     default:
3216         ASSERT_NOT_REACHED;
3217         xstep = 0;
3218         ystep = 0;
3219     }
3220
3221     /* At this point, (that is, within the surface backend interface),
3222      * the pattern's matrix maps from cairo's device space to cairo's
3223      * pattern space, (both with their origin at the upper-left, and
3224      * cairo's pattern space of size width,height).
3225      *
3226      * Then, we must emit a PDF pattern object that maps from its own
3227      * pattern space, (which has a size that we establish in the BBox
3228      * dictionary entry), to the PDF page's *initial* space, (which
3229      * does not benefit from the Y-axis flipping matrix that we emit
3230      * on each page). So the PDF patterns matrix maps from a
3231      * (width,height) pattern space to a device space with the origin
3232      * in the lower-left corner.
3233      *
3234      * So to handle all of that, we start with an identity matrix for
3235      * the PDF pattern to device matrix. We translate it up by the
3236      * image height then flip it in the Y direction, (moving us from
3237      * the PDF origin to cairo's origin). We then multiply in the
3238      * inverse of the cairo pattern matrix, (since it maps from device
3239      * to pattern, while we're setting up pattern to device). Finally,
3240      * we translate back down by the image height and flip again to
3241      * end up at the lower-left origin that PDF expects.
3242      *
3243      * Additionally, within the stream that paints the pattern itself,
3244      * we are using a PDF image object that has a size of (1,1) so we
3245      * have to scale it up by the image width and height to fill our
3246      * pattern cell.
3247      */
3248     cairo_p2d = pattern->matrix;
3249     status = cairo_matrix_invert (&cairo_p2d);
3250     /* cairo_pattern_set_matrix ensures the matrix is invertible */
3251     assert (status == CAIRO_INT_STATUS_SUCCESS);
3252
3253     cairo_matrix_multiply (&pdf_p2d, &cairo_p2d, &surface->cairo_to_pdf);
3254     cairo_matrix_translate (&pdf_p2d, -x_offset, -y_offset);
3255     cairo_matrix_translate (&pdf_p2d, 0.0, pattern_height);
3256     cairo_matrix_scale (&pdf_p2d, 1.0, -1.0);
3257
3258     _get_bbox_from_extents (pattern_height, &pattern_extents, &bbox);
3259     _cairo_pdf_surface_update_object (surface, pdf_pattern->pattern_res);
3260     status = _cairo_pdf_surface_open_stream (surface,
3261                                              &pdf_pattern->pattern_res,
3262                                              FALSE,
3263                                              "   /PatternType 1\n"
3264                                              "   /BBox [ %f %f %f %f ]\n"
3265                                              "   /XStep %f\n"
3266                                              "   /YStep %f\n"
3267                                              "   /TilingType 1\n"
3268                                              "   /PaintType 1\n"
3269                                              "   /Matrix [ %f %f %f %f %f %f ]\n"
3270                                              "   /Resources << /XObject << /x%d %d 0 R >> >>\n",
3271                                              bbox.p1.x, bbox.p1.y, bbox.p2.x, bbox.p2.y,
3272                                              xstep, ystep,
3273                                              pdf_p2d.xx, pdf_p2d.yx,
3274                                              pdf_p2d.xy, pdf_p2d.yy,
3275                                              pdf_p2d.x0, pdf_p2d.y0,
3276                                              pattern_resource.id,
3277                                              pattern_resource.id);
3278     if (unlikely (status))
3279         return status;
3280
3281     if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE &&
3282         ((cairo_surface_pattern_t *) pattern)->surface->type == CAIRO_SURFACE_TYPE_RECORDING) {
3283         snprintf(draw_surface,
3284                  sizeof (draw_surface),
3285                  "/x%d Do\n",
3286                  pattern_resource.id);
3287     } else {
3288         snprintf(draw_surface,
3289                  sizeof (draw_surface),
3290                  "q %d 0 0 %d 0 0 cm /x%d Do Q",
3291                  pattern_width,
3292                  pattern_height,
3293                  pattern_resource.id);
3294     }
3295
3296     if (extend == CAIRO_EXTEND_REFLECT) {
3297         _cairo_output_stream_printf (surface->output,
3298                                      "q 0 0 %d %d re W n %s Q\n"
3299                                      "q -1 0 0 1 %d 0 cm 0 0 %d %d re W n %s Q\n"
3300                                      "q 1 0 0 -1 0 %d cm 0 0 %d %d re W n %s Q\n"
3301                                      "q -1 0 0 -1 %d %d cm 0 0 %d %d re W n %s Q\n",
3302                                      pattern_width, pattern_height,
3303                                      draw_surface,
3304                                      pattern_width*2, pattern_width, pattern_height,
3305                                      draw_surface,
3306                                      pattern_height*2, pattern_width, pattern_height,
3307                                      draw_surface,
3308                                      pattern_width*2, pattern_height*2, pattern_width, pattern_height,
3309                                      draw_surface);
3310     } else {
3311         _cairo_output_stream_printf (surface->output,
3312                                      " %s \n",
3313                                      draw_surface);
3314     }
3315
3316     status = _cairo_pdf_surface_close_stream (surface);
3317     if (unlikely (status))
3318         return status;
3319
3320     return _cairo_output_stream_get_status (surface->output);
3321 }
3322
3323 typedef struct _cairo_pdf_color_stop {
3324     double offset;
3325     double color[4];
3326     cairo_pdf_resource_t resource;
3327 } cairo_pdf_color_stop_t;
3328
3329 static cairo_int_status_t
3330 cairo_pdf_surface_emit_rgb_linear_function (cairo_pdf_surface_t    *surface,
3331                                             cairo_pdf_color_stop_t *stop1,
3332                                             cairo_pdf_color_stop_t *stop2,
3333                                             cairo_pdf_resource_t   *function)
3334 {
3335     int num_elems, i;
3336     cairo_pdf_rgb_linear_function_t elem;
3337     cairo_pdf_resource_t res;
3338     cairo_int_status_t status;
3339
3340     num_elems = _cairo_array_num_elements (&surface->rgb_linear_functions);
3341     for (i = 0; i < num_elems; i++) {
3342         _cairo_array_copy_element (&surface->rgb_linear_functions, i, &elem);
3343         if (memcmp (&elem.color1[0], &stop1->color[0], sizeof (double)*3) != 0)
3344             continue;
3345         if (memcmp (&elem.color2[0], &stop2->color[0], sizeof (double)*3) != 0)
3346             continue;
3347         *function =  elem.resource;
3348         return CAIRO_STATUS_SUCCESS;
3349     }
3350
3351     res = _cairo_pdf_surface_new_object (surface);
3352     if (res.id == 0)
3353         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
3354
3355     _cairo_output_stream_printf (surface->output,
3356                                  "%d 0 obj\n"
3357                                  "<< /FunctionType 2\n"
3358                                  "   /Domain [ 0 1 ]\n"
3359                                  "   /C0 [ %f %f %f ]\n"
3360                                  "   /C1 [ %f %f %f ]\n"
3361                                  "   /N 1\n"
3362                                  ">>\n"
3363                                  "endobj\n",
3364                                  res.id,
3365                                  stop1->color[0],
3366                                  stop1->color[1],
3367                                  stop1->color[2],
3368                                  stop2->color[0],
3369                                  stop2->color[1],
3370                                  stop2->color[2]);
3371
3372     elem.resource = res;
3373     memcpy (&elem.color1[0], &stop1->color[0], sizeof (double)*3);
3374     memcpy (&elem.color2[0], &stop2->color[0], sizeof (double)*3);
3375
3376     status = _cairo_array_append (&surface->rgb_linear_functions, &elem);
3377     *function = res;
3378
3379     return status;
3380 }
3381
3382 static cairo_int_status_t
3383 cairo_pdf_surface_emit_alpha_linear_function (cairo_pdf_surface_t    *surface,
3384                                               cairo_pdf_color_stop_t *stop1,
3385                                               cairo_pdf_color_stop_t *stop2,
3386                                               cairo_pdf_resource_t   *function)
3387 {
3388     int num_elems, i;
3389     cairo_pdf_alpha_linear_function_t elem;
3390     cairo_pdf_resource_t res;
3391     cairo_int_status_t status;
3392
3393     num_elems = _cairo_array_num_elements (&surface->alpha_linear_functions);
3394     for (i = 0; i < num_elems; i++) {
3395         _cairo_array_copy_element (&surface->alpha_linear_functions, i, &elem);
3396         if (elem.alpha1 != stop1->color[3])
3397             continue;
3398         if (elem.alpha2 != stop2->color[3])
3399             continue;
3400         *function =  elem.resource;
3401         return CAIRO_STATUS_SUCCESS;
3402     }
3403
3404     res = _cairo_pdf_surface_new_object (surface);
3405     if (res.id == 0)
3406         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
3407
3408     _cairo_output_stream_printf (surface->output,
3409                                  "%d 0 obj\n"
3410                                  "<< /FunctionType 2\n"
3411                                  "   /Domain [ 0 1 ]\n"
3412                                  "   /C0 [ %f ]\n"
3413                                  "   /C1 [ %f ]\n"
3414                                  "   /N 1\n"
3415                                  ">>\n"
3416                                  "endobj\n",
3417                                  res.id,
3418                                  stop1->color[3],
3419                                  stop2->color[3]);
3420
3421     elem.resource = res;
3422     elem.alpha1 = stop1->color[3];
3423     elem.alpha2 = stop2->color[3];
3424
3425     status = _cairo_array_append (&surface->alpha_linear_functions, &elem);
3426     *function = res;
3427
3428     return status;
3429 }
3430
3431 static cairo_int_status_t
3432 _cairo_pdf_surface_emit_stitched_colorgradient (cairo_pdf_surface_t    *surface,
3433                                                 unsigned int            n_stops,
3434                                                 cairo_pdf_color_stop_t *stops,
3435                                                 cairo_bool_t            is_alpha,
3436                                                 cairo_pdf_resource_t   *function)
3437 {
3438     cairo_pdf_resource_t res;
3439     unsigned int i;
3440     cairo_int_status_t status;
3441
3442     /* emit linear gradients between pairs of subsequent stops... */
3443     for (i = 0; i < n_stops-1; i++) {
3444         if (is_alpha) {
3445             status = cairo_pdf_surface_emit_alpha_linear_function (surface,
3446                                                                    &stops[i],
3447                                                                    &stops[i+1],
3448                                                                    &stops[i].resource);
3449             if (unlikely (status))
3450                 return status;
3451         } else {
3452             status = cairo_pdf_surface_emit_rgb_linear_function (surface,
3453                                                                  &stops[i],
3454                                                                  &stops[i+1],
3455                                                                  &stops[i].resource);
3456             if (unlikely (status))
3457                 return status;
3458         }
3459     }
3460
3461     /* ... and stitch them together */
3462     res = _cairo_pdf_surface_new_object (surface);
3463     if (res.id == 0)
3464         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
3465
3466     _cairo_output_stream_printf (surface->output,
3467                                  "%d 0 obj\n"
3468                                  "<< /FunctionType 3\n"
3469                                  "   /Domain [ %f %f ]\n",
3470                                  res.id,
3471                                  stops[0].offset,
3472                                  stops[n_stops - 1].offset);
3473
3474     _cairo_output_stream_printf (surface->output,
3475                                  "   /Functions [ ");
3476     for (i = 0; i < n_stops-1; i++)
3477         _cairo_output_stream_printf (surface->output,
3478                                      "%d 0 R ", stops[i].resource.id);
3479     _cairo_output_stream_printf (surface->output,
3480                                  "]\n");
3481
3482     _cairo_output_stream_printf (surface->output,
3483                                  "   /Bounds [ ");
3484     for (i = 1; i < n_stops-1; i++)
3485         _cairo_output_stream_printf (surface->output,
3486                                      "%f ", stops[i].offset);
3487     _cairo_output_stream_printf (surface->output,
3488                                  "]\n");
3489
3490     _cairo_output_stream_printf (surface->output,
3491                                  "   /Encode [ ");
3492     for (i = 1; i < n_stops; i++)
3493         _cairo_output_stream_printf (surface->output,
3494                                      "0 1 ");
3495     _cairo_output_stream_printf (surface->output,
3496                                  "]\n");
3497
3498     _cairo_output_stream_printf (surface->output,
3499                                  ">>\n"
3500                                  "endobj\n");
3501
3502     *function = res;
3503
3504     return _cairo_output_stream_get_status (surface->output);
3505 }
3506
3507
3508 static void
3509 calc_gradient_color (cairo_pdf_color_stop_t *new_stop,
3510                      cairo_pdf_color_stop_t *stop1,
3511                      cairo_pdf_color_stop_t *stop2)
3512 {
3513     int i;
3514     double offset = stop1->offset / (stop1->offset + 1.0 - stop2->offset);
3515
3516     for (i = 0; i < 4; i++)
3517         new_stop->color[i] = stop1->color[i] + offset*(stop2->color[i] - stop1->color[i]);
3518 }
3519
3520 #define COLOR_STOP_EPSILON 1e-6
3521
3522 static cairo_int_status_t
3523 _cairo_pdf_surface_emit_pattern_stops (cairo_pdf_surface_t      *surface,
3524                                        cairo_gradient_pattern_t *pattern,
3525                                        cairo_pdf_resource_t     *color_function,
3526                                        cairo_pdf_resource_t     *alpha_function)
3527 {
3528     cairo_pdf_color_stop_t *allstops, *stops;
3529     unsigned int n_stops;
3530     unsigned int i;
3531     cairo_bool_t emit_alpha = FALSE;
3532     cairo_int_status_t status;
3533
3534     color_function->id = 0;
3535     alpha_function->id = 0;
3536
3537     allstops = _cairo_malloc_ab ((pattern->n_stops + 2), sizeof (cairo_pdf_color_stop_t));
3538     if (unlikely (allstops == NULL))
3539         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
3540
3541     stops = &allstops[1];
3542     n_stops = pattern->n_stops;
3543
3544     for (i = 0; i < n_stops; i++) {
3545         stops[i].color[0] = pattern->stops[i].color.red;
3546         stops[i].color[1] = pattern->stops[i].color.green;
3547         stops[i].color[2] = pattern->stops[i].color.blue;
3548         stops[i].color[3] = pattern->stops[i].color.alpha;
3549         if (!CAIRO_ALPHA_IS_OPAQUE (stops[i].color[3]))
3550             emit_alpha = TRUE;
3551         stops[i].offset = pattern->stops[i].offset;
3552     }
3553
3554     if (pattern->base.extend == CAIRO_EXTEND_REPEAT ||
3555         pattern->base.extend == CAIRO_EXTEND_REFLECT) {
3556         if (stops[0].offset > COLOR_STOP_EPSILON) {
3557             if (pattern->base.extend == CAIRO_EXTEND_REFLECT)
3558                 memcpy (allstops, stops, sizeof (cairo_pdf_color_stop_t));
3559             else
3560                 calc_gradient_color (&allstops[0], &stops[0], &stops[n_stops-1]);
3561             stops = allstops;
3562             n_stops++;
3563         }
3564         stops[0].offset = 0.0;
3565
3566         if (stops[n_stops-1].offset < 1.0 - COLOR_STOP_EPSILON) {
3567             if (pattern->base.extend == CAIRO_EXTEND_REFLECT) {
3568                 memcpy (&stops[n_stops],
3569                         &stops[n_stops - 1],
3570                         sizeof (cairo_pdf_color_stop_t));
3571             } else {
3572                 calc_gradient_color (&stops[n_stops], &stops[0], &stops[n_stops-1]);
3573             }
3574             n_stops++;
3575         }
3576         stops[n_stops-1].offset = 1.0;
3577     }
3578
3579     if (stops[0].offset == stops[n_stops - 1].offset) {
3580         /*
3581          * The first and the last stops have the same offset, but we
3582          * don't want a function with an empty domain, because that
3583          * would provoke underdefined behaviour from rasterisers.
3584          * This can only happen with EXTEND_PAD, because EXTEND_NONE
3585          * is optimised into a clear pattern in cairo-gstate, and
3586          * REFLECT/REPEAT are always transformed to have the first
3587          * stop at t=0 and the last stop at t=1.  Thus we want a step
3588          * function going from the first color to the last one.
3589          *
3590          * This can be accomplished by stitching three functions:
3591          *  - a constant first color function,
3592          *  - a step from the first color to the last color (with empty domain)
3593          *  - a constant last color function
3594          */
3595         cairo_pdf_color_stop_t pad_stops[4];
3596
3597         assert (pattern->base.extend == CAIRO_EXTEND_PAD);
3598
3599         pad_stops[0] = pad_stops[1] = stops[0];
3600         pad_stops[2] = pad_stops[3] = stops[n_stops - 1];
3601
3602         pad_stops[0].offset = 0;
3603         pad_stops[3].offset = 1;
3604
3605         status = _cairo_pdf_surface_emit_stitched_colorgradient (surface,
3606                                                                  4,
3607                                                                  pad_stops,
3608                                                                  FALSE,
3609                                                                  color_function);
3610         if (unlikely (status))
3611             goto BAIL;
3612
3613         if (emit_alpha) {
3614             status = _cairo_pdf_surface_emit_stitched_colorgradient (surface,
3615                                                                      4,
3616                                                                      pad_stops,
3617                                                                      TRUE,
3618                                                                      alpha_function);
3619             if (unlikely (status))
3620                 goto BAIL;
3621         }
3622     } else if (n_stops == 2) {
3623         /* no need for stitched function */
3624         status = cairo_pdf_surface_emit_rgb_linear_function (surface,
3625                                                              &stops[0],
3626                                                              &stops[n_stops - 1],
3627                                                              color_function);
3628         if (unlikely (status))
3629             goto BAIL;
3630
3631         if (emit_alpha) {
3632             status = cairo_pdf_surface_emit_alpha_linear_function (surface,
3633                                                                    &stops[0],
3634                                                                    &stops[n_stops - 1],
3635                                                                    alpha_function);
3636             if (unlikely (status))
3637                 goto BAIL;
3638         }
3639     } else {
3640         /* multiple stops: stitch. XXX possible optimization: regularly spaced
3641          * stops do not require stitching. XXX */
3642         status = _cairo_pdf_surface_emit_stitched_colorgradient (surface,
3643                                                                  n_stops,
3644                                                                  stops,
3645                                                                  FALSE,
3646                                                                  color_function);
3647         if (unlikely (status))
3648             goto BAIL;
3649
3650         if (emit_alpha) {
3651             status = _cairo_pdf_surface_emit_stitched_colorgradient (surface,
3652                                                                      n_stops,
3653                                                                      stops,
3654                                                                      TRUE,
3655                                                                      alpha_function);
3656             if (unlikely (status))
3657                 goto BAIL;
3658         }
3659     }
3660
3661 BAIL:
3662     free (allstops);
3663     return status;
3664 }
3665
3666 static cairo_int_status_t
3667 _cairo_pdf_surface_emit_repeating_function (cairo_pdf_surface_t      *surface,
3668                                             cairo_gradient_pattern_t *pattern,
3669                                             cairo_pdf_resource_t     *function,
3670                                             int                       begin,
3671                                             int                       end)
3672 {
3673     cairo_pdf_resource_t res;
3674     int i;
3675
3676     res = _cairo_pdf_surface_new_object (surface);
3677     if (res.id == 0)
3678         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
3679
3680     _cairo_output_stream_printf (surface->output,
3681                                  "%d 0 obj\n"
3682                                  "<< /FunctionType 3\n"
3683                                  "   /Domain [ %d %d ]\n",
3684                                  res.id,
3685                                  begin,
3686                                  end);
3687
3688     _cairo_output_stream_printf (surface->output,
3689                                  "   /Functions [ ");
3690     for (i = begin; i < end; i++)
3691         _cairo_output_stream_printf (surface->output,
3692                                      "%d 0 R ", function->id);
3693     _cairo_output_stream_printf (surface->output,
3694                                  "]\n");
3695
3696     _cairo_output_stream_printf (surface->output,
3697                                  "   /Bounds [ ");
3698     for (i = begin + 1; i < end; i++)
3699         _cairo_output_stream_printf (surface->output,
3700                                      "%d ", i);
3701     _cairo_output_stream_printf (surface->output,
3702                                  "]\n");
3703
3704     _cairo_output_stream_printf (surface->output,
3705                                  "   /Encode [ ");
3706     for (i = begin; i < end; i++) {
3707         if ((i % 2) && pattern->base.extend == CAIRO_EXTEND_REFLECT) {
3708             _cairo_output_stream_printf (surface->output,
3709                                          "1 0 ");
3710         } else {
3711             _cairo_output_stream_printf (surface->output,
3712                                          "0 1 ");
3713         }
3714     }
3715     _cairo_output_stream_printf (surface->output,
3716                                  "]\n");
3717
3718     _cairo_output_stream_printf (surface->output,
3719                                  ">>\n"
3720                                  "endobj\n");
3721
3722     *function = res;
3723
3724     return _cairo_output_stream_get_status (surface->output);
3725 }
3726
3727 static cairo_int_status_t
3728 cairo_pdf_surface_emit_transparency_group (cairo_pdf_surface_t  *surface,
3729                                            cairo_pdf_pattern_t  *pdf_pattern,
3730                                            cairo_pdf_resource_t  gstate_resource,
3731                                            cairo_pdf_resource_t  gradient_mask)
3732 {
3733     cairo_pdf_resource_t smask_resource;
3734     cairo_int_status_t status;
3735     char buf[100];
3736     double x1, y1, x2, y2;
3737
3738     if (pdf_pattern->is_shading) {
3739         snprintf(buf, sizeof(buf),
3740                  "         /Shading\n"
3741                  "            << /sh%d %d 0 R >>\n",
3742                  gradient_mask.id,
3743                  gradient_mask.id);
3744     } else {
3745         snprintf(buf, sizeof(buf),
3746                  "         /Pattern\n"
3747                  "            << /p%d %d 0 R >>\n",
3748                  gradient_mask.id,
3749                  gradient_mask.id);
3750     }
3751
3752     if (pdf_pattern->is_shading) {
3753         cairo_box_t box;
3754
3755         /* When emitting a shading operator we are in cairo pattern
3756          * coordinates. _cairo_pdf_surface_paint_gradient has set the
3757          * ctm to the pattern matrix (including the convertion from
3758          * pdf to cairo coordinates) */
3759         _cairo_box_from_rectangle (&box, &pdf_pattern->extents);
3760         _cairo_box_to_doubles (&box, &x1, &y1, &x2, &y2);
3761         _cairo_matrix_transform_bounding_box (&pdf_pattern->pattern->matrix, &x1, &y1, &x2, &y2, NULL);
3762     } else {
3763         cairo_box_double_t box;
3764
3765         /* When emitting a shading pattern we are in pdf page
3766          * coordinates. The color and alpha shading patterns painted
3767          * in the XObject below contain the cairo pattern to pdf page
3768          * matrix in the /Matrix entry of the pattern. */
3769         _get_bbox_from_extents (pdf_pattern->height, &pdf_pattern->extents, &box);
3770         x1 = box.p1.x;
3771         y1 = box.p1.y;
3772         x2 = box.p2.x;
3773         y2 = box.p2.y;
3774     }
3775     status = _cairo_pdf_surface_open_stream (surface,
3776                                              NULL,
3777                                              surface->compress_content,
3778                                              "   /Type /XObject\n"
3779                                              "   /Subtype /Form\n"
3780                                              "   /FormType 1\n"
3781                                              "   /BBox [ %f %f %f %f ]\n"
3782                                              "   /Resources\n"
3783                                              "      << /ExtGState\n"
3784                                              "            << /a0 << /ca 1 /CA 1 >>"
3785                                              "      >>\n"
3786                                              "%s"
3787                                              "      >>\n"
3788                                              "   /Group\n"
3789                                              "      << /Type /Group\n"
3790                                              "         /S /Transparency\n"
3791                                              "         /I true\n"
3792                                              "         /CS /DeviceGray\n"
3793                                              "      >>\n",
3794                                              x1,y1,x2,y2,
3795                                              buf);
3796     if (unlikely (status))
3797         return status;
3798
3799     if (pdf_pattern->is_shading) {
3800         _cairo_output_stream_printf (surface->output,
3801                                      "/a0 gs /sh%d sh\n",
3802                                      gradient_mask.id);
3803     } else {
3804         _cairo_output_stream_printf (surface->output,
3805                                      "q\n"
3806                                      "/a0 gs\n"
3807                                      "/Pattern cs /p%d scn\n"
3808                                      "0 0 %f %f re\n"
3809                                      "f\n"
3810                                      "Q\n",
3811                                      gradient_mask.id,
3812                                      surface->width,
3813                                      surface->height);
3814     }
3815
3816     status = _cairo_pdf_surface_close_stream (surface);
3817     if (unlikely (status))
3818         return status;
3819
3820     smask_resource = _cairo_pdf_surface_new_object (surface);
3821     if (smask_resource.id == 0)
3822         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
3823
3824     _cairo_output_stream_printf (surface->output,
3825                                  "%d 0 obj\n"
3826                                  "<< /Type /Mask\n"
3827                                  "   /S /Luminosity\n"
3828                                  "   /G %d 0 R\n"
3829                                  ">>\n"
3830                                  "endobj\n",
3831                                  smask_resource.id,
3832                                  surface->pdf_stream.self.id);
3833
3834     /* Create GState which uses the transparency group as an SMask. */
3835     _cairo_pdf_surface_update_object (surface, gstate_resource);
3836
3837     _cairo_output_stream_printf (surface->output,
3838                                  "%d 0 obj\n"
3839                                  "<< /Type /ExtGState\n"
3840                                  "   /SMask %d 0 R\n"
3841                                  "   /ca 1\n"
3842                                  "   /CA 1\n"
3843                                  "   /AIS false\n"
3844                                  ">>\n"
3845                                  "endobj\n",
3846                                  gstate_resource.id,
3847                                  smask_resource.id);
3848
3849     return _cairo_output_stream_get_status (surface->output);
3850 }
3851
3852 static void
3853 _cairo_pdf_surface_output_gradient (cairo_pdf_surface_t        *surface,
3854                                     const cairo_pdf_pattern_t  *pdf_pattern,
3855                                     cairo_pdf_resource_t        pattern_resource,
3856                                     const cairo_matrix_t       *pat_to_pdf,
3857                                     const cairo_circle_double_t*start,
3858                                     const cairo_circle_double_t*end,
3859                                     const double               *domain,
3860                                     const char                 *colorspace,
3861                                     cairo_pdf_resource_t        color_function)
3862 {
3863     _cairo_output_stream_printf (surface->output,
3864                                  "%d 0 obj\n",
3865                                  pattern_resource.id);
3866
3867     if (!pdf_pattern->is_shading) {
3868         _cairo_output_stream_printf (surface->output,
3869                                      "<< /Type /Pattern\n"
3870                                      "   /PatternType 2\n"
3871                                      "   /Matrix [ ");
3872         _cairo_output_stream_print_matrix (surface->output, pat_to_pdf);
3873         _cairo_output_stream_printf (surface->output,
3874                                      " ]\n"
3875                                      "   /Shading\n");
3876     }
3877
3878     if (pdf_pattern->pattern->type == CAIRO_PATTERN_TYPE_LINEAR) {
3879         _cairo_output_stream_printf (surface->output,
3880                                      "      << /ShadingType 2\n"
3881                                      "         /ColorSpace %s\n"
3882                                      "         /Coords [ %f %f %f %f ]\n",
3883                                      colorspace,
3884                                      start->center.x, start->center.y,
3885                                      end->center.x, end->center.y);
3886     } else {
3887         _cairo_output_stream_printf (surface->output,
3888                                      "      << /ShadingType 3\n"
3889                                      "         /ColorSpace %s\n"
3890                                      "         /Coords [ %f %f %f %f %f %f ]\n",
3891                                      colorspace,
3892                                      start->center.x, start->center.y,
3893                                      MAX (start->radius, 0),
3894                                      end->center.x, end->center.y,
3895                                      MAX (end->radius, 0));
3896     }
3897
3898     _cairo_output_stream_printf (surface->output,
3899                                  "         /Domain [ %f %f ]\n",
3900                                  domain[0], domain[1]);
3901
3902     if (pdf_pattern->pattern->extend != CAIRO_EXTEND_NONE) {
3903         _cairo_output_stream_printf (surface->output,
3904                                      "         /Extend [ true true ]\n");
3905     } else {
3906         _cairo_output_stream_printf (surface->output,
3907                                      "         /Extend [ false false ]\n");
3908     }
3909
3910     _cairo_output_stream_printf (surface->output,
3911                                  "         /Function %d 0 R\n"
3912                                  "      >>\n",
3913                                  color_function.id);
3914
3915     if (!pdf_pattern->is_shading) {
3916         _cairo_output_stream_printf (surface->output,
3917                                      ">>\n");
3918     }
3919
3920     _cairo_output_stream_printf (surface->output,
3921                                      "endobj\n");
3922 }
3923
3924 static cairo_int_status_t
3925 _cairo_pdf_surface_emit_gradient (cairo_pdf_surface_t    *surface,
3926                                   cairo_pdf_pattern_t    *pdf_pattern)
3927 {
3928     cairo_gradient_pattern_t *pattern = (cairo_gradient_pattern_t *) pdf_pattern->pattern;
3929     cairo_pdf_resource_t color_function, alpha_function;
3930     cairo_matrix_t pat_to_pdf;
3931     cairo_circle_double_t start, end;
3932     double domain[2];
3933     cairo_int_status_t status;
3934
3935     assert (pattern->n_stops != 0);
3936
3937     status = _cairo_pdf_surface_emit_pattern_stops (surface,
3938                                                     pattern,
3939                                                     &color_function,
3940                                                     &alpha_function);
3941     if (unlikely (status))
3942         return status;
3943
3944     pat_to_pdf = pattern->base.matrix;
3945     status = cairo_matrix_invert (&pat_to_pdf);
3946     /* cairo_pattern_set_matrix ensures the matrix is invertible */
3947     assert (status == CAIRO_INT_STATUS_SUCCESS);
3948     cairo_matrix_multiply (&pat_to_pdf, &pat_to_pdf, &surface->cairo_to_pdf);
3949
3950     if (pattern->base.extend == CAIRO_EXTEND_REPEAT ||
3951         pattern->base.extend == CAIRO_EXTEND_REFLECT)
3952     {
3953         double bounds_x1, bounds_x2, bounds_y1, bounds_y2;
3954         double x_scale, y_scale, tolerance;
3955
3956         /* TODO: use tighter extents */
3957         bounds_x1 = 0;
3958         bounds_y1 = 0;
3959         bounds_x2 = surface->width;
3960         bounds_y2 = surface->height;
3961         _cairo_matrix_transform_bounding_box (&pattern->base.matrix,
3962                                               &bounds_x1, &bounds_y1,
3963                                               &bounds_x2, &bounds_y2,
3964                                               NULL);
3965
3966         x_scale = surface->base.x_resolution / surface->base.x_fallback_resolution;
3967         y_scale = surface->base.y_resolution / surface->base.y_fallback_resolution;
3968
3969         tolerance = fabs (_cairo_matrix_compute_determinant (&pattern->base.matrix));
3970         tolerance /= _cairo_matrix_transformed_circle_major_axis (&pattern->base.matrix, 1);
3971         tolerance *= MIN (x_scale, y_scale);
3972
3973         _cairo_gradient_pattern_box_to_parameter (pattern,
3974                                                   bounds_x1, bounds_y1,
3975                                                   bounds_x2, bounds_y2,
3976                                                   tolerance, domain);
3977     } else if (pattern->stops[0].offset == pattern->stops[pattern->n_stops - 1].offset) {
3978         /*
3979          * If the first and the last stop offset are the same, then
3980          * the color function is a step function.
3981          * _cairo_ps_surface_emit_pattern_stops emits it as a stitched
3982          * function no matter how many stops the pattern has.  The
3983          * domain of the stitched function will be [0 1] in this case.
3984          *
3985          * This is done to avoid emitting degenerate gradients for
3986          * EXTEND_PAD patterns having a step color function.
3987          */
3988         domain[0] = 0.0;
3989         domain[1] = 1.0;
3990
3991         assert (pattern->base.extend == CAIRO_EXTEND_PAD);
3992     } else {
3993         domain[0] = pattern->stops[0].offset;
3994         domain[1] = pattern->stops[pattern->n_stops - 1].offset;
3995     }
3996
3997     /* PDF requires the first and last stop to be the same as the
3998      * extreme coordinates. For repeating patterns this moves the
3999      * extreme coordinates out to the begin/end of the repeating
4000      * function. For non repeating patterns this may move the extreme
4001      * coordinates in if there are not stops at offset 0 and 1. */
4002     _cairo_gradient_pattern_interpolate (pattern, domain[0], &start);
4003     _cairo_gradient_pattern_interpolate (pattern, domain[1], &end);
4004
4005     if (pattern->base.extend == CAIRO_EXTEND_REPEAT ||
4006         pattern->base.extend == CAIRO_EXTEND_REFLECT)
4007     {
4008         int repeat_begin, repeat_end;
4009
4010         repeat_begin = floor (domain[0]);
4011         repeat_end = ceil (domain[1]);
4012
4013         status = _cairo_pdf_surface_emit_repeating_function (surface,
4014                                                              pattern,
4015                                                              &color_function,
4016                                                              repeat_begin,
4017                                                              repeat_end);
4018         if (unlikely (status))
4019             return status;
4020
4021         if (alpha_function.id != 0) {
4022             status = _cairo_pdf_surface_emit_repeating_function (surface,
4023                                                                  pattern,
4024                                                                  &alpha_function,
4025                                                                  repeat_begin,
4026                                                                  repeat_end);
4027             if (unlikely (status))
4028                 return status;
4029         }
4030     } else if (pattern->n_stops <= 2) {
4031         /* For EXTEND_NONE and EXTEND_PAD if there are only two stops a
4032          * Type 2 function is used by itself without a stitching
4033          * function. Type 2 functions always have the domain [0 1] */
4034         domain[0] = 0.0;
4035         domain[1] = 1.0;
4036     }
4037
4038     _cairo_pdf_surface_update_object (surface, pdf_pattern->pattern_res);
4039     _cairo_pdf_surface_output_gradient (surface, pdf_pattern,
4040                                         pdf_pattern->pattern_res,
4041                                         &pat_to_pdf, &start, &end, domain,
4042                                         "/DeviceRGB", color_function);
4043
4044     if (alpha_function.id != 0) {
4045         cairo_pdf_resource_t mask_resource;
4046
4047         assert (pdf_pattern->gstate_res.id != 0);
4048
4049         /* Create pattern for SMask. */
4050         mask_resource = _cairo_pdf_surface_new_object (surface);
4051         if (mask_resource.id == 0)
4052             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
4053
4054         _cairo_pdf_surface_output_gradient (surface, pdf_pattern,
4055                                             mask_resource,
4056                                             &pat_to_pdf, &start, &end, domain,
4057                                             "/DeviceGray", alpha_function);
4058
4059         status = cairo_pdf_surface_emit_transparency_group (surface,
4060                                                             pdf_pattern,
4061                                                             pdf_pattern->gstate_res,
4062                                                             mask_resource);
4063         if (unlikely (status))
4064             return status;
4065     }
4066
4067     return _cairo_output_stream_get_status (surface->output);
4068 }
4069
4070 static cairo_int_status_t
4071 _cairo_pdf_surface_emit_mesh_pattern (cairo_pdf_surface_t    *surface,
4072                                       cairo_pdf_pattern_t    *pdf_pattern)
4073 {
4074     cairo_matrix_t pat_to_pdf;
4075     cairo_int_status_t status;
4076     cairo_pattern_t *pattern = pdf_pattern->pattern;
4077     cairo_pdf_shading_t shading;
4078     int i;
4079     cairo_pdf_resource_t res;
4080
4081     pat_to_pdf = pattern->matrix;
4082     status = cairo_matrix_invert (&pat_to_pdf);
4083     /* cairo_pattern_set_matrix ensures the matrix is invertible */
4084     assert (status == CAIRO_INT_STATUS_SUCCESS);
4085
4086     cairo_matrix_multiply (&pat_to_pdf, &pat_to_pdf, &surface->cairo_to_pdf);
4087
4088     status = _cairo_pdf_shading_init_color (&shading, (cairo_mesh_pattern_t *) pattern);
4089     if (unlikely (status))
4090         return status;
4091
4092     res = _cairo_pdf_surface_new_object (surface);
4093     if (unlikely (res.id == 0))
4094         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
4095
4096     _cairo_output_stream_printf (surface->output,
4097                                  "%d 0 obj\n"
4098                                  "<< /ShadingType %d\n"
4099                                  "   /ColorSpace /DeviceRGB\n"
4100                                  "   /BitsPerCoordinate %d\n"
4101                                  "   /BitsPerComponent %d\n"
4102                                  "   /BitsPerFlag %d\n"
4103                                  "   /Decode [",
4104                                  res.id,
4105                                  shading.shading_type,
4106                                  shading.bits_per_coordinate,
4107                                  shading.bits_per_component,
4108                                  shading.bits_per_flag);
4109
4110     for (i = 0; i < shading.decode_array_length; i++)
4111         _cairo_output_stream_printf (surface->output, "%f ", shading.decode_array[i]);
4112
4113     _cairo_output_stream_printf (surface->output,
4114                                  "]\n"
4115                                  "   /Length %ld\n"
4116                                  ">>\n"
4117                                  "stream\n",
4118                                  shading.data_length);
4119
4120     _cairo_output_stream_write (surface->output, shading.data, shading.data_length);
4121
4122     _cairo_output_stream_printf (surface->output,
4123                                  "\nendstream\n"
4124                                  "endobj\n");
4125
4126     _cairo_pdf_shading_fini (&shading);
4127
4128     _cairo_pdf_surface_update_object (surface, pdf_pattern->pattern_res);
4129     _cairo_output_stream_printf (surface->output,
4130                                  "%d 0 obj\n"
4131                                  "<< /Type /Pattern\n"
4132                                  "   /PatternType 2\n"
4133                                  "   /Matrix [ ",
4134                                  pdf_pattern->pattern_res.id);
4135     _cairo_output_stream_print_matrix (surface->output, &pat_to_pdf);
4136     _cairo_output_stream_printf (surface->output,
4137                                  " ]\n"
4138                                  "   /Shading %d 0 R\n"
4139                                  ">>\n"
4140                                  "endobj\n",
4141                                  res.id);
4142
4143     if (pdf_pattern->gstate_res.id != 0) {
4144         cairo_pdf_resource_t mask_resource;
4145
4146         /* Create pattern for SMask. */
4147         res = _cairo_pdf_surface_new_object (surface);
4148         if (unlikely (res.id == 0))
4149             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
4150
4151         status = _cairo_pdf_shading_init_alpha (&shading, (cairo_mesh_pattern_t *) pattern);
4152         if (unlikely (status))
4153             return status;
4154
4155         _cairo_output_stream_printf (surface->output,
4156                                  "%d 0 obj\n"
4157                                  "<< /ShadingType %d\n"
4158                                  "   /ColorSpace /DeviceGray\n"
4159                                  "   /BitsPerCoordinate %d\n"
4160                                  "   /BitsPerComponent %d\n"
4161                                  "   /BitsPerFlag %d\n"
4162                                  "   /Decode [",
4163                                  res.id,
4164                                  shading.shading_type,
4165                                  shading.bits_per_coordinate,
4166                                  shading.bits_per_component,
4167                                  shading.bits_per_flag);
4168
4169         for (i = 0; i < shading.decode_array_length; i++)
4170             _cairo_output_stream_printf (surface->output, "%f ", shading.decode_array[i]);
4171
4172         _cairo_output_stream_printf (surface->output,
4173                                      "]\n"
4174                                      "   /Length %ld\n"
4175                                      ">>\n"
4176                                      "stream\n",
4177                                      shading.data_length);
4178
4179         _cairo_output_stream_write (surface->output, shading.data, shading.data_length);
4180
4181         _cairo_output_stream_printf (surface->output,
4182                                      "\nendstream\n"
4183                                      "endobj\n");
4184         _cairo_pdf_shading_fini (&shading);
4185
4186         mask_resource = _cairo_pdf_surface_new_object (surface);
4187         if (unlikely (mask_resource.id == 0))
4188             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
4189
4190         _cairo_output_stream_printf (surface->output,
4191                                      "%d 0 obj\n"
4192                                      "<< /Type /Pattern\n"
4193                                      "   /PatternType 2\n"
4194                                      "   /Matrix [ ",
4195                                      mask_resource.id);
4196         _cairo_output_stream_print_matrix (surface->output, &pat_to_pdf);
4197         _cairo_output_stream_printf (surface->output,
4198                                      " ]\n"
4199                                      "   /Shading %d 0 R\n"
4200                                      ">>\n"
4201                                      "endobj\n",
4202                                      res.id);
4203
4204         status = cairo_pdf_surface_emit_transparency_group (surface,
4205                                                             pdf_pattern,
4206                                                             pdf_pattern->gstate_res,
4207                                                             mask_resource);
4208         if (unlikely (status))
4209             return status;
4210     }
4211
4212     return _cairo_output_stream_get_status (surface->output);
4213 }
4214
4215 static cairo_int_status_t
4216 _cairo_pdf_surface_emit_pattern (cairo_pdf_surface_t *surface, cairo_pdf_pattern_t *pdf_pattern)
4217 {
4218     double old_width, old_height;
4219     cairo_int_status_t status;
4220
4221     old_width = surface->width;
4222     old_height = surface->height;
4223     _cairo_pdf_surface_set_size_internal (surface,
4224                                           pdf_pattern->width,
4225                                           pdf_pattern->height);
4226
4227     switch (pdf_pattern->pattern->type) {
4228     case CAIRO_PATTERN_TYPE_SOLID:
4229         ASSERT_NOT_REACHED;
4230         status = _cairo_error (CAIRO_STATUS_PATTERN_TYPE_MISMATCH);
4231         break;
4232
4233     case CAIRO_PATTERN_TYPE_SURFACE:
4234     case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
4235         status = _cairo_pdf_surface_emit_surface_pattern (surface, pdf_pattern);
4236         break;
4237
4238     case CAIRO_PATTERN_TYPE_LINEAR:
4239     case CAIRO_PATTERN_TYPE_RADIAL:
4240         status = _cairo_pdf_surface_emit_gradient (surface, pdf_pattern);
4241         break;
4242
4243     case CAIRO_PATTERN_TYPE_MESH:
4244         status = _cairo_pdf_surface_emit_mesh_pattern (surface, pdf_pattern);
4245         break;
4246
4247     default:
4248         ASSERT_NOT_REACHED;
4249         status = _cairo_error (CAIRO_STATUS_PATTERN_TYPE_MISMATCH);
4250         break;
4251     }
4252
4253     _cairo_pdf_surface_set_size_internal (surface,
4254                                           old_width,
4255                                           old_height);
4256
4257     return status;
4258 }
4259
4260 static cairo_int_status_t
4261 _cairo_pdf_surface_paint_surface_pattern (cairo_pdf_surface_t          *surface,
4262                                           cairo_operator_t              op,
4263                                           const cairo_pattern_t        *source,
4264                                           const cairo_rectangle_int_t  *extents,
4265                                           cairo_pdf_resource_t         *smask_res,
4266                                           cairo_bool_t                  stencil_mask)
4267 {
4268     cairo_pdf_resource_t surface_res;
4269     int width, height;
4270     cairo_matrix_t cairo_p2d, pdf_p2d;
4271     cairo_int_status_t status;
4272     int alpha;
4273     cairo_rectangle_int_t extents2;
4274     double x_offset;
4275     double y_offset;
4276
4277     if (source->extend == CAIRO_EXTEND_PAD &&
4278         !(source->type == CAIRO_PATTERN_TYPE_SURFACE &&
4279           ((cairo_surface_pattern_t *)source)->surface->type == CAIRO_SURFACE_TYPE_RECORDING))
4280     {
4281         status = _cairo_pdf_surface_add_padded_image_surface (surface,
4282                                                               source,
4283                                                               extents,
4284                                                               &surface_res,
4285                                                               &width,
4286                                                               &height,
4287                                                               &x_offset,
4288                                                               &y_offset);
4289     } else {
4290         status = _cairo_pdf_surface_add_source_surface (surface,
4291                                                         NULL,
4292                                                         source,
4293                                                         op,
4294                                                         source->filter,
4295                                                         stencil_mask,
4296                                                         FALSE,
4297                                                         extents,
4298                                                         smask_res,
4299                                                         &surface_res,
4300                                                         &width,
4301                                                         &height,
4302                                                         &x_offset,
4303                                                         &y_offset,
4304                                                         &extents2);
4305     }
4306     if (unlikely (status))
4307         return status;
4308
4309     cairo_p2d = source->matrix;
4310     status = cairo_matrix_invert (&cairo_p2d);
4311     /* cairo_pattern_set_matrix ensures the matrix is invertible */
4312     assert (status == CAIRO_INT_STATUS_SUCCESS);
4313
4314     pdf_p2d = surface->cairo_to_pdf;
4315     cairo_matrix_multiply (&pdf_p2d, &cairo_p2d, &pdf_p2d);
4316     cairo_matrix_translate (&pdf_p2d, x_offset, y_offset);
4317     cairo_matrix_translate (&pdf_p2d, 0.0, height);
4318     cairo_matrix_scale (&pdf_p2d, 1.0, -1.0);
4319     if (!(source->type == CAIRO_PATTERN_TYPE_SURFACE &&
4320           ((cairo_surface_pattern_t *)source)->surface->type == CAIRO_SURFACE_TYPE_RECORDING))
4321     {
4322         cairo_matrix_scale (&pdf_p2d, width, height);
4323     }
4324
4325     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
4326     if (unlikely (status))
4327         return status;
4328
4329     if (! _cairo_matrix_is_identity (&pdf_p2d)) {
4330         _cairo_output_stream_print_matrix (surface->output, &pdf_p2d);
4331         _cairo_output_stream_printf (surface->output, " cm\n");
4332     }
4333
4334     status = _cairo_pdf_surface_add_alpha (surface, 1.0, &alpha);
4335     if (unlikely (status))
4336         return status;
4337
4338     if (stencil_mask) {
4339         _cairo_output_stream_printf (surface->output,
4340                                      "/x%d Do\n",
4341                                      surface_res.id);
4342     } else {
4343         _cairo_output_stream_printf (surface->output,
4344                                      "/a%d gs /x%d Do\n",
4345                                      alpha,
4346                                      surface_res.id);
4347     }
4348
4349     return _cairo_pdf_surface_add_xobject (surface, surface_res);
4350 }
4351
4352 static cairo_int_status_t
4353 _cairo_pdf_surface_paint_gradient (cairo_pdf_surface_t         *surface,
4354                                    cairo_operator_t             op,
4355                                    const cairo_pattern_t       *source,
4356                                    const cairo_rectangle_int_t *extents)
4357 {
4358     cairo_pdf_resource_t shading_res, gstate_res;
4359     cairo_matrix_t pat_to_pdf;
4360     cairo_int_status_t status;
4361     int alpha;
4362
4363     status = _cairo_pdf_surface_add_pdf_shading (surface, source,
4364                                                  op, extents,
4365                                                  &shading_res, &gstate_res);
4366     if (unlikely (status == CAIRO_INT_STATUS_NOTHING_TO_DO))
4367         return CAIRO_INT_STATUS_SUCCESS;
4368     if (unlikely (status))
4369         return status;
4370
4371     pat_to_pdf = source->matrix;
4372     status = cairo_matrix_invert (&pat_to_pdf);
4373     /* cairo_pattern_set_matrix ensures the matrix is invertible */
4374     assert (status == CAIRO_INT_STATUS_SUCCESS);
4375     cairo_matrix_multiply (&pat_to_pdf, &pat_to_pdf, &surface->cairo_to_pdf);
4376
4377     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
4378     if (unlikely (status))
4379         return status;
4380
4381     if (! _cairo_matrix_is_identity (&pat_to_pdf)) {
4382         _cairo_output_stream_print_matrix (surface->output, &pat_to_pdf);
4383         _cairo_output_stream_printf (surface->output, " cm\n");
4384     }
4385
4386     status = _cairo_pdf_surface_add_shading (surface, shading_res);
4387     if (unlikely (status))
4388         return status;
4389
4390     if (gstate_res.id != 0) {
4391         status = _cairo_pdf_surface_add_smask (surface, gstate_res);
4392         if (unlikely (status))
4393             return status;
4394
4395         _cairo_output_stream_printf (surface->output,
4396                                      "/s%d gs /sh%d sh\n",
4397                                      gstate_res.id,
4398                                      shading_res.id);
4399     } else {
4400         status = _cairo_pdf_surface_add_alpha (surface, 1.0, &alpha);
4401         if (unlikely (status))
4402             return status;
4403
4404         _cairo_output_stream_printf (surface->output,
4405                                      "/a%d gs /sh%d sh\n",
4406                                      alpha,
4407                                      shading_res.id);
4408     }
4409
4410     return status;
4411 }
4412
4413 static cairo_int_status_t
4414 _cairo_pdf_surface_paint_pattern (cairo_pdf_surface_t          *surface,
4415                                   cairo_operator_t              op,
4416                                   const cairo_pattern_t        *source,
4417                                   const cairo_rectangle_int_t  *extents,
4418                                   cairo_bool_t                  mask)
4419 {
4420     switch (source->type) {
4421     case CAIRO_PATTERN_TYPE_SURFACE:
4422     case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
4423         return _cairo_pdf_surface_paint_surface_pattern (surface,
4424                                                          op,
4425                                                          source,
4426                                                          extents,
4427                                                          NULL,
4428                                                          mask);
4429     case CAIRO_PATTERN_TYPE_LINEAR:
4430     case CAIRO_PATTERN_TYPE_RADIAL:
4431     case CAIRO_PATTERN_TYPE_MESH:
4432         return _cairo_pdf_surface_paint_gradient (surface,
4433                                                   op,
4434                                                   source,
4435                                                   extents);
4436
4437     case CAIRO_PATTERN_TYPE_SOLID:
4438     default:
4439         ASSERT_NOT_REACHED;
4440         return CAIRO_STATUS_SUCCESS;
4441     }
4442 }
4443
4444 static cairo_bool_t
4445 _can_paint_pattern (const cairo_pattern_t *pattern)
4446 {
4447     switch (pattern->type) {
4448     case CAIRO_PATTERN_TYPE_SOLID:
4449         return FALSE;
4450
4451     case CAIRO_PATTERN_TYPE_SURFACE:
4452     case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
4453         return (pattern->extend == CAIRO_EXTEND_NONE ||
4454                 pattern->extend == CAIRO_EXTEND_PAD);
4455
4456     case CAIRO_PATTERN_TYPE_LINEAR:
4457     case CAIRO_PATTERN_TYPE_RADIAL:
4458         return TRUE;
4459
4460     case CAIRO_PATTERN_TYPE_MESH:
4461         return FALSE;
4462
4463     default:
4464         ASSERT_NOT_REACHED;
4465         return FALSE;
4466     }
4467 }
4468
4469 static cairo_int_status_t
4470 _cairo_pdf_surface_select_operator (cairo_pdf_surface_t *surface,
4471                                     cairo_operator_t     op)
4472 {
4473     cairo_int_status_t status;
4474
4475     if (op == surface->current_operator)
4476         return CAIRO_STATUS_SUCCESS;
4477
4478     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
4479     if (unlikely (status))
4480         return status;
4481
4482     _cairo_output_stream_printf (surface->output,
4483                                  "/b%d gs\n", op);
4484     surface->current_operator = op;
4485     _cairo_pdf_surface_add_operator (surface, op);
4486
4487     return CAIRO_STATUS_SUCCESS;
4488 }
4489
4490 static cairo_int_status_t
4491 _cairo_pdf_surface_select_pattern (cairo_pdf_surface_t *surface,
4492                                    const cairo_pattern_t     *pattern,
4493                                    cairo_pdf_resource_t pattern_res,
4494                                    cairo_bool_t         is_stroke)
4495 {
4496     cairo_int_status_t status;
4497     int alpha;
4498     const cairo_color_t *solid_color = NULL;
4499
4500     if (pattern->type == CAIRO_PATTERN_TYPE_SOLID) {
4501         const cairo_solid_pattern_t *solid = (const cairo_solid_pattern_t *) pattern;
4502
4503         solid_color = &solid->color;
4504     }
4505
4506     if (solid_color != NULL) {
4507         if (surface->current_pattern_is_solid_color == FALSE ||
4508             surface->current_color_red != solid_color->red ||
4509             surface->current_color_green != solid_color->green ||
4510             surface->current_color_blue != solid_color->blue ||
4511             surface->current_color_is_stroke != is_stroke)
4512         {
4513             status = _cairo_pdf_operators_flush (&surface->pdf_operators);
4514             if (unlikely (status))
4515                 return status;
4516
4517             _cairo_output_stream_printf (surface->output,
4518                                          "%f %f %f ",
4519                                          solid_color->red,
4520                                          solid_color->green,
4521                                          solid_color->blue);
4522
4523             if (is_stroke)
4524                 _cairo_output_stream_printf (surface->output, "RG ");
4525             else
4526                 _cairo_output_stream_printf (surface->output, "rg ");
4527
4528             surface->current_color_red = solid_color->red;
4529             surface->current_color_green = solid_color->green;
4530             surface->current_color_blue = solid_color->blue;
4531             surface->current_color_is_stroke = is_stroke;
4532         }
4533
4534         if (surface->current_pattern_is_solid_color == FALSE ||
4535             surface->current_color_alpha != solid_color->alpha)
4536         {
4537             status = _cairo_pdf_surface_add_alpha (surface, solid_color->alpha, &alpha);
4538             if (unlikely (status))
4539                 return status;
4540
4541             status = _cairo_pdf_operators_flush (&surface->pdf_operators);
4542             if (unlikely (status))
4543                 return status;
4544
4545             _cairo_output_stream_printf (surface->output,
4546                                          "/a%d gs\n",
4547                                          alpha);
4548             surface->current_color_alpha = solid_color->alpha;
4549         }
4550
4551         surface->current_pattern_is_solid_color = TRUE;
4552     } else {
4553         status = _cairo_pdf_surface_add_alpha (surface, 1.0, &alpha);
4554         if (unlikely (status))
4555             return status;
4556
4557         status = _cairo_pdf_surface_add_pattern (surface, pattern_res);
4558         if (unlikely (status))
4559             return status;
4560
4561         status = _cairo_pdf_operators_flush (&surface->pdf_operators);
4562         if (unlikely (status))
4563             return status;
4564
4565         /* fill-stroke calls select_pattern twice. Don't save if the
4566          * gstate is already saved. */
4567         if (!surface->select_pattern_gstate_saved)
4568             _cairo_output_stream_printf (surface->output, "q ");
4569
4570         if (is_stroke) {
4571             _cairo_output_stream_printf (surface->output,
4572                                          "/Pattern CS /p%d SCN ",
4573                                          pattern_res.id);
4574         } else {
4575             _cairo_output_stream_printf (surface->output,
4576                                          "/Pattern cs /p%d scn ",
4577                                          pattern_res.id);
4578         }
4579         _cairo_output_stream_printf (surface->output,
4580                                      "/a%d gs\n",
4581                                      alpha);
4582         surface->select_pattern_gstate_saved = TRUE;
4583         surface->current_pattern_is_solid_color = FALSE;
4584     }
4585
4586     return _cairo_output_stream_get_status (surface->output);
4587 }
4588
4589 static cairo_int_status_t
4590 _cairo_pdf_surface_unselect_pattern (cairo_pdf_surface_t *surface)
4591 {
4592     cairo_int_status_t status;
4593
4594     if (surface->select_pattern_gstate_saved) {
4595         status = _cairo_pdf_operators_flush (&surface->pdf_operators);
4596         if (unlikely (status))
4597             return status;
4598
4599         _cairo_output_stream_printf (surface->output, "Q\n");
4600         _cairo_pdf_operators_reset (&surface->pdf_operators);
4601         surface->current_pattern_is_solid_color = FALSE;
4602     }
4603     surface->select_pattern_gstate_saved = FALSE;
4604
4605     return CAIRO_STATUS_SUCCESS;
4606 }
4607
4608 static cairo_int_status_t
4609 _cairo_pdf_surface_show_page (void *abstract_surface)
4610 {
4611     cairo_pdf_surface_t *surface = abstract_surface;
4612     cairo_int_status_t status;
4613
4614     status = _cairo_pdf_surface_close_content_stream (surface);
4615     if (unlikely (status))
4616         return status;
4617
4618     _cairo_surface_clipper_reset (&surface->clipper);
4619
4620     status = _cairo_pdf_surface_write_page (surface);
4621     if (unlikely (status))
4622         return status;
4623
4624     _cairo_pdf_surface_clear (surface);
4625
4626     return CAIRO_STATUS_SUCCESS;
4627 }
4628
4629 static cairo_bool_t
4630 _cairo_pdf_surface_get_extents (void                    *abstract_surface,
4631                                 cairo_rectangle_int_t   *rectangle)
4632 {
4633     cairo_pdf_surface_t *surface = abstract_surface;
4634
4635     rectangle->x = 0;
4636     rectangle->y = 0;
4637
4638     /* XXX: The conversion to integers here is pretty bogus, (not to
4639      * mention the arbitrary limitation of width to a short(!). We
4640      * may need to come up with a better interface for get_size.
4641      */
4642     rectangle->width  = ceil (surface->width);
4643     rectangle->height = ceil (surface->height);
4644
4645     return TRUE;
4646 }
4647
4648 static void
4649 _cairo_pdf_surface_get_font_options (void                  *abstract_surface,
4650                                      cairo_font_options_t  *options)
4651 {
4652     _cairo_font_options_init_default (options);
4653
4654     cairo_font_options_set_hint_style (options, CAIRO_HINT_STYLE_NONE);
4655     cairo_font_options_set_hint_metrics (options, CAIRO_HINT_METRICS_OFF);
4656     cairo_font_options_set_antialias (options, CAIRO_ANTIALIAS_GRAY);
4657     _cairo_font_options_set_round_glyph_positions (options, CAIRO_ROUND_GLYPH_POS_OFF);
4658 }
4659
4660 static cairo_pdf_resource_t
4661 _cairo_pdf_surface_write_info (cairo_pdf_surface_t *surface)
4662 {
4663     cairo_pdf_resource_t info;
4664
4665     info = _cairo_pdf_surface_new_object (surface);
4666     if (info.id == 0)
4667         return info;
4668
4669     _cairo_output_stream_printf (surface->output,
4670                                  "%d 0 obj\n"
4671                                  "<< /Creator (cairo %s (http://cairographics.org))\n"
4672                                  "   /Producer (cairo %s (http://cairographics.org))\n"
4673                                  ">>\n"
4674                                  "endobj\n",
4675                                  info.id,
4676                                  cairo_version_string (),
4677                                  cairo_version_string ());
4678
4679     return info;
4680 }
4681
4682 static void
4683 _cairo_pdf_surface_write_pages (cairo_pdf_surface_t *surface)
4684 {
4685     cairo_pdf_resource_t page;
4686     int num_pages, i;
4687
4688     _cairo_pdf_surface_update_object (surface, surface->pages_resource);
4689     _cairo_output_stream_printf (surface->output,
4690                                  "%d 0 obj\n"
4691                                  "<< /Type /Pages\n"
4692                                  "   /Kids [ ",
4693                                  surface->pages_resource.id);
4694
4695     num_pages = _cairo_array_num_elements (&surface->pages);
4696     for (i = 0; i < num_pages; i++) {
4697         _cairo_array_copy_element (&surface->pages, i, &page);
4698         _cairo_output_stream_printf (surface->output, "%d 0 R ", page.id);
4699     }
4700
4701     _cairo_output_stream_printf (surface->output, "]\n");
4702     _cairo_output_stream_printf (surface->output, "   /Count %d\n", num_pages);
4703
4704
4705     /* TODO: Figure out which other defaults to be inherited by /Page
4706      * objects. */
4707     _cairo_output_stream_printf (surface->output,
4708                                  ">>\n"
4709                                  "endobj\n");
4710 }
4711
4712 static cairo_int_status_t
4713 _utf8_to_pdf_string (const char *utf8, char **str_out)
4714 {
4715     int i;
4716     int len;
4717     cairo_bool_t ascii;
4718     char *str;
4719     cairo_int_status_t status = CAIRO_STATUS_SUCCESS;
4720
4721     ascii = TRUE;
4722     len = strlen (utf8);
4723     for (i = 0; i < len; i++) {
4724         unsigned c = utf8[i];
4725         if (c < 32 || c > 126 || c == '(' || c == ')' || c == '\\') {
4726             ascii = FALSE;
4727             break;
4728         }
4729     }
4730
4731     if (ascii) {
4732         str = malloc (len + 3);
4733         if (str == NULL)
4734             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
4735
4736         str[0] = '(';
4737         for (i = 0; i < len; i++)
4738             str[i+1] = utf8[i];
4739         str[i+1] = ')';
4740         str[i+2] = 0;
4741     } else {
4742         uint16_t *utf16 = NULL;
4743         int utf16_len = 0;
4744
4745         status = _cairo_utf8_to_utf16 (utf8, -1, &utf16, &utf16_len);
4746         if (unlikely (status))
4747             return status;
4748
4749         str = malloc (utf16_len*4 + 7);
4750         if (str == NULL) {
4751             free (utf16);
4752             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
4753         }
4754
4755         strcpy (str, "<FEFF");
4756         for (i = 0; i < utf16_len; i++)
4757             snprintf (str + 4*i + 5, 5, "%04X", utf16[i]);
4758
4759         strcat (str, ">");
4760         free (utf16);
4761     }
4762     *str_out = str;
4763
4764     return status;
4765 }
4766
4767 static cairo_int_status_t
4768 _cairo_pdf_surface_emit_unicode_for_glyph (cairo_pdf_surface_t  *surface,
4769                                            const char           *utf8)
4770 {
4771     uint16_t *utf16 = NULL;
4772     int utf16_len = 0;
4773     cairo_int_status_t status;
4774     int i;
4775
4776     if (utf8 && *utf8) {
4777         status = _cairo_utf8_to_utf16 (utf8, -1, &utf16, &utf16_len);
4778         if (unlikely (status))
4779             return status;
4780     }
4781
4782     _cairo_output_stream_printf (surface->output, "<");
4783     if (utf16 == NULL || utf16_len == 0) {
4784         /* According to the "ToUnicode Mapping File Tutorial"
4785          * http://www.adobe.com/devnet/acrobat/pdfs/5411.ToUnicode.pdf
4786          *
4787          * Glyphs that do not map to a Unicode code point must be
4788          * mapped to 0xfffd "REPLACEMENT CHARACTER".
4789          */
4790         _cairo_output_stream_printf (surface->output,
4791                                      "fffd");
4792     } else {
4793         for (i = 0; i < utf16_len; i++)
4794             _cairo_output_stream_printf (surface->output,
4795                                          "%04x", (int) (utf16[i]));
4796     }
4797     _cairo_output_stream_printf (surface->output, ">");
4798
4799     free (utf16);
4800
4801     return CAIRO_STATUS_SUCCESS;
4802 }
4803
4804 /* Bob Jenkins hash
4805  *
4806  * Public domain code from:
4807  *   http://burtleburtle.net/bob/hash/doobs.html
4808  */
4809
4810 #define HASH_MIX(a,b,c)                 \
4811 {                                       \
4812     a -= b; a -= c; a ^= (c>>13);       \
4813     b -= c; b -= a; b ^= (a<<8);        \
4814     c -= a; c -= b; c ^= (b>>13);       \
4815     a -= b; a -= c; a ^= (c>>12);       \
4816     b -= c; b -= a; b ^= (a<<16);       \
4817     c -= a; c -= b; c ^= (b>>5);        \
4818     a -= b; a -= c; a ^= (c>>3);        \
4819     b -= c; b -= a; b ^= (a<<10);       \
4820     c -= a; c -= b; c ^= (b>>15);       \
4821 }
4822
4823 static uint32_t
4824 _hash_data (const unsigned char *data, int length, uint32_t initval)
4825 {
4826     uint32_t a, b, c, len;
4827
4828     len = length;
4829     a = b = 0x9e3779b9;  /* the golden ratio; an arbitrary value */
4830     c = initval;         /* the previous hash value */
4831
4832     while (len >= 12) {
4833         a += (data[0] + ((uint32_t)data[1]<<8) + ((uint32_t)data[2]<<16) + ((uint32_t)data[3]<<24));
4834         b += (data[4] + ((uint32_t)data[5]<<8) + ((uint32_t)data[6]<<16) + ((uint32_t)data[7]<<24));
4835         c += (data[8] + ((uint32_t)data[9]<<8) + ((uint32_t)data[10]<<16)+ ((uint32_t)data[11]<<24));
4836         HASH_MIX (a,b,c);
4837         data += 12;
4838         len -= 12;
4839     }
4840
4841     c += length;
4842     switch(len) {
4843     case 11: c+= ((uint32_t) data[10] << 24);
4844     case 10: c+= ((uint32_t) data[9] << 16);
4845     case 9 : c+= ((uint32_t) data[8] << 8);
4846     case 8 : b+= ((uint32_t) data[7] << 24);
4847     case 7 : b+= ((uint32_t) data[6] << 16);
4848     case 6 : b+= ((uint32_t) data[5] << 8);
4849     case 5 : b+= data[4];
4850     case 4 : a+= ((uint32_t) data[3] << 24);
4851     case 3 : a+= ((uint32_t) data[2] << 16);
4852     case 2 : a+= ((uint32_t) data[1] << 8);
4853     case 1 : a+= data[0];
4854     }
4855     HASH_MIX (a,b,c);
4856
4857     return c;
4858 }
4859
4860 static void
4861 _create_font_subset_tag (cairo_scaled_font_subset_t     *font_subset,
4862                          const char                     *font_name,
4863                          char                           *tag)
4864 {
4865     uint32_t hash;
4866     int i;
4867     long numerator;
4868     ldiv_t d;
4869
4870     hash = _hash_data ((unsigned char *) font_name, strlen(font_name), 0);
4871     hash = _hash_data ((unsigned char *) (font_subset->glyphs),
4872                        font_subset->num_glyphs * sizeof(unsigned long), hash);
4873
4874     numerator = abs (hash);
4875     for (i = 0; i < 6; i++) {
4876         d = ldiv (numerator, 26);
4877         numerator = d.quot;
4878         tag[i] = 'A' + d.rem;
4879     }
4880     tag[i] = 0;
4881 }
4882
4883 static cairo_int_status_t
4884 _cairo_pdf_surface_emit_to_unicode_stream (cairo_pdf_surface_t          *surface,
4885                                            cairo_scaled_font_subset_t   *font_subset,
4886                                            cairo_pdf_resource_t         *stream)
4887 {
4888     unsigned int i, num_bfchar;
4889     cairo_int_status_t status;
4890
4891     stream->id = 0;
4892
4893     status = _cairo_pdf_surface_open_stream (surface,
4894                                               NULL,
4895                                               surface->compress_content,
4896                                               NULL);
4897     if (unlikely (status))
4898         return status;
4899
4900     _cairo_output_stream_printf (surface->output,
4901                                  "/CIDInit /ProcSet findresource begin\n"
4902                                  "12 dict begin\n"
4903                                  "begincmap\n"
4904                                  "/CIDSystemInfo\n"
4905                                  "<< /Registry (Adobe)\n"
4906                                  "   /Ordering (UCS)\n"
4907                                  "   /Supplement 0\n"
4908                                  ">> def\n"
4909                                  "/CMapName /Adobe-Identity-UCS def\n"
4910                                  "/CMapType 2 def\n"
4911                                  "1 begincodespacerange\n");
4912
4913     if (font_subset->is_composite && !font_subset->is_latin) {
4914         _cairo_output_stream_printf (surface->output,
4915                                      "<0000> <ffff>\n");
4916     } else {
4917         _cairo_output_stream_printf (surface->output,
4918                                      "<00> <ff>\n");
4919     }
4920
4921     _cairo_output_stream_printf (surface->output,
4922                                   "endcodespacerange\n");
4923
4924     if (font_subset->is_scaled) {
4925         /* Type 3 fonts include glyph 0 in the subset */
4926         num_bfchar = font_subset->num_glyphs;
4927
4928         /* The CMap specification has a limit of 100 characters per beginbfchar operator */
4929         _cairo_output_stream_printf (surface->output,
4930                                      "%d beginbfchar\n",
4931                                      num_bfchar > 100 ? 100 : num_bfchar);
4932
4933         for (i = 0; i < num_bfchar; i++) {
4934             if (i != 0 && i % 100 == 0) {
4935                 _cairo_output_stream_printf (surface->output,
4936                                              "endbfchar\n"
4937                                              "%d beginbfchar\n",
4938                                              num_bfchar - i > 100 ? 100 : num_bfchar - i);
4939             }
4940             _cairo_output_stream_printf (surface->output, "<%02x> ", i);
4941             status = _cairo_pdf_surface_emit_unicode_for_glyph (surface,
4942                                                                 font_subset->utf8[i]);
4943             if (unlikely (status))
4944                 return status;
4945
4946             _cairo_output_stream_printf (surface->output,
4947                                          "\n");
4948         }
4949     } else {
4950         /* Other fonts reserve glyph 0 for .notdef. Omit glyph 0 from the /ToUnicode map */
4951         num_bfchar = font_subset->num_glyphs - 1;
4952
4953         /* The CMap specification has a limit of 100 characters per beginbfchar operator */
4954         _cairo_output_stream_printf (surface->output,
4955                                      "%d beginbfchar\n",
4956                                      num_bfchar > 100 ? 100 : num_bfchar);
4957
4958         for (i = 0; i < num_bfchar; i++) {
4959             if (i != 0 && i % 100 == 0) {
4960                 _cairo_output_stream_printf (surface->output,
4961                                              "endbfchar\n"
4962                                              "%d beginbfchar\n",
4963                                              num_bfchar - i > 100 ? 100 : num_bfchar - i);
4964             }
4965             if (font_subset->is_latin)
4966                 _cairo_output_stream_printf (surface->output, "<%02x> ", font_subset->to_latin_char[i + 1]);
4967             else if (font_subset->is_composite)
4968                 _cairo_output_stream_printf (surface->output, "<%04x> ", i + 1);
4969             else
4970                 _cairo_output_stream_printf (surface->output, "<%02x> ", i + 1);
4971
4972             status = _cairo_pdf_surface_emit_unicode_for_glyph (surface,
4973                                                                 font_subset->utf8[i + 1]);
4974             if (unlikely (status))
4975                 return status;
4976
4977             _cairo_output_stream_printf (surface->output,
4978                                          "\n");
4979         }
4980     }
4981
4982     _cairo_output_stream_printf (surface->output,
4983                                  "endbfchar\n");
4984
4985     _cairo_output_stream_printf (surface->output,
4986                                  "endcmap\n"
4987                                  "CMapName currentdict /CMap defineresource pop\n"
4988                                  "end\n"
4989                                  "end\n");
4990
4991     *stream = surface->pdf_stream.self;
4992     return _cairo_pdf_surface_close_stream (surface);
4993 }
4994
4995 #define PDF_UNITS_PER_EM 1000
4996
4997 static cairo_int_status_t
4998 _cairo_pdf_surface_emit_cff_font (cairo_pdf_surface_t           *surface,
4999                                   cairo_scaled_font_subset_t    *font_subset,
5000                                   cairo_cff_subset_t            *subset)
5001 {
5002     cairo_pdf_resource_t stream, descriptor, cidfont_dict;
5003     cairo_pdf_resource_t subset_resource, to_unicode_stream;
5004     cairo_pdf_font_t font;
5005     unsigned int i, last_glyph;
5006     cairo_int_status_t status;
5007     char tag[10];
5008
5009     _create_font_subset_tag (font_subset, subset->ps_name, tag);
5010
5011     subset_resource = _cairo_pdf_surface_get_font_resource (surface,
5012                                                             font_subset->font_id,
5013                                                             font_subset->subset_id);
5014     if (subset_resource.id == 0)
5015         return CAIRO_STATUS_SUCCESS;
5016
5017     status = _cairo_pdf_surface_open_stream (surface,
5018                                              NULL,
5019                                              TRUE,
5020                                              font_subset->is_latin ?
5021                                              "   /Subtype /Type1C\n" :
5022                                              "   /Subtype /CIDFontType0C\n");
5023     if (unlikely (status))
5024         return status;
5025
5026     stream = surface->pdf_stream.self;
5027     _cairo_output_stream_write (surface->output,
5028                                 subset->data, subset->data_length);
5029     status = _cairo_pdf_surface_close_stream (surface);
5030     if (unlikely (status))
5031         return status;
5032
5033     status = _cairo_pdf_surface_emit_to_unicode_stream (surface,
5034                                                         font_subset,
5035                                                         &to_unicode_stream);
5036     if (_cairo_int_status_is_error (status))
5037         return status;
5038
5039     descriptor = _cairo_pdf_surface_new_object (surface);
5040     if (descriptor.id == 0)
5041         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5042
5043     _cairo_output_stream_printf (surface->output,
5044                                  "%d 0 obj\n"
5045                                  "<< /Type /FontDescriptor\n"
5046                                  "   /FontName /%s+%s\n",
5047                                  descriptor.id,
5048                                  tag,
5049                                  subset->ps_name);
5050
5051     if (subset->family_name_utf8) {
5052         char *pdf_str;
5053
5054         status = _utf8_to_pdf_string (subset->family_name_utf8, &pdf_str);
5055         if (unlikely (status))
5056             return status;
5057
5058         _cairo_output_stream_printf (surface->output,
5059                                      "   /FontFamily %s\n",
5060                                      pdf_str);
5061         free (pdf_str);
5062     }
5063
5064     _cairo_output_stream_printf (surface->output,
5065                                  "   /Flags 4\n"
5066                                  "   /FontBBox [ %ld %ld %ld %ld ]\n"
5067                                  "   /ItalicAngle 0\n"
5068                                  "   /Ascent %ld\n"
5069                                  "   /Descent %ld\n"
5070                                  "   /CapHeight %ld\n"
5071                                  "   /StemV 80\n"
5072                                  "   /StemH 80\n"
5073                                  "   /FontFile3 %u 0 R\n"
5074                                  ">>\n"
5075                                  "endobj\n",
5076                                  (long)(subset->x_min*PDF_UNITS_PER_EM),
5077                                  (long)(subset->y_min*PDF_UNITS_PER_EM),
5078                                  (long)(subset->x_max*PDF_UNITS_PER_EM),
5079                                  (long)(subset->y_max*PDF_UNITS_PER_EM),
5080                                  (long)(subset->ascent*PDF_UNITS_PER_EM),
5081                                  (long)(subset->descent*PDF_UNITS_PER_EM),
5082                                  (long)(subset->y_max*PDF_UNITS_PER_EM),
5083                                  stream.id);
5084
5085     if (font_subset->is_latin) {
5086         /* find last glyph used */
5087         for (i = 255; i >= 32; i--)
5088             if (font_subset->latin_to_subset_glyph_index[i] > 0)
5089                 break;
5090
5091         last_glyph = i;
5092         _cairo_pdf_surface_update_object (surface, subset_resource);
5093         _cairo_output_stream_printf (surface->output,
5094                                      "%d 0 obj\n"
5095                                      "<< /Type /Font\n"
5096                                      "   /Subtype /Type1\n"
5097                                      "   /BaseFont /%s+%s\n"
5098                                      "   /FirstChar 32\n"
5099                                      "   /LastChar %d\n"
5100                                      "   /FontDescriptor %d 0 R\n"
5101                                      "   /Encoding /WinAnsiEncoding\n"
5102                                      "   /Widths [",
5103                                      subset_resource.id,
5104                                      tag,
5105                                      subset->ps_name,
5106                                      last_glyph,
5107                                      descriptor.id);
5108
5109         for (i = 32; i < last_glyph + 1; i++) {
5110             int glyph = font_subset->latin_to_subset_glyph_index[i];
5111             if (glyph > 0) {
5112                 _cairo_output_stream_printf (surface->output,
5113                                              " %ld",
5114                                              (long)(subset->widths[glyph]*PDF_UNITS_PER_EM));
5115             } else {
5116                 _cairo_output_stream_printf (surface->output, " 0");
5117             }
5118         }
5119
5120         _cairo_output_stream_printf (surface->output,
5121                                      " ]\n");
5122
5123         if (to_unicode_stream.id != 0)
5124             _cairo_output_stream_printf (surface->output,
5125                                          "    /ToUnicode %d 0 R\n",
5126                                          to_unicode_stream.id);
5127
5128         _cairo_output_stream_printf (surface->output,
5129                                      ">>\n"
5130                                      "endobj\n");
5131     } else {
5132         cidfont_dict = _cairo_pdf_surface_new_object (surface);
5133         if (cidfont_dict.id == 0)
5134             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5135
5136         _cairo_output_stream_printf (surface->output,
5137                                      "%d 0 obj\n"
5138                                      "<< /Type /Font\n"
5139                                      "   /Subtype /CIDFontType0\n"
5140                                      "   /BaseFont /%s+%s\n"
5141                                      "   /CIDSystemInfo\n"
5142                                      "   << /Registry (Adobe)\n"
5143                                      "      /Ordering (Identity)\n"
5144                                      "      /Supplement 0\n"
5145                                      "   >>\n"
5146                                      "   /FontDescriptor %d 0 R\n"
5147                                      "   /W [0 [",
5148                                      cidfont_dict.id,
5149                                      tag,
5150                                      subset->ps_name,
5151                                      descriptor.id);
5152
5153         for (i = 0; i < font_subset->num_glyphs; i++)
5154             _cairo_output_stream_printf (surface->output,
5155                                          " %ld",
5156                                          (long)(subset->widths[i]*PDF_UNITS_PER_EM));
5157
5158         _cairo_output_stream_printf (surface->output,
5159                                      " ]]\n"
5160                                      ">>\n"
5161                                      "endobj\n");
5162
5163         _cairo_pdf_surface_update_object (surface, subset_resource);
5164         _cairo_output_stream_printf (surface->output,
5165                                      "%d 0 obj\n"
5166                                      "<< /Type /Font\n"
5167                                      "   /Subtype /Type0\n"
5168                                      "   /BaseFont /%s+%s\n"
5169                                      "   /Encoding /Identity-H\n"
5170                                      "   /DescendantFonts [ %d 0 R]\n",
5171                                      subset_resource.id,
5172                                      tag,
5173                                      subset->ps_name,
5174                                      cidfont_dict.id);
5175
5176         if (to_unicode_stream.id != 0)
5177             _cairo_output_stream_printf (surface->output,
5178                                          "   /ToUnicode %d 0 R\n",
5179                                          to_unicode_stream.id);
5180
5181         _cairo_output_stream_printf (surface->output,
5182                                      ">>\n"
5183                                      "endobj\n");
5184     }
5185
5186     font.font_id = font_subset->font_id;
5187     font.subset_id = font_subset->subset_id;
5188     font.subset_resource = subset_resource;
5189     status = _cairo_array_append (&surface->fonts, &font);
5190
5191     return status;
5192 }
5193
5194 static cairo_int_status_t
5195 _cairo_pdf_surface_emit_cff_font_subset (cairo_pdf_surface_t         *surface,
5196                                          cairo_scaled_font_subset_t  *font_subset)
5197 {
5198     cairo_int_status_t status;
5199     cairo_cff_subset_t subset;
5200     char name[64];
5201
5202     snprintf (name, sizeof name, "CairoFont-%d-%d",
5203               font_subset->font_id, font_subset->subset_id);
5204     status = _cairo_cff_subset_init (&subset, name, font_subset);
5205     if (unlikely (status))
5206         return status;
5207
5208     status = _cairo_pdf_surface_emit_cff_font (surface, font_subset, &subset);
5209
5210     _cairo_cff_subset_fini (&subset);
5211
5212     return status;
5213 }
5214
5215 static cairo_int_status_t
5216 _cairo_pdf_surface_emit_cff_fallback_font (cairo_pdf_surface_t         *surface,
5217                                            cairo_scaled_font_subset_t  *font_subset)
5218 {
5219     cairo_int_status_t status;
5220     cairo_cff_subset_t subset;
5221     char name[64];
5222
5223     /* CFF fallback subsetting does not work with 8-bit glyphs unless
5224      * they are a latin subset */
5225     if (!font_subset->is_composite && !font_subset->is_latin)
5226         return CAIRO_INT_STATUS_UNSUPPORTED;
5227
5228     snprintf (name, sizeof name, "CairoFont-%d-%d",
5229               font_subset->font_id, font_subset->subset_id);
5230     status = _cairo_cff_fallback_init (&subset, name, font_subset);
5231     if (unlikely (status))
5232         return status;
5233
5234     status = _cairo_pdf_surface_emit_cff_font (surface, font_subset, &subset);
5235
5236     _cairo_cff_fallback_fini (&subset);
5237
5238     return status;
5239 }
5240
5241 static cairo_int_status_t
5242 _cairo_pdf_surface_emit_type1_font (cairo_pdf_surface_t         *surface,
5243                                     cairo_scaled_font_subset_t  *font_subset,
5244                                     cairo_type1_subset_t        *subset)
5245 {
5246     cairo_pdf_resource_t stream, descriptor, subset_resource, to_unicode_stream;
5247     cairo_pdf_font_t font;
5248     cairo_int_status_t status;
5249     unsigned long length;
5250     unsigned int i, last_glyph;
5251     char tag[10];
5252
5253     _create_font_subset_tag (font_subset, subset->base_font, tag);
5254
5255     subset_resource = _cairo_pdf_surface_get_font_resource (surface,
5256                                                             font_subset->font_id,
5257                                                             font_subset->subset_id);
5258     if (subset_resource.id == 0)
5259         return CAIRO_STATUS_SUCCESS;
5260
5261     length = subset->header_length + subset->data_length + subset->trailer_length;
5262     status = _cairo_pdf_surface_open_stream (surface,
5263                                              NULL,
5264                                              TRUE,
5265                                              "   /Length1 %lu\n"
5266                                              "   /Length2 %lu\n"
5267                                              "   /Length3 %lu\n",
5268                                              subset->header_length,
5269                                              subset->data_length,
5270                                              subset->trailer_length);
5271     if (unlikely (status))
5272         return status;
5273
5274     stream = surface->pdf_stream.self;
5275     _cairo_output_stream_write (surface->output, subset->data, length);
5276     status = _cairo_pdf_surface_close_stream (surface);
5277     if (unlikely (status))
5278         return status;
5279
5280     status = _cairo_pdf_surface_emit_to_unicode_stream (surface,
5281                                                         font_subset,
5282                                                         &to_unicode_stream);
5283     if (_cairo_int_status_is_error (status))
5284         return status;
5285
5286     last_glyph = font_subset->num_glyphs - 1;
5287     if (font_subset->is_latin) {
5288         /* find last glyph used */
5289         for (i = 255; i >= 32; i--)
5290             if (font_subset->latin_to_subset_glyph_index[i] > 0)
5291                 break;
5292
5293         last_glyph = i;
5294     }
5295
5296     descriptor = _cairo_pdf_surface_new_object (surface);
5297     if (descriptor.id == 0)
5298         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5299
5300     _cairo_output_stream_printf (surface->output,
5301                                  "%d 0 obj\n"
5302                                  "<< /Type /FontDescriptor\n"
5303                                  "   /FontName /%s+%s\n"
5304                                  "   /Flags 4\n"
5305                                  "   /FontBBox [ %ld %ld %ld %ld ]\n"
5306                                  "   /ItalicAngle 0\n"
5307                                  "   /Ascent %ld\n"
5308                                  "   /Descent %ld\n"
5309                                  "   /CapHeight %ld\n"
5310                                  "   /StemV 80\n"
5311                                  "   /StemH 80\n"
5312                                  "   /FontFile %u 0 R\n"
5313                                  ">>\n"
5314                                  "endobj\n",
5315                                  descriptor.id,
5316                                  tag,
5317                                  subset->base_font,
5318                                  (long)(subset->x_min*PDF_UNITS_PER_EM),
5319                                  (long)(subset->y_min*PDF_UNITS_PER_EM),
5320                                  (long)(subset->x_max*PDF_UNITS_PER_EM),
5321                                  (long)(subset->y_max*PDF_UNITS_PER_EM),
5322                                  (long)(subset->ascent*PDF_UNITS_PER_EM),
5323                                  (long)(subset->descent*PDF_UNITS_PER_EM),
5324                                  (long)(subset->y_max*PDF_UNITS_PER_EM),
5325                                  stream.id);
5326
5327     _cairo_pdf_surface_update_object (surface, subset_resource);
5328     _cairo_output_stream_printf (surface->output,
5329                                  "%d 0 obj\n"
5330                                  "<< /Type /Font\n"
5331                                  "   /Subtype /Type1\n"
5332                                  "   /BaseFont /%s+%s\n"
5333                                  "   /FirstChar %d\n"
5334                                  "   /LastChar %d\n"
5335                                  "   /FontDescriptor %d 0 R\n",
5336                                  subset_resource.id,
5337                                  tag,
5338                                  subset->base_font,
5339                                  font_subset->is_latin ? 32 : 0,
5340                                  last_glyph,
5341                                  descriptor.id);
5342
5343     if (font_subset->is_latin)
5344         _cairo_output_stream_printf (surface->output, "   /Encoding /WinAnsiEncoding\n");
5345
5346     _cairo_output_stream_printf (surface->output, "   /Widths [");
5347     if (font_subset->is_latin) {
5348         for (i = 32; i < last_glyph + 1; i++) {
5349             int glyph = font_subset->latin_to_subset_glyph_index[i];
5350             if (glyph > 0) {
5351                 _cairo_output_stream_printf (surface->output,
5352                                              " %ld",
5353                                              (long)(subset->widths[glyph]*PDF_UNITS_PER_EM));
5354             } else {
5355                 _cairo_output_stream_printf (surface->output, " 0");
5356             }
5357         }
5358     } else {
5359         for (i = 0; i < font_subset->num_glyphs; i++)
5360             _cairo_output_stream_printf (surface->output,
5361                                          " %ld",
5362                                          (long)(subset->widths[i]*PDF_UNITS_PER_EM));
5363     }
5364
5365     _cairo_output_stream_printf (surface->output,
5366                                  " ]\n");
5367
5368     if (to_unicode_stream.id != 0)
5369         _cairo_output_stream_printf (surface->output,
5370                                      "    /ToUnicode %d 0 R\n",
5371                                      to_unicode_stream.id);
5372
5373     _cairo_output_stream_printf (surface->output,
5374                                  ">>\n"
5375                                  "endobj\n");
5376
5377     font.font_id = font_subset->font_id;
5378     font.subset_id = font_subset->subset_id;
5379     font.subset_resource = subset_resource;
5380     return _cairo_array_append (&surface->fonts, &font);
5381 }
5382
5383 static cairo_int_status_t
5384 _cairo_pdf_surface_emit_type1_font_subset (cairo_pdf_surface_t          *surface,
5385                                            cairo_scaled_font_subset_t   *font_subset)
5386 {
5387     cairo_int_status_t status;
5388     cairo_type1_subset_t subset;
5389     char name[64];
5390
5391     /* 16-bit glyphs not compatible with Type 1 fonts */
5392     if (font_subset->is_composite && !font_subset->is_latin)
5393         return CAIRO_INT_STATUS_UNSUPPORTED;
5394
5395     snprintf (name, sizeof name, "CairoFont-%d-%d",
5396               font_subset->font_id, font_subset->subset_id);
5397     status = _cairo_type1_subset_init (&subset, name, font_subset, FALSE);
5398     if (unlikely (status))
5399         return status;
5400
5401     status = _cairo_pdf_surface_emit_type1_font (surface, font_subset, &subset);
5402
5403     _cairo_type1_subset_fini (&subset);
5404     return status;
5405 }
5406
5407 static cairo_int_status_t
5408 _cairo_pdf_surface_emit_type1_fallback_font (cairo_pdf_surface_t        *surface,
5409                                              cairo_scaled_font_subset_t *font_subset)
5410 {
5411     cairo_int_status_t status;
5412     cairo_type1_subset_t subset;
5413     char name[64];
5414
5415     /* 16-bit glyphs not compatible with Type 1 fonts */
5416     if (font_subset->is_composite && !font_subset->is_latin)
5417         return CAIRO_INT_STATUS_UNSUPPORTED;
5418
5419     snprintf (name, sizeof name, "CairoFont-%d-%d",
5420               font_subset->font_id, font_subset->subset_id);
5421     status = _cairo_type1_fallback_init_binary (&subset, name, font_subset);
5422     if (unlikely (status))
5423         return status;
5424
5425     status = _cairo_pdf_surface_emit_type1_font (surface, font_subset, &subset);
5426
5427     _cairo_type1_fallback_fini (&subset);
5428     return status;
5429 }
5430
5431 static cairo_int_status_t
5432 _cairo_pdf_surface_emit_truetype_font_subset (cairo_pdf_surface_t               *surface,
5433                                               cairo_scaled_font_subset_t        *font_subset)
5434 {
5435     cairo_pdf_resource_t stream, descriptor, cidfont_dict;
5436     cairo_pdf_resource_t subset_resource, to_unicode_stream;
5437     cairo_int_status_t status;
5438     cairo_pdf_font_t font;
5439     cairo_truetype_subset_t subset;
5440     unsigned int i, last_glyph;
5441     char tag[10];
5442
5443     subset_resource = _cairo_pdf_surface_get_font_resource (surface,
5444                                                             font_subset->font_id,
5445                                                             font_subset->subset_id);
5446     if (subset_resource.id == 0)
5447         return CAIRO_STATUS_SUCCESS;
5448
5449     status = _cairo_truetype_subset_init_pdf (&subset, font_subset);
5450     if (unlikely (status))
5451         return status;
5452
5453     _create_font_subset_tag (font_subset, subset.ps_name, tag);
5454
5455     status = _cairo_pdf_surface_open_stream (surface,
5456                                              NULL,
5457                                              TRUE,
5458                                              "   /Length1 %lu\n",
5459                                              subset.data_length);
5460     if (unlikely (status)) {
5461         _cairo_truetype_subset_fini (&subset);
5462         return status;
5463     }
5464
5465     stream = surface->pdf_stream.self;
5466     _cairo_output_stream_write (surface->output,
5467                                 subset.data, subset.data_length);
5468     status = _cairo_pdf_surface_close_stream (surface);
5469     if (unlikely (status)) {
5470         _cairo_truetype_subset_fini (&subset);
5471         return status;
5472     }
5473
5474     status = _cairo_pdf_surface_emit_to_unicode_stream (surface,
5475                                                         font_subset,
5476                                                         &to_unicode_stream);
5477     if (_cairo_int_status_is_error (status)) {
5478         _cairo_truetype_subset_fini (&subset);
5479         return status;
5480     }
5481
5482     descriptor = _cairo_pdf_surface_new_object (surface);
5483     if (descriptor.id == 0) {
5484         _cairo_truetype_subset_fini (&subset);
5485         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5486     }
5487
5488     _cairo_output_stream_printf (surface->output,
5489                                  "%d 0 obj\n"
5490                                  "<< /Type /FontDescriptor\n"
5491                                  "   /FontName /%s+%s\n",
5492                                  descriptor.id,
5493                                  tag,
5494                                  subset.ps_name);
5495
5496     if (subset.family_name_utf8) {
5497         char *pdf_str;
5498
5499         status = _utf8_to_pdf_string (subset.family_name_utf8, &pdf_str);
5500     if (unlikely (status)) {
5501         _cairo_truetype_subset_fini (&subset);
5502         return status;
5503     }
5504
5505         _cairo_output_stream_printf (surface->output,
5506                                      "   /FontFamily %s\n",
5507                                      pdf_str);
5508         free (pdf_str);
5509     }
5510
5511     _cairo_output_stream_printf (surface->output,
5512                                  "   /Flags %d\n"
5513                                  "   /FontBBox [ %ld %ld %ld %ld ]\n"
5514                                  "   /ItalicAngle 0\n"
5515                                  "   /Ascent %ld\n"
5516                                  "   /Descent %ld\n"
5517                                  "   /CapHeight %ld\n"
5518                                  "   /StemV 80\n"
5519                                  "   /StemH 80\n"
5520                                  "   /FontFile2 %u 0 R\n"
5521                                  ">>\n"
5522                                  "endobj\n",
5523                                  font_subset->is_latin ? 32 : 4,
5524                                  (long)(subset.x_min*PDF_UNITS_PER_EM),
5525                                  (long)(subset.y_min*PDF_UNITS_PER_EM),
5526                                  (long)(subset.x_max*PDF_UNITS_PER_EM),
5527                                  (long)(subset.y_max*PDF_UNITS_PER_EM),
5528                                  (long)(subset.ascent*PDF_UNITS_PER_EM),
5529                                  (long)(subset.descent*PDF_UNITS_PER_EM),
5530                                  (long)(subset.y_max*PDF_UNITS_PER_EM),
5531                                  stream.id);
5532
5533     if (font_subset->is_latin) {
5534         /* find last glyph used */
5535         for (i = 255; i >= 32; i--)
5536             if (font_subset->latin_to_subset_glyph_index[i] > 0)
5537                 break;
5538
5539         last_glyph = i;
5540         _cairo_pdf_surface_update_object (surface, subset_resource);
5541         _cairo_output_stream_printf (surface->output,
5542                                      "%d 0 obj\n"
5543                                      "<< /Type /Font\n"
5544                                      "   /Subtype /TrueType\n"
5545                                      "   /BaseFont /%s+%s\n"
5546                                      "   /FirstChar 32\n"
5547                                      "   /LastChar %d\n"
5548                                      "   /FontDescriptor %d 0 R\n"
5549                                      "   /Encoding /WinAnsiEncoding\n"
5550                                      "   /Widths [",
5551                                      subset_resource.id,
5552                                      tag,
5553                                      subset.ps_name,
5554                                      last_glyph,
5555                                      descriptor.id);
5556
5557         for (i = 32; i < last_glyph + 1; i++) {
5558             int glyph = font_subset->latin_to_subset_glyph_index[i];
5559             if (glyph > 0) {
5560                 _cairo_output_stream_printf (surface->output,
5561                                              " %ld",
5562                                              (long)(subset.widths[glyph]*PDF_UNITS_PER_EM));
5563             } else {
5564                 _cairo_output_stream_printf (surface->output, " 0");
5565             }
5566         }
5567
5568         _cairo_output_stream_printf (surface->output,
5569                                      " ]\n");
5570
5571         if (to_unicode_stream.id != 0)
5572             _cairo_output_stream_printf (surface->output,
5573                                          "    /ToUnicode %d 0 R\n",
5574                                          to_unicode_stream.id);
5575
5576         _cairo_output_stream_printf (surface->output,
5577                                      ">>\n"
5578                                      "endobj\n");
5579     } else {
5580         cidfont_dict = _cairo_pdf_surface_new_object (surface);
5581         if (cidfont_dict.id == 0) {
5582             _cairo_truetype_subset_fini (&subset);
5583             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5584         }
5585
5586         _cairo_output_stream_printf (surface->output,
5587                                      "%d 0 obj\n"
5588                                      "<< /Type /Font\n"
5589                                      "   /Subtype /CIDFontType2\n"
5590                                      "   /BaseFont /%s+%s\n"
5591                                      "   /CIDSystemInfo\n"
5592                                      "   << /Registry (Adobe)\n"
5593                                      "      /Ordering (Identity)\n"
5594                                      "      /Supplement 0\n"
5595                                      "   >>\n"
5596                                      "   /FontDescriptor %d 0 R\n"
5597                                      "   /W [0 [",
5598                                      cidfont_dict.id,
5599                                      tag,
5600                                      subset.ps_name,
5601                                      descriptor.id);
5602
5603         for (i = 0; i < font_subset->num_glyphs; i++)
5604             _cairo_output_stream_printf (surface->output,
5605                                          " %ld",
5606                                          (long)(subset.widths[i]*PDF_UNITS_PER_EM));
5607
5608         _cairo_output_stream_printf (surface->output,
5609                                      " ]]\n"
5610                                      ">>\n"
5611                                      "endobj\n");
5612
5613         _cairo_pdf_surface_update_object (surface, subset_resource);
5614         _cairo_output_stream_printf (surface->output,
5615                                      "%d 0 obj\n"
5616                                      "<< /Type /Font\n"
5617                                      "   /Subtype /Type0\n"
5618                                      "   /BaseFont /%s+%s\n"
5619                                      "   /Encoding /Identity-H\n"
5620                                      "   /DescendantFonts [ %d 0 R]\n",
5621                                      subset_resource.id,
5622                                      tag,
5623                                      subset.ps_name,
5624                                      cidfont_dict.id);
5625
5626         if (to_unicode_stream.id != 0)
5627             _cairo_output_stream_printf (surface->output,
5628                                          "   /ToUnicode %d 0 R\n",
5629                                          to_unicode_stream.id);
5630
5631         _cairo_output_stream_printf (surface->output,
5632                                      ">>\n"
5633                                      "endobj\n");
5634     }
5635
5636     font.font_id = font_subset->font_id;
5637     font.subset_id = font_subset->subset_id;
5638     font.subset_resource = subset_resource;
5639     status = _cairo_array_append (&surface->fonts, &font);
5640
5641     _cairo_truetype_subset_fini (&subset);
5642
5643     return status;
5644 }
5645
5646 static cairo_int_status_t
5647 _cairo_pdf_emit_imagemask (cairo_image_surface_t *image,
5648                              cairo_output_stream_t *stream)
5649 {
5650     uint8_t *byte, output_byte;
5651     int row, col, num_cols;
5652
5653     /* The only image type supported by Type 3 fonts are 1-bit image
5654      * masks */
5655     assert (image->format == CAIRO_FORMAT_A1);
5656
5657     _cairo_output_stream_printf (stream,
5658                                  "BI\n"
5659                                  "/IM true\n"
5660                                  "/W %d\n"
5661                                  "/H %d\n"
5662                                  "/BPC 1\n"
5663                                  "/D [1 0]\n",
5664                                  image->width,
5665                                  image->height);
5666
5667     _cairo_output_stream_printf (stream,
5668                                  "ID ");
5669
5670     num_cols = (image->width + 7) / 8;
5671     for (row = 0; row < image->height; row++) {
5672         byte = image->data + row * image->stride;
5673         for (col = 0; col < num_cols; col++) {
5674             output_byte = CAIRO_BITSWAP8_IF_LITTLE_ENDIAN (*byte);
5675             _cairo_output_stream_write (stream, &output_byte, 1);
5676             byte++;
5677         }
5678     }
5679
5680     _cairo_output_stream_printf (stream,
5681                                  "\nEI\n");
5682
5683     return _cairo_output_stream_get_status (stream);
5684 }
5685
5686 static cairo_int_status_t
5687 _cairo_pdf_surface_analyze_user_font_subset (cairo_scaled_font_subset_t *font_subset,
5688                                              void                       *closure)
5689 {
5690     cairo_pdf_surface_t *surface = closure;
5691     cairo_int_status_t status = CAIRO_INT_STATUS_SUCCESS;
5692     cairo_int_status_t status2;
5693     unsigned int i;
5694     cairo_surface_t *type3_surface;
5695     cairo_output_stream_t *null_stream;
5696
5697     null_stream = _cairo_null_stream_create ();
5698     type3_surface = _cairo_type3_glyph_surface_create (font_subset->scaled_font,
5699                                                        null_stream,
5700                                                        _cairo_pdf_emit_imagemask,
5701                                                        surface->font_subsets,
5702                                                        FALSE);
5703     if (unlikely (type3_surface->status)) {
5704         status2 = _cairo_output_stream_destroy (null_stream);
5705         status = type3_surface->status;
5706         cairo_surface_destroy (type3_surface);
5707         return status;
5708     }
5709
5710     _cairo_type3_glyph_surface_set_font_subsets_callback (type3_surface,
5711                                                           _cairo_pdf_surface_add_font,
5712                                                           surface);
5713
5714     for (i = 0; i < font_subset->num_glyphs; i++) {
5715         status = _cairo_type3_glyph_surface_analyze_glyph (type3_surface,
5716                                                            font_subset->glyphs[i]);
5717         if (unlikely (status))
5718             break;
5719     }
5720
5721     cairo_surface_destroy (type3_surface);
5722     status2 = _cairo_output_stream_destroy (null_stream);
5723     if (status == CAIRO_INT_STATUS_SUCCESS)
5724         status = status2;
5725
5726     return status;
5727 }
5728
5729 static cairo_int_status_t
5730 _cairo_pdf_surface_emit_type3_font_subset (cairo_pdf_surface_t          *surface,
5731                                            cairo_scaled_font_subset_t   *font_subset)
5732 {
5733     cairo_int_status_t status = CAIRO_STATUS_SUCCESS;
5734     cairo_pdf_resource_t *glyphs, encoding, char_procs, subset_resource, to_unicode_stream;
5735     cairo_pdf_font_t font;
5736     double *widths;
5737     unsigned int i;
5738     cairo_box_t font_bbox = {{0,0},{0,0}};
5739     cairo_box_t bbox = {{0,0},{0,0}};
5740     cairo_surface_t *type3_surface;
5741
5742     if (font_subset->num_glyphs == 0)
5743         return CAIRO_STATUS_SUCCESS;
5744
5745     subset_resource = _cairo_pdf_surface_get_font_resource (surface,
5746                                                             font_subset->font_id,
5747                                                             font_subset->subset_id);
5748     if (subset_resource.id == 0)
5749         return CAIRO_STATUS_SUCCESS;
5750
5751     glyphs = _cairo_malloc_ab (font_subset->num_glyphs, sizeof (cairo_pdf_resource_t));
5752     if (unlikely (glyphs == NULL))
5753         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5754
5755     widths = _cairo_malloc_ab (font_subset->num_glyphs, sizeof (double));
5756     if (unlikely (widths == NULL)) {
5757         free (glyphs);
5758         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5759     }
5760
5761     _cairo_pdf_group_resources_clear (&surface->resources);
5762     type3_surface = _cairo_type3_glyph_surface_create (font_subset->scaled_font,
5763                                                        NULL,
5764                                                        _cairo_pdf_emit_imagemask,
5765                                                        surface->font_subsets,
5766                                                        FALSE);
5767     if (unlikely (type3_surface->status)) {
5768         free (glyphs);
5769         free (widths);
5770         status = type3_surface->status;
5771         cairo_surface_destroy (type3_surface);
5772         return status;
5773     }
5774
5775     _cairo_type3_glyph_surface_set_font_subsets_callback (type3_surface,
5776                                                           _cairo_pdf_surface_add_font,
5777                                                           surface);
5778
5779     for (i = 0; i < font_subset->num_glyphs; i++) {
5780         status = _cairo_pdf_surface_open_stream (surface,
5781                                                  NULL,
5782                                                  surface->compress_content,
5783                                                  NULL);
5784         if (unlikely (status))
5785             break;
5786
5787         glyphs[i] = surface->pdf_stream.self;
5788         status = _cairo_type3_glyph_surface_emit_glyph (type3_surface,
5789                                                         surface->output,
5790                                                         font_subset->glyphs[i],
5791                                                         &bbox,
5792                                                         &widths[i]);
5793         if (unlikely (status))
5794             break;
5795
5796         status = _cairo_pdf_surface_close_stream (surface);
5797         if (unlikely (status))
5798             break;
5799
5800         if (i == 0) {
5801             font_bbox.p1.x = bbox.p1.x;
5802             font_bbox.p1.y = bbox.p1.y;
5803             font_bbox.p2.x = bbox.p2.x;
5804             font_bbox.p2.y = bbox.p2.y;
5805         } else {
5806             if (bbox.p1.x < font_bbox.p1.x)
5807                 font_bbox.p1.x = bbox.p1.x;
5808             if (bbox.p1.y < font_bbox.p1.y)
5809                 font_bbox.p1.y = bbox.p1.y;
5810             if (bbox.p2.x > font_bbox.p2.x)
5811                 font_bbox.p2.x = bbox.p2.x;
5812             if (bbox.p2.y > font_bbox.p2.y)
5813                 font_bbox.p2.y = bbox.p2.y;
5814         }
5815     }
5816     cairo_surface_destroy (type3_surface);
5817     if (unlikely (status)) {
5818         free (glyphs);
5819         free (widths);
5820         return status;
5821     }
5822
5823     encoding = _cairo_pdf_surface_new_object (surface);
5824     if (encoding.id == 0) {
5825         free (glyphs);
5826         free (widths);
5827         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5828     }
5829
5830     _cairo_output_stream_printf (surface->output,
5831                                  "%d 0 obj\n"
5832                                  "<< /Type /Encoding\n"
5833                                  "   /Differences [0", encoding.id);
5834     for (i = 0; i < font_subset->num_glyphs; i++)
5835         _cairo_output_stream_printf (surface->output,
5836                                      " /%d", i);
5837     _cairo_output_stream_printf (surface->output,
5838                                  "]\n"
5839                                  ">>\n"
5840                                  "endobj\n");
5841
5842     char_procs = _cairo_pdf_surface_new_object (surface);
5843     if (char_procs.id == 0) {
5844         free (glyphs);
5845         free (widths);
5846         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
5847     }
5848
5849     _cairo_output_stream_printf (surface->output,
5850                                  "%d 0 obj\n"
5851                                  "<<\n", char_procs.id);
5852     for (i = 0; i < font_subset->num_glyphs; i++)
5853         _cairo_output_stream_printf (surface->output,
5854                                      " /%d %d 0 R\n",
5855                                      i, glyphs[i].id);
5856     _cairo_output_stream_printf (surface->output,
5857                                  ">>\n"
5858                                  "endobj\n");
5859
5860     free (glyphs);
5861
5862     status = _cairo_pdf_surface_emit_to_unicode_stream (surface,
5863                                                         font_subset,
5864                                                         &to_unicode_stream);
5865     if (_cairo_int_status_is_error (status)) {
5866         free (widths);
5867         return status;
5868     }
5869
5870     _cairo_pdf_surface_update_object (surface, subset_resource);
5871     _cairo_output_stream_printf (surface->output,
5872                                  "%d 0 obj\n"
5873                                  "<< /Type /Font\n"
5874                                  "   /Subtype /Type3\n"
5875                                  "   /FontBBox [%f %f %f %f]\n"
5876                                  "   /FontMatrix [ 1 0 0 1 0 0 ]\n"
5877                                  "   /Encoding %d 0 R\n"
5878                                  "   /CharProcs %d 0 R\n"
5879                                  "   /FirstChar 0\n"
5880                                  "   /LastChar %d\n",
5881                                  subset_resource.id,
5882                                  _cairo_fixed_to_double (font_bbox.p1.x),
5883                                  - _cairo_fixed_to_double (font_bbox.p2.y),
5884                                  _cairo_fixed_to_double (font_bbox.p2.x),
5885                                  - _cairo_fixed_to_double (font_bbox.p1.y),
5886                                  encoding.id,
5887                                  char_procs.id,
5888                                  font_subset->num_glyphs - 1);
5889
5890     _cairo_output_stream_printf (surface->output,
5891                                  "   /Widths [");
5892     for (i = 0; i < font_subset->num_glyphs; i++)
5893         _cairo_output_stream_printf (surface->output, " %f", widths[i]);
5894     _cairo_output_stream_printf (surface->output,
5895                                  "]\n");
5896     free (widths);
5897
5898     _cairo_output_stream_printf (surface->output,
5899                                  "   /Resources\n");
5900     _cairo_pdf_surface_emit_group_resources (surface, &surface->resources);
5901
5902     if (to_unicode_stream.id != 0)
5903         _cairo_output_stream_printf (surface->output,
5904                                      "    /ToUnicode %d 0 R\n",
5905                                      to_unicode_stream.id);
5906
5907     _cairo_output_stream_printf (surface->output,
5908                                  ">>\n"
5909                                  "endobj\n");
5910
5911     font.font_id = font_subset->font_id;
5912     font.subset_id = font_subset->subset_id;
5913     font.subset_resource = subset_resource;
5914     return _cairo_array_append (&surface->fonts, &font);
5915 }
5916
5917 static cairo_int_status_t
5918 _cairo_pdf_surface_emit_unscaled_font_subset (cairo_scaled_font_subset_t *font_subset,
5919                                               void                       *closure)
5920 {
5921     cairo_pdf_surface_t *surface = closure;
5922     cairo_int_status_t status;
5923
5924     status = _cairo_pdf_surface_emit_cff_font_subset (surface, font_subset);
5925     if (status != CAIRO_INT_STATUS_UNSUPPORTED)
5926         return status;
5927
5928     status = _cairo_pdf_surface_emit_truetype_font_subset (surface, font_subset);
5929     if (status != CAIRO_INT_STATUS_UNSUPPORTED)
5930         return status;
5931
5932     status = _cairo_pdf_surface_emit_type1_font_subset (surface, font_subset);
5933     if (status != CAIRO_INT_STATUS_UNSUPPORTED)
5934         return status;
5935
5936     status = _cairo_pdf_surface_emit_cff_fallback_font (surface, font_subset);
5937     if (status != CAIRO_INT_STATUS_UNSUPPORTED)
5938         return status;
5939
5940     status = _cairo_pdf_surface_emit_type1_fallback_font (surface, font_subset);
5941     if (status != CAIRO_INT_STATUS_UNSUPPORTED)
5942         return status;
5943
5944     ASSERT_NOT_REACHED;
5945     return CAIRO_INT_STATUS_SUCCESS;
5946 }
5947
5948 static cairo_int_status_t
5949 _cairo_pdf_surface_emit_scaled_font_subset (cairo_scaled_font_subset_t *font_subset,
5950                                             void                       *closure)
5951 {
5952     cairo_pdf_surface_t *surface = closure;
5953     cairo_int_status_t status;
5954
5955     status = _cairo_pdf_surface_emit_type3_font_subset (surface, font_subset);
5956     if (status != CAIRO_INT_STATUS_UNSUPPORTED)
5957         return status;
5958
5959     ASSERT_NOT_REACHED;
5960     return CAIRO_INT_STATUS_SUCCESS;
5961 }
5962
5963 static cairo_int_status_t
5964 _cairo_pdf_surface_emit_font_subsets (cairo_pdf_surface_t *surface)
5965 {
5966     cairo_int_status_t status;
5967
5968     status = _cairo_scaled_font_subsets_foreach_user (surface->font_subsets,
5969                                                       _cairo_pdf_surface_analyze_user_font_subset,
5970                                                       surface);
5971     if (unlikely (status))
5972         goto BAIL;
5973
5974     status = _cairo_scaled_font_subsets_foreach_unscaled (surface->font_subsets,
5975                                                           _cairo_pdf_surface_emit_unscaled_font_subset,
5976                                                           surface);
5977     if (unlikely (status))
5978         goto BAIL;
5979
5980     status = _cairo_scaled_font_subsets_foreach_scaled (surface->font_subsets,
5981                                                         _cairo_pdf_surface_emit_scaled_font_subset,
5982                                                         surface);
5983     if (unlikely (status))
5984         goto BAIL;
5985
5986     status = _cairo_scaled_font_subsets_foreach_user (surface->font_subsets,
5987                                                       _cairo_pdf_surface_emit_scaled_font_subset,
5988                                                       surface);
5989
5990 BAIL:
5991     _cairo_scaled_font_subsets_destroy (surface->font_subsets);
5992     surface->font_subsets = NULL;
5993
5994     return status;
5995 }
5996
5997 static cairo_pdf_resource_t
5998 _cairo_pdf_surface_write_catalog (cairo_pdf_surface_t *surface)
5999 {
6000     cairo_pdf_resource_t catalog;
6001
6002     catalog = _cairo_pdf_surface_new_object (surface);
6003     if (catalog.id == 0)
6004         return catalog;
6005
6006     _cairo_output_stream_printf (surface->output,
6007                                  "%d 0 obj\n"
6008                                  "<< /Type /Catalog\n"
6009                                  "   /Pages %d 0 R\n"
6010                                  ">>\n"
6011                                  "endobj\n",
6012                                  catalog.id,
6013                                  surface->pages_resource.id);
6014
6015     return catalog;
6016 }
6017
6018 static long
6019 _cairo_pdf_surface_write_xref (cairo_pdf_surface_t *surface)
6020 {
6021     cairo_pdf_object_t *object;
6022     int num_objects, i;
6023     long offset;
6024     char buffer[11];
6025
6026     num_objects = _cairo_array_num_elements (&surface->objects);
6027
6028     offset = _cairo_output_stream_get_position (surface->output);
6029     _cairo_output_stream_printf (surface->output,
6030                                  "xref\n"
6031                                  "%d %d\n",
6032                                  0, num_objects + 1);
6033
6034     _cairo_output_stream_printf (surface->output,
6035                                  "0000000000 65535 f \n");
6036     for (i = 0; i < num_objects; i++) {
6037         object = _cairo_array_index (&surface->objects, i);
6038         if (object == NULL)
6039             return -1;
6040         snprintf (buffer, sizeof buffer, "%010ld", object->offset);
6041         _cairo_output_stream_printf (surface->output,
6042                                      "%s 00000 n \n", buffer);
6043     }
6044
6045     return offset;
6046 }
6047
6048 static cairo_int_status_t
6049 _cairo_pdf_surface_write_mask_group (cairo_pdf_surface_t        *surface,
6050                                      cairo_pdf_smask_group_t    *group)
6051 {
6052     cairo_pdf_resource_t mask_group;
6053     cairo_pdf_resource_t smask;
6054     cairo_pdf_smask_group_t *smask_group;
6055     cairo_pdf_resource_t pattern_res, gstate_res;
6056     cairo_int_status_t status;
6057     cairo_box_double_t bbox;
6058
6059     /* Create mask group */
6060     _get_bbox_from_extents (group->height, &group->extents, &bbox);
6061     status = _cairo_pdf_surface_open_group (surface, &bbox, NULL);
6062     if (unlikely (status))
6063         return status;
6064
6065     if (_can_paint_pattern (group->mask)) {
6066         _cairo_output_stream_printf (surface->output, "q\n");
6067         status = _cairo_pdf_surface_paint_pattern (surface,
6068                                                    CAIRO_OPERATOR_OVER,
6069                                                    group->mask,
6070                                                    &group->extents,
6071                                                    FALSE);
6072         if (unlikely (status))
6073             return status;
6074
6075         _cairo_output_stream_printf (surface->output, "Q\n");
6076     } else {
6077         pattern_res.id = 0;
6078         gstate_res.id = 0;
6079         status = _cairo_pdf_surface_add_pdf_pattern (surface, group->mask,
6080                                                      CAIRO_OPERATOR_OVER,
6081                                                      NULL,
6082                                                      &pattern_res, &gstate_res);
6083         if (unlikely (status))
6084             return status;
6085
6086         if (gstate_res.id != 0) {
6087             smask_group = _cairo_pdf_surface_create_smask_group (surface, &group->extents);
6088             if (unlikely (smask_group == NULL))
6089                 return _cairo_error (CAIRO_STATUS_NO_MEMORY);
6090
6091             smask_group->width = group->width;
6092             smask_group->height = group->height;
6093             smask_group->operation = PDF_PAINT;
6094             smask_group->source = cairo_pattern_reference (group->mask);
6095             smask_group->source_res = pattern_res;
6096             status = _cairo_pdf_surface_add_smask_group (surface, smask_group);
6097             if (unlikely (status)) {
6098                 _cairo_pdf_smask_group_destroy (smask_group);
6099                 return status;
6100             }
6101
6102             status = _cairo_pdf_surface_add_smask (surface, gstate_res);
6103             if (unlikely (status))
6104                 return status;
6105
6106             status = _cairo_pdf_surface_add_xobject (surface, smask_group->group_res);
6107             if (unlikely (status))
6108                 return status;
6109
6110             _cairo_output_stream_printf (surface->output,
6111                                          "q /s%d gs /x%d Do Q\n",
6112                                          gstate_res.id,
6113                                          smask_group->group_res.id);
6114         } else {
6115             status = _cairo_pdf_surface_select_pattern (surface, group->mask, pattern_res, FALSE);
6116             if (unlikely (status))
6117                 return status;
6118
6119             _cairo_output_stream_printf (surface->output,
6120                                          "%f %f %f %f re f\n",
6121                                          bbox.p1.x,
6122                                          bbox.p1.y,
6123                                          bbox.p2.x - bbox.p1.x,
6124                                          bbox.p2.y - bbox.p1.y);
6125
6126             status = _cairo_pdf_surface_unselect_pattern (surface);
6127             if (unlikely (status))
6128                 return status;
6129         }
6130     }
6131
6132     status = _cairo_pdf_surface_close_group (surface, &mask_group);
6133     if (unlikely (status))
6134         return status;
6135
6136     /* Create source group */
6137     status = _cairo_pdf_surface_open_group (surface, &bbox, &group->source_res);
6138     if (unlikely (status))
6139         return status;
6140
6141     if (_can_paint_pattern (group->source)) {
6142         _cairo_output_stream_printf (surface->output, "q\n");
6143         status = _cairo_pdf_surface_paint_pattern (surface,
6144                                                    CAIRO_OPERATOR_OVER,
6145                                                    group->source,
6146                                                    &group->extents,
6147                                                    FALSE);
6148         if (unlikely (status))
6149             return status;
6150
6151         _cairo_output_stream_printf (surface->output, "Q\n");
6152     } else {
6153         pattern_res.id = 0;
6154         gstate_res.id = 0;
6155         status = _cairo_pdf_surface_add_pdf_pattern (surface, group->source,
6156                                                      CAIRO_OPERATOR_OVER,
6157                                                      NULL,
6158                                                      &pattern_res, &gstate_res);
6159         if (unlikely (status))
6160             return status;
6161
6162         if (gstate_res.id != 0) {
6163             smask_group = _cairo_pdf_surface_create_smask_group (surface, &group->extents);
6164             if (unlikely (smask_group == NULL))
6165                 return _cairo_error (CAIRO_STATUS_NO_MEMORY);
6166
6167             smask_group->operation = PDF_PAINT;
6168             smask_group->source = cairo_pattern_reference (group->source);
6169             smask_group->source_res = pattern_res;
6170             status = _cairo_pdf_surface_add_smask_group (surface, smask_group);
6171             if (unlikely (status)) {
6172                 _cairo_pdf_smask_group_destroy (smask_group);
6173                 return status;
6174             }
6175
6176             status = _cairo_pdf_surface_add_smask (surface, gstate_res);
6177             if (unlikely (status))
6178                 return status;
6179
6180             status = _cairo_pdf_surface_add_xobject (surface, smask_group->group_res);
6181             if (unlikely (status))
6182                 return status;
6183
6184             _cairo_output_stream_printf (surface->output,
6185                                          "q /s%d gs /x%d Do Q\n",
6186                                          gstate_res.id,
6187                                          smask_group->group_res.id);
6188         } else {
6189             status = _cairo_pdf_surface_select_pattern (surface, group->source, pattern_res, FALSE);
6190             if (unlikely (status))
6191                 return status;
6192
6193             _cairo_output_stream_printf (surface->output,
6194                                          "%f %f %f %f re f\n",
6195                                          bbox.p1.x,
6196                                          bbox.p1.y,
6197                                          bbox.p2.x - bbox.p1.x,
6198                                          bbox.p2.y - bbox.p1.y);
6199
6200             status = _cairo_pdf_surface_unselect_pattern (surface);
6201             if (unlikely (status))
6202                 return status;
6203         }
6204     }
6205
6206     status = _cairo_pdf_surface_close_group (surface, NULL);
6207     if (unlikely (status))
6208         return status;
6209
6210     /* Create an smask based on the alpha component of mask_group */
6211     smask = _cairo_pdf_surface_new_object (surface);
6212     if (smask.id == 0)
6213         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
6214
6215     _cairo_output_stream_printf (surface->output,
6216                                  "%d 0 obj\n"
6217                                  "<< /Type /Mask\n"
6218                                  "   /S /Alpha\n"
6219                                  "   /G %d 0 R\n"
6220                                  ">>\n"
6221                                  "endobj\n",
6222                                  smask.id,
6223                                  mask_group.id);
6224
6225     /* Create a GState that uses the smask */
6226     _cairo_pdf_surface_update_object (surface, group->group_res);
6227     _cairo_output_stream_printf (surface->output,
6228                                  "%d 0 obj\n"
6229                                  "<< /Type /ExtGState\n"
6230                                  "   /SMask %d 0 R\n"
6231                                  "   /ca 1\n"
6232                                  "   /CA 1\n"
6233                                  "   /AIS false\n"
6234                                  ">>\n"
6235                                  "endobj\n",
6236                                  group->group_res.id,
6237                                  smask.id);
6238
6239     return _cairo_output_stream_get_status (surface->output);
6240 }
6241
6242 static cairo_int_status_t
6243 _cairo_pdf_surface_write_smask_group (cairo_pdf_surface_t     *surface,
6244                                       cairo_pdf_smask_group_t *group)
6245 {
6246     double old_width, old_height;
6247     cairo_int_status_t status;
6248     cairo_box_double_t bbox;
6249
6250     old_width = surface->width;
6251     old_height = surface->height;
6252     _cairo_pdf_surface_set_size_internal (surface,
6253                                           group->width,
6254                                           group->height);
6255     /* _mask is a special case that requires two groups - source
6256      * and mask as well as a smask and gstate dictionary */
6257     if (group->operation == PDF_MASK) {
6258         status = _cairo_pdf_surface_write_mask_group (surface, group);
6259         goto RESTORE_SIZE;
6260     }
6261
6262     _get_bbox_from_extents (group->height, &group->extents, &bbox);
6263     status = _cairo_pdf_surface_open_group (surface, &bbox, &group->group_res);
6264     if (unlikely (status))
6265         return status;
6266
6267     status = _cairo_pdf_surface_select_pattern (surface,
6268                                                 group->source,
6269                                                 group->source_res,
6270                                                 group->operation == PDF_STROKE);
6271     if (unlikely (status))
6272         return status;
6273
6274     switch (group->operation) {
6275     case PDF_PAINT:
6276         _cairo_output_stream_printf (surface->output,
6277                                      "0 0 %f %f re f\n",
6278                                      surface->width, surface->height);
6279         break;
6280     case PDF_MASK:
6281         ASSERT_NOT_REACHED;
6282         break;
6283     case PDF_FILL:
6284         status = _cairo_pdf_operators_fill (&surface->pdf_operators,
6285                                             &group->path,
6286                                             group->fill_rule);
6287         break;
6288     case PDF_STROKE:
6289         status = _cairo_pdf_operators_stroke (&surface->pdf_operators,
6290                                               &group->path,
6291                                               &group->style,
6292                                               &group->ctm,
6293                                               &group->ctm_inverse);
6294         break;
6295     case PDF_SHOW_GLYPHS:
6296         status = _cairo_pdf_operators_show_text_glyphs (&surface->pdf_operators,
6297                                                         group->utf8, group->utf8_len,
6298                                                         group->glyphs, group->num_glyphs,
6299                                                         group->clusters, group->num_clusters,
6300                                                         group->cluster_flags,
6301                                                         group->scaled_font);
6302         break;
6303     }
6304     if (unlikely (status))
6305         return status;
6306
6307     status = _cairo_pdf_surface_unselect_pattern (surface);
6308     if (unlikely (status))
6309         return status;
6310
6311     status = _cairo_pdf_surface_close_group (surface, NULL);
6312
6313 RESTORE_SIZE:
6314     _cairo_pdf_surface_set_size_internal (surface,
6315                                           old_width,
6316                                           old_height);
6317
6318     return status;
6319 }
6320
6321 static cairo_int_status_t
6322 _cairo_pdf_surface_write_patterns_and_smask_groups (cairo_pdf_surface_t *surface)
6323 {
6324     cairo_pdf_pattern_t pattern;
6325     cairo_pdf_smask_group_t *group;
6326     cairo_pdf_source_surface_t src_surface;
6327     unsigned int pattern_index, group_index, surface_index;
6328     cairo_int_status_t status;
6329
6330     /* Writing out PDF_MASK groups will cause additional smask groups
6331      * to be appended to surface->smask_groups. Additional patterns
6332      * may also be appended to surface->patterns.
6333      *
6334      * Writing recording surface patterns will cause additional patterns
6335      * and groups to be appended.
6336      */
6337     pattern_index = 0;
6338     group_index = 0;
6339     surface_index = 0;
6340     while ((pattern_index < _cairo_array_num_elements (&surface->page_patterns)) ||
6341            (group_index < _cairo_array_num_elements (&surface->smask_groups)) ||
6342            (surface_index < _cairo_array_num_elements (&surface->page_surfaces)))
6343     {
6344         for (; group_index < _cairo_array_num_elements (&surface->smask_groups); group_index++) {
6345             _cairo_array_copy_element (&surface->smask_groups, group_index, &group);
6346             status = _cairo_pdf_surface_write_smask_group (surface, group);
6347             if (unlikely (status))
6348                 return status;
6349         }
6350
6351         for (; pattern_index < _cairo_array_num_elements (&surface->page_patterns); pattern_index++) {
6352             _cairo_array_copy_element (&surface->page_patterns, pattern_index, &pattern);
6353             status = _cairo_pdf_surface_emit_pattern (surface, &pattern);
6354             if (unlikely (status))
6355                 return status;
6356         }
6357
6358         for (; surface_index < _cairo_array_num_elements (&surface->page_surfaces); surface_index++) {
6359             _cairo_array_copy_element (&surface->page_surfaces, surface_index, &src_surface);
6360             status = _cairo_pdf_surface_emit_surface (surface, &src_surface);
6361             if (unlikely (status))
6362                 return status;
6363         }
6364     }
6365
6366     return CAIRO_STATUS_SUCCESS;
6367 }
6368
6369 static cairo_int_status_t
6370 _cairo_pdf_surface_write_page (cairo_pdf_surface_t *surface)
6371 {
6372     cairo_pdf_resource_t page, knockout, res;
6373     cairo_int_status_t status;
6374     unsigned int i, len;
6375
6376     _cairo_pdf_group_resources_clear (&surface->resources);
6377     if (surface->has_fallback_images) {
6378         cairo_rectangle_int_t extents;
6379         cairo_box_double_t    bbox;
6380
6381         extents.x = 0;
6382         extents.y = 0;
6383         extents.width = ceil (surface->width);
6384         extents.height = ceil (surface->height);
6385         _get_bbox_from_extents (surface->height, &extents, &bbox);
6386         status = _cairo_pdf_surface_open_knockout_group (surface, &bbox);
6387         if (unlikely (status))
6388             return status;
6389
6390         len = _cairo_array_num_elements (&surface->knockout_group);
6391         for (i = 0; i < len; i++) {
6392             _cairo_array_copy_element (&surface->knockout_group, i, &res);
6393             _cairo_output_stream_printf (surface->output,
6394                                          "/x%d Do\n",
6395                                          res.id);
6396             status = _cairo_pdf_surface_add_xobject (surface, res);
6397             if (unlikely (status))
6398                 return status;
6399         }
6400         _cairo_output_stream_printf (surface->output,
6401                                      "/x%d Do\n",
6402                                      surface->content.id);
6403         status = _cairo_pdf_surface_add_xobject (surface, surface->content);
6404         if (unlikely (status))
6405             return status;
6406
6407         status = _cairo_pdf_surface_close_group (surface, &knockout);
6408         if (unlikely (status))
6409             return status;
6410
6411         _cairo_pdf_group_resources_clear (&surface->resources);
6412         status = _cairo_pdf_surface_open_content_stream (surface, NULL, NULL, FALSE, FALSE);
6413         if (unlikely (status))
6414             return status;
6415
6416         _cairo_output_stream_printf (surface->output,
6417                                      "/x%d Do\n",
6418                                      knockout.id);
6419         status = _cairo_pdf_surface_add_xobject (surface, knockout);
6420         if (unlikely (status))
6421             return status;
6422
6423         status = _cairo_pdf_surface_close_content_stream (surface);
6424         if (unlikely (status))
6425             return status;
6426     }
6427
6428     page = _cairo_pdf_surface_new_object (surface);
6429     if (page.id == 0)
6430         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
6431
6432     _cairo_output_stream_printf (surface->output,
6433                                  "%d 0 obj\n"
6434                                  "<< /Type /Page\n"
6435                                  "   /Parent %d 0 R\n"
6436                                  "   /MediaBox [ 0 0 %f %f ]\n"
6437                                  "   /Contents %d 0 R\n"
6438                                  "   /Group <<\n"
6439                                  "      /Type /Group\n"
6440                                  "      /S /Transparency\n"
6441                                  "      /I true\n"
6442                                  "      /CS /DeviceRGB\n"
6443                                  "   >>\n"
6444                                  "   /Resources %d 0 R\n"
6445                                  ">>\n"
6446                                  "endobj\n",
6447                                  page.id,
6448                                  surface->pages_resource.id,
6449                                  surface->width,
6450                                  surface->height,
6451                                  surface->content.id,
6452                                  surface->content_resources.id);
6453
6454     status = _cairo_array_append (&surface->pages, &page);
6455     if (unlikely (status))
6456         return status;
6457
6458     status = _cairo_pdf_surface_write_patterns_and_smask_groups (surface);
6459     if (unlikely (status))
6460         return status;
6461
6462     return CAIRO_STATUS_SUCCESS;
6463 }
6464
6465 static cairo_int_status_t
6466 _cairo_pdf_surface_analyze_surface_pattern_transparency (cairo_pdf_surface_t      *surface,
6467                                                          cairo_surface_pattern_t *pattern)
6468 {
6469     cairo_image_surface_t  *image;
6470     void                   *image_extra;
6471     cairo_int_status_t      status;
6472     cairo_image_transparency_t transparency;
6473
6474     status = _cairo_surface_acquire_source_image (pattern->surface,
6475                                                   &image,
6476                                                   &image_extra);
6477     if (unlikely (status))
6478         return status;
6479
6480     if (image->base.status)
6481         return image->base.status;
6482
6483     transparency = _cairo_image_analyze_transparency (image);
6484     if (transparency == CAIRO_IMAGE_IS_OPAQUE)
6485         status = CAIRO_STATUS_SUCCESS;
6486     else
6487         status = CAIRO_INT_STATUS_FLATTEN_TRANSPARENCY;
6488
6489     _cairo_surface_release_source_image (pattern->surface, image, image_extra);
6490
6491     return status;
6492 }
6493
6494 static cairo_bool_t
6495 _surface_pattern_supported (cairo_surface_pattern_t *pattern)
6496 {
6497     cairo_extend_t extend;
6498
6499     if (pattern->surface->type == CAIRO_SURFACE_TYPE_RECORDING)
6500         return TRUE;
6501
6502     if (pattern->surface->backend->acquire_source_image == NULL)
6503         return FALSE;
6504
6505     /* Does an ALPHA-only source surface even make sense? Maybe, but I
6506      * don't think it's worth the extra code to support it. */
6507
6508 /* XXX: Need to write this function here...
6509     if (pattern->surface->content == CAIRO_CONTENT_ALPHA)
6510         return FALSE;
6511 */
6512
6513     extend = cairo_pattern_get_extend (&pattern->base);
6514     switch (extend) {
6515     case CAIRO_EXTEND_NONE:
6516     case CAIRO_EXTEND_REPEAT:
6517     case CAIRO_EXTEND_REFLECT:
6518     /* There's no point returning FALSE for EXTEND_PAD, as the image
6519      * surface does not currently implement it either */
6520     case CAIRO_EXTEND_PAD:
6521         return TRUE;
6522     }
6523
6524     ASSERT_NOT_REACHED;
6525     return FALSE;
6526 }
6527
6528 static cairo_bool_t
6529 _pattern_supported (const cairo_pattern_t *pattern)
6530 {
6531     switch (pattern->type) {
6532     case CAIRO_PATTERN_TYPE_SOLID:
6533     case CAIRO_PATTERN_TYPE_LINEAR:
6534     case CAIRO_PATTERN_TYPE_RADIAL:
6535     case CAIRO_PATTERN_TYPE_MESH:
6536     case CAIRO_PATTERN_TYPE_RASTER_SOURCE:
6537         return TRUE;
6538
6539     case CAIRO_PATTERN_TYPE_SURFACE:
6540         return _surface_pattern_supported ((cairo_surface_pattern_t *) pattern);
6541
6542     default:
6543         ASSERT_NOT_REACHED;
6544         return FALSE;
6545     }
6546 }
6547
6548 static cairo_bool_t
6549 _pdf_operator_supported (cairo_operator_t op)
6550 {
6551     switch (op) {
6552     case CAIRO_OPERATOR_OVER:
6553     case CAIRO_OPERATOR_MULTIPLY:
6554     case CAIRO_OPERATOR_SCREEN:
6555     case CAIRO_OPERATOR_OVERLAY:
6556     case CAIRO_OPERATOR_DARKEN:
6557     case CAIRO_OPERATOR_LIGHTEN:
6558     case CAIRO_OPERATOR_COLOR_DODGE:
6559     case CAIRO_OPERATOR_COLOR_BURN:
6560     case CAIRO_OPERATOR_HARD_LIGHT:
6561     case CAIRO_OPERATOR_SOFT_LIGHT:
6562     case CAIRO_OPERATOR_DIFFERENCE:
6563     case CAIRO_OPERATOR_EXCLUSION:
6564     case CAIRO_OPERATOR_HSL_HUE:
6565     case CAIRO_OPERATOR_HSL_SATURATION:
6566     case CAIRO_OPERATOR_HSL_COLOR:
6567     case CAIRO_OPERATOR_HSL_LUMINOSITY:
6568         return TRUE;
6569
6570     default:
6571     case CAIRO_OPERATOR_CLEAR:
6572     case CAIRO_OPERATOR_SOURCE:
6573     case CAIRO_OPERATOR_IN:
6574     case CAIRO_OPERATOR_OUT:
6575     case CAIRO_OPERATOR_ATOP:
6576     case CAIRO_OPERATOR_DEST:
6577     case CAIRO_OPERATOR_DEST_OVER:
6578     case CAIRO_OPERATOR_DEST_IN:
6579     case CAIRO_OPERATOR_DEST_OUT:
6580     case CAIRO_OPERATOR_DEST_ATOP:
6581     case CAIRO_OPERATOR_XOR:
6582     case CAIRO_OPERATOR_ADD:
6583     case CAIRO_OPERATOR_SATURATE:
6584         return FALSE;
6585     }
6586 }
6587
6588 static cairo_int_status_t
6589 _cairo_pdf_surface_analyze_operation (cairo_pdf_surface_t  *surface,
6590                                       cairo_operator_t      op,
6591                                       const cairo_pattern_t      *pattern,
6592                                       const cairo_rectangle_int_t        *extents)
6593 {
6594     if (surface->force_fallbacks &&
6595         surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE)
6596     {
6597         return CAIRO_INT_STATUS_UNSUPPORTED;
6598     }
6599
6600     if (! _pattern_supported (pattern))
6601         return CAIRO_INT_STATUS_UNSUPPORTED;
6602
6603     if (_pdf_operator_supported (op)) {
6604         if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE) {
6605             cairo_surface_pattern_t *surface_pattern = (cairo_surface_pattern_t *) pattern;
6606
6607             if (surface_pattern->surface->type == CAIRO_SURFACE_TYPE_RECORDING) {
6608                 if (pattern->extend == CAIRO_EXTEND_PAD) {
6609                     cairo_box_t box;
6610                     cairo_rectangle_int_t rect;
6611                     cairo_rectangle_int_t rec_extents;
6612
6613                     /* get the operation extents in pattern space */
6614                     _cairo_box_from_rectangle (&box, extents);
6615                     _cairo_matrix_transform_bounding_box_fixed (&pattern->matrix, &box, NULL);
6616                     _cairo_box_round_to_rectangle (&box, &rect);
6617
6618                     /* Check if surface needs padding to fill extents */
6619                     if (_cairo_surface_get_extents (surface_pattern->surface, &rec_extents)) {
6620                         if (_cairo_fixed_integer_ceil(box.p1.x) < rec_extents.x ||
6621                             _cairo_fixed_integer_ceil(box.p1.y) < rec_extents.y ||
6622                             _cairo_fixed_integer_floor(box.p2.y) > rec_extents.x + rec_extents.width ||
6623                             _cairo_fixed_integer_floor(box.p2.y) > rec_extents.y + rec_extents.height)
6624                         {
6625                             return CAIRO_INT_STATUS_UNSUPPORTED;
6626                         }
6627                     }
6628                 }
6629                 return CAIRO_INT_STATUS_ANALYZE_RECORDING_SURFACE_PATTERN;
6630             }
6631         }
6632
6633         return CAIRO_STATUS_SUCCESS;
6634     }
6635
6636
6637     /* The SOURCE operator is supported if the pattern is opaque or if
6638      * there is nothing painted underneath. */
6639     if (op == CAIRO_OPERATOR_SOURCE) {
6640         if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE) {
6641             cairo_surface_pattern_t *surface_pattern = (cairo_surface_pattern_t *) pattern;
6642
6643             if (surface_pattern->surface->type == CAIRO_SURFACE_TYPE_RECORDING) {
6644                 if (_cairo_pattern_is_opaque (pattern, extents)) {
6645                     return CAIRO_INT_STATUS_ANALYZE_RECORDING_SURFACE_PATTERN;
6646                 } else {
6647                     /* FIXME: The analysis surface does not yet have
6648                      * the capability to analyze a non opaque recording
6649                      * surface and mark it supported if there is
6650                      * nothing underneath. For now recording surfaces of
6651                      * type CONTENT_COLOR_ALPHA painted with
6652                      * OPERATOR_SOURCE will result in a fallback
6653                      * image. */
6654
6655                     return CAIRO_INT_STATUS_UNSUPPORTED;
6656                 }
6657             } else {
6658                 return _cairo_pdf_surface_analyze_surface_pattern_transparency (surface,
6659                                                                                 surface_pattern);
6660             }
6661         }
6662
6663         if (_cairo_pattern_is_opaque (pattern, extents))
6664             return CAIRO_STATUS_SUCCESS;
6665         else
6666             return CAIRO_INT_STATUS_FLATTEN_TRANSPARENCY;
6667     }
6668
6669     return CAIRO_INT_STATUS_UNSUPPORTED;
6670 }
6671
6672 static cairo_bool_t
6673 _cairo_pdf_surface_operation_supported (cairo_pdf_surface_t  *surface,
6674                                         cairo_operator_t      op,
6675                                         const cairo_pattern_t      *pattern,
6676                                         const cairo_rectangle_int_t *extents)
6677 {
6678     return _cairo_pdf_surface_analyze_operation (surface, op, pattern, extents) != CAIRO_INT_STATUS_UNSUPPORTED;
6679 }
6680
6681 static cairo_int_status_t
6682 _cairo_pdf_surface_start_fallback (cairo_pdf_surface_t *surface)
6683 {
6684     cairo_box_double_t bbox;
6685     cairo_int_status_t status;
6686
6687     status = _cairo_pdf_surface_close_content_stream (surface);
6688     if (unlikely (status))
6689         return status;
6690
6691     status = _cairo_array_append (&surface->knockout_group, &surface->content);
6692     if (unlikely (status))
6693         return status;
6694
6695     _cairo_pdf_group_resources_clear (&surface->resources);
6696     bbox.p1.x = 0;
6697     bbox.p1.y = 0;
6698     bbox.p2.x = surface->width;
6699     bbox.p2.y = surface->height;
6700     return _cairo_pdf_surface_open_content_stream (surface, &bbox, NULL, TRUE, TRUE);
6701 }
6702
6703 /* If source is an opaque image and mask is an image and both images
6704  * have the same bounding box we can emit them as a image/smask pair.
6705  */
6706 static cairo_int_status_t
6707 _cairo_pdf_surface_emit_combined_smask (cairo_pdf_surface_t         *surface,
6708                                         cairo_operator_t             op,
6709                                         const cairo_pattern_t       *source,
6710                                         const cairo_pattern_t       *mask,
6711                                         const cairo_rectangle_int_t *extents)
6712 {
6713     cairo_int_status_t status;
6714     cairo_image_surface_t  *image;
6715     void                   *image_extra;
6716     cairo_image_transparency_t transparency;
6717     cairo_pdf_resource_t smask_res;
6718     int src_width, src_height;
6719     int mask_width, mask_height;
6720     double src_x_offset, src_y_offset;
6721     double mask_x_offset, mask_y_offset;
6722     double src_x1, src_y1, src_x2, src_y2;
6723     double mask_x1, mask_y1, mask_x2, mask_y2;
6724     cairo_matrix_t p2u;
6725     double src_radius, mask_radius, e;
6726     cairo_rectangle_int_t extents2;
6727     cairo_bool_t need_smask;
6728
6729     /* Check that source and mask are images */
6730
6731     if (!((source->type == CAIRO_PATTERN_TYPE_SURFACE || source->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE) &&
6732           (mask->type == CAIRO_PATTERN_TYPE_SURFACE || mask->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE)))
6733         return CAIRO_INT_STATUS_UNSUPPORTED;
6734
6735     if (source->type == CAIRO_PATTERN_TYPE_SURFACE &&
6736         ((cairo_surface_pattern_t *) source)->surface->type == CAIRO_SURFACE_TYPE_RECORDING)
6737     {
6738         return CAIRO_INT_STATUS_UNSUPPORTED;
6739     }
6740
6741     if (mask->type == CAIRO_PATTERN_TYPE_SURFACE &&
6742         ((cairo_surface_pattern_t *) mask)->surface->type == CAIRO_SURFACE_TYPE_RECORDING)
6743     {
6744         return CAIRO_INT_STATUS_UNSUPPORTED;
6745     }
6746
6747     if (source->extend != CAIRO_EXTEND_NONE || mask->extend != CAIRO_EXTEND_NONE)
6748         return CAIRO_INT_STATUS_UNSUPPORTED;
6749
6750     /* Check that source is opaque and get image sizes */
6751
6752     status = _cairo_pdf_surface_acquire_source_image_from_pattern (surface, source,
6753                                                                    &image, &image_extra);
6754     if (unlikely (status))
6755         return status;
6756
6757     if (image->base.status)
6758         return image->base.status;
6759
6760     src_width = image->width;
6761     src_height = image->height;
6762     if (source->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE) {
6763         cairo_surface_get_device_offset (&image->base, &src_x_offset, &src_y_offset);
6764     } else {
6765         src_x_offset = 0;
6766         src_y_offset = 0;
6767     }
6768
6769     transparency = _cairo_image_analyze_transparency (image);
6770     _cairo_pdf_surface_release_source_image_from_pattern (surface, source, image, image_extra);
6771
6772     if (transparency != CAIRO_IMAGE_IS_OPAQUE)
6773         return CAIRO_INT_STATUS_UNSUPPORTED;
6774
6775     status = _cairo_pdf_surface_acquire_source_image_from_pattern (surface, mask,
6776                                                                    &image, &image_extra);
6777     if (unlikely (status))
6778         return status;
6779
6780     if (image->base.status)
6781         return image->base.status;
6782
6783     mask_width = image->width;
6784     mask_height = image->height;
6785     if (mask->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE) {
6786         cairo_surface_get_device_offset (&image->base, &mask_x_offset, &mask_y_offset);
6787     } else {
6788         mask_x_offset = 0;
6789         mask_y_offset = 0;
6790     }
6791
6792     transparency = _cairo_image_analyze_transparency (image);
6793     need_smask = transparency != CAIRO_IMAGE_IS_OPAQUE;
6794
6795     _cairo_pdf_surface_release_source_image_from_pattern (surface, mask, image, image_extra);
6796
6797     /* Check that both images have the same extents with a tolerance
6798      * of half the smallest source pixel. */
6799
6800     p2u = source->matrix;
6801     status = cairo_matrix_invert (&p2u);
6802     /* cairo_pattern_set_matrix ensures the matrix is invertible */
6803     assert (status == CAIRO_INT_STATUS_SUCCESS);
6804     src_x1 = 0;
6805     src_y1 = 0;
6806     src_x2 = src_width;
6807     src_y2 = src_height;
6808     cairo_matrix_transform_point (&p2u, &src_x1, &src_y1);
6809     cairo_matrix_transform_point (&p2u, &src_x2, &src_y2);
6810     src_radius = _cairo_matrix_transformed_circle_major_axis (&p2u, 0.5);
6811
6812     p2u = mask->matrix;
6813     status = cairo_matrix_invert (&p2u);
6814     /* cairo_pattern_set_matrix ensures the matrix is invertible */
6815     assert (status == CAIRO_INT_STATUS_SUCCESS);
6816     mask_x1 = 0;
6817     mask_y1 = 0;
6818     mask_x2 = mask_width;
6819     mask_y2 = mask_height;
6820     cairo_matrix_transform_point (&p2u, &mask_x1, &mask_y1);
6821     cairo_matrix_transform_point (&p2u, &mask_x2, &mask_y2);
6822     mask_radius = _cairo_matrix_transformed_circle_major_axis (&p2u, 0.5);
6823
6824     if (src_radius < mask_radius)
6825         e = src_radius;
6826     else
6827         e = mask_radius;
6828
6829     if (fabs(src_x1 - mask_x1) > e ||
6830         fabs(src_x2 - mask_x2) > e ||
6831         fabs(src_y1 - mask_y1) > e ||
6832         fabs(src_y2 - mask_y2) > e)
6833         return CAIRO_INT_STATUS_UNSUPPORTED;
6834
6835     /* Check both images have same device offset */
6836     if (fabs(src_x_offset - mask_x_offset) > e ||
6837         fabs(src_y_offset - mask_y_offset) > e)
6838         return CAIRO_INT_STATUS_UNSUPPORTED;
6839
6840     if (need_smask) {
6841         status = _cairo_pdf_surface_add_source_surface (surface,
6842                                                         NULL,
6843                                                         mask,
6844                                                         op,
6845                                                         source->filter,
6846                                                         FALSE,
6847                                                         TRUE,
6848                                                         extents,
6849                                                         NULL,
6850                                                         &smask_res,
6851                                                         &mask_width,
6852                                                         &mask_height,
6853                                                         &mask_x_offset,
6854                                                         &mask_y_offset,
6855                                                         &extents2);
6856         if (unlikely (status))
6857             return status;
6858     }
6859
6860     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
6861     if (unlikely (status))
6862         return status;
6863
6864     _cairo_output_stream_printf (surface->output, "q\n");
6865     status = _cairo_pdf_surface_paint_surface_pattern (surface, op, source, extents,
6866                                                        need_smask ? &smask_res : NULL,
6867                                                        FALSE);
6868     if (unlikely (status))
6869         return status;
6870
6871     _cairo_output_stream_printf (surface->output, "Q\n");
6872
6873     status = _cairo_output_stream_get_status (surface->output);
6874
6875
6876     return status;
6877 }
6878
6879 /* A PDF stencil mask is an A1 mask used with the current color */
6880 static cairo_int_status_t
6881 _cairo_pdf_surface_emit_stencil_mask (cairo_pdf_surface_t         *surface,
6882                                       cairo_operator_t             op,
6883                                       const cairo_pattern_t       *source,
6884                                       const cairo_pattern_t       *mask,
6885                                       const cairo_rectangle_int_t *extents)
6886 {
6887     cairo_int_status_t status;
6888     cairo_image_surface_t  *image;
6889     void                   *image_extra;
6890     cairo_image_transparency_t transparency;
6891     cairo_pdf_resource_t pattern_res = {0};
6892
6893     if (! (source->type == CAIRO_PATTERN_TYPE_SOLID &&
6894            (mask->type == CAIRO_PATTERN_TYPE_SURFACE || mask->type == CAIRO_PATTERN_TYPE_RASTER_SOURCE)))
6895         return CAIRO_INT_STATUS_UNSUPPORTED;
6896
6897     if (mask->type == CAIRO_PATTERN_TYPE_SURFACE &&
6898         ((cairo_surface_pattern_t *) mask)->surface->type == CAIRO_SURFACE_TYPE_RECORDING)
6899     {
6900         return CAIRO_INT_STATUS_UNSUPPORTED;
6901     }
6902
6903     status = _cairo_pdf_surface_acquire_source_image_from_pattern (surface, mask,
6904                                                                    &image, &image_extra);
6905     if (unlikely (status))
6906         return status;
6907
6908     if (image->base.status)
6909         return image->base.status;
6910
6911     transparency = _cairo_image_analyze_transparency (image);
6912     if (transparency != CAIRO_IMAGE_IS_OPAQUE &&
6913         transparency != CAIRO_IMAGE_HAS_BILEVEL_ALPHA)
6914     {
6915         status = CAIRO_INT_STATUS_UNSUPPORTED;
6916         goto cleanup;
6917     }
6918
6919     status = _cairo_pdf_surface_select_pattern (surface, source,
6920                                                 pattern_res, FALSE);
6921     if (unlikely (status))
6922         return status;
6923
6924     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
6925     if (unlikely (status))
6926         return status;
6927
6928     _cairo_output_stream_printf (surface->output, "q\n");
6929     status = _cairo_pdf_surface_paint_surface_pattern (surface, op, mask, extents, NULL, TRUE);
6930     if (unlikely (status))
6931         return status;
6932
6933     _cairo_output_stream_printf (surface->output, "Q\n");
6934
6935     status = _cairo_output_stream_get_status (surface->output);
6936
6937 cleanup:
6938     _cairo_pdf_surface_release_source_image_from_pattern (surface, mask, image, image_extra);
6939
6940     return status;
6941 }
6942
6943 static cairo_int_status_t
6944 _cairo_pdf_surface_set_clip (cairo_pdf_surface_t *surface,
6945                              cairo_composite_rectangles_t *composite)
6946 {
6947     cairo_clip_t *clip = composite->clip;
6948
6949     if (_cairo_composite_rectangles_can_reduce_clip (composite, clip))
6950         clip = NULL;
6951
6952     if (clip == NULL) {
6953         if (_cairo_composite_rectangles_can_reduce_clip (composite,
6954                                                          surface->clipper.clip))
6955             return CAIRO_STATUS_SUCCESS;
6956     }
6957
6958     return _cairo_surface_clipper_set_clip (&surface->clipper, clip);
6959 }
6960
6961 static cairo_int_status_t
6962 _cairo_pdf_surface_paint (void                  *abstract_surface,
6963                           cairo_operator_t       op,
6964                           const cairo_pattern_t *source,
6965                           const cairo_clip_t    *clip)
6966 {
6967     cairo_pdf_surface_t *surface = abstract_surface;
6968     cairo_pdf_smask_group_t *group;
6969     cairo_pdf_resource_t pattern_res, gstate_res;
6970     cairo_composite_rectangles_t extents;
6971     cairo_int_status_t status;
6972
6973     status = _cairo_composite_rectangles_init_for_paint (&extents,
6974                                                          &surface->base,
6975                                                          op, source, clip);
6976     if (unlikely (status))
6977         return status;
6978
6979     if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
6980         status = _cairo_pdf_surface_analyze_operation (surface, op, source, &extents.bounded);
6981         goto cleanup;
6982     } else if (surface->paginated_mode == CAIRO_PAGINATED_MODE_FALLBACK) {
6983         status = _cairo_pdf_surface_start_fallback (surface);
6984         if (unlikely (status))
6985             goto cleanup;
6986     }
6987
6988     assert (_cairo_pdf_surface_operation_supported (surface, op, source, &extents.bounded));
6989
6990     status = _cairo_pdf_surface_set_clip (surface, &extents);
6991     if (unlikely (status))
6992         goto cleanup;
6993
6994     status = _cairo_pdf_surface_select_operator (surface, op);
6995     if (unlikely (status))
6996         goto cleanup;
6997
6998     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
6999     if (unlikely (status))
7000         goto cleanup;
7001
7002     if (_can_paint_pattern (source)) {
7003         _cairo_output_stream_printf (surface->output, "q\n");
7004         status = _cairo_pdf_surface_paint_pattern (surface,
7005                                                    op,
7006                                                    source,
7007                                                    &extents.bounded,
7008                                                    FALSE);
7009         if (unlikely (status))
7010             goto cleanup;
7011
7012         _cairo_output_stream_printf (surface->output, "Q\n");
7013         _cairo_composite_rectangles_fini (&extents);
7014         return _cairo_output_stream_get_status (surface->output);
7015     }
7016
7017     pattern_res.id = 0;
7018     gstate_res.id = 0;
7019     status = _cairo_pdf_surface_add_pdf_pattern (surface, source, op,
7020                                                  &extents.bounded,
7021                                                  &pattern_res, &gstate_res);
7022     if (unlikely (status))
7023         goto cleanup;
7024
7025     if (gstate_res.id != 0) {
7026         group = _cairo_pdf_surface_create_smask_group (surface, &extents.bounded);
7027         if (unlikely (group == NULL)) {
7028             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7029             goto cleanup;
7030         }
7031
7032         group->operation = PDF_PAINT;
7033         status = _cairo_pattern_create_copy (&group->source, source);
7034         if (unlikely (status)) {
7035             _cairo_pdf_smask_group_destroy (group);
7036             goto cleanup;
7037         }
7038         group->source_res = pattern_res;
7039         status = _cairo_pdf_surface_add_smask_group (surface, group);
7040         if (unlikely (status)) {
7041             _cairo_pdf_smask_group_destroy (group);
7042             goto cleanup;
7043         }
7044
7045         status = _cairo_pdf_surface_add_smask (surface, gstate_res);
7046         if (unlikely (status))
7047             goto cleanup;
7048
7049         status = _cairo_pdf_surface_add_xobject (surface, group->group_res);
7050         if (unlikely (status))
7051             goto cleanup;
7052
7053         _cairo_output_stream_printf (surface->output,
7054                                      "q /s%d gs /x%d Do Q\n",
7055                                      gstate_res.id,
7056                                      group->group_res.id);
7057     } else {
7058         status = _cairo_pdf_surface_select_pattern (surface, source,
7059                                                     pattern_res, FALSE);
7060         if (unlikely (status))
7061             goto cleanup;
7062
7063         _cairo_output_stream_printf (surface->output,
7064                                      "0 0 %f %f re f\n",
7065                                      surface->width, surface->height);
7066
7067         status = _cairo_pdf_surface_unselect_pattern (surface);
7068         if (unlikely (status))
7069             goto cleanup;
7070     }
7071
7072     _cairo_composite_rectangles_fini (&extents);
7073     return _cairo_output_stream_get_status (surface->output);
7074
7075 cleanup:
7076     _cairo_composite_rectangles_fini (&extents);
7077     return status;
7078 }
7079
7080 static cairo_int_status_t
7081 _cairo_pdf_surface_mask (void                   *abstract_surface,
7082                          cairo_operator_t        op,
7083                          const cairo_pattern_t  *source,
7084                          const cairo_pattern_t  *mask,
7085                          const cairo_clip_t     *clip)
7086 {
7087     cairo_pdf_surface_t *surface = abstract_surface;
7088     cairo_pdf_smask_group_t *group;
7089     cairo_composite_rectangles_t extents;
7090     cairo_int_status_t status;
7091     cairo_rectangle_int_t r;
7092     cairo_box_t box;
7093
7094     status = _cairo_composite_rectangles_init_for_mask (&extents,
7095                                                         &surface->base,
7096                                                         op, source, mask, clip);
7097     if (unlikely (status))
7098         return status;
7099
7100     if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
7101         cairo_int_status_t source_status, mask_status;
7102
7103         status = _cairo_pdf_surface_analyze_operation (surface, op, source, &extents.bounded);
7104         if (_cairo_int_status_is_error (status))
7105             goto cleanup;
7106         source_status = status;
7107
7108         if (mask->has_component_alpha) {
7109             status = CAIRO_INT_STATUS_UNSUPPORTED;
7110         } else {
7111             status = _cairo_pdf_surface_analyze_operation (surface, op, mask, &extents.bounded);
7112             if (_cairo_int_status_is_error (status))
7113                 goto cleanup;
7114         }
7115         mask_status = status;
7116
7117         _cairo_composite_rectangles_fini (&extents);
7118         return _cairo_analysis_surface_merge_status (source_status,
7119                                                      mask_status);
7120     } else if (surface->paginated_mode == CAIRO_PAGINATED_MODE_FALLBACK) {
7121         status = _cairo_pdf_surface_start_fallback (surface);
7122         if (unlikely (status))
7123             goto cleanup;
7124     }
7125
7126     assert (_cairo_pdf_surface_operation_supported (surface, op, source, &extents.bounded));
7127     assert (_cairo_pdf_surface_operation_supported (surface, op, mask, &extents.bounded));
7128
7129     /* get the accurate extents */
7130     status = _cairo_pattern_get_ink_extents (source, &r);
7131     if (unlikely (status))
7132         goto cleanup;
7133
7134     /* XXX slight impedance mismatch */
7135     _cairo_box_from_rectangle (&box, &r);
7136     status = _cairo_composite_rectangles_intersect_source_extents (&extents,
7137                                                                    &box);
7138     if (unlikely (status))
7139         goto cleanup;
7140
7141     status = _cairo_pattern_get_ink_extents (mask, &r);
7142     if (unlikely (status))
7143         goto cleanup;
7144
7145     _cairo_box_from_rectangle (&box, &r);
7146     status = _cairo_composite_rectangles_intersect_mask_extents (&extents,
7147                                                                  &box);
7148     if (unlikely (status))
7149         goto cleanup;
7150
7151     status = _cairo_pdf_surface_set_clip (surface, &extents);
7152     if (unlikely (status))
7153         goto cleanup;
7154
7155     status = _cairo_pdf_surface_select_operator (surface, op);
7156     if (unlikely (status))
7157         goto cleanup;
7158
7159     /* Check if we can combine source and mask into a smask image */
7160     status = _cairo_pdf_surface_emit_combined_smask (surface, op, source, mask, &extents.bounded);
7161     if (status != CAIRO_INT_STATUS_UNSUPPORTED)
7162         goto cleanup;
7163
7164     /* Check if we can use a stencil mask */
7165     status = _cairo_pdf_surface_emit_stencil_mask (surface, op, source, mask, &extents.bounded);
7166     if (status != CAIRO_INT_STATUS_UNSUPPORTED)
7167         goto cleanup;
7168
7169     group = _cairo_pdf_surface_create_smask_group (surface, &extents.bounded);
7170     if (unlikely (group == NULL)) {
7171         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7172         goto cleanup;
7173     }
7174
7175     group->operation = PDF_MASK;
7176     status = _cairo_pattern_create_copy (&group->source, source);
7177     if (unlikely (status)) {
7178         _cairo_pdf_smask_group_destroy (group);
7179         goto cleanup;
7180     }
7181     status = _cairo_pattern_create_copy (&group->mask, mask);
7182     if (unlikely (status)) {
7183         _cairo_pdf_smask_group_destroy (group);
7184         goto cleanup;
7185     }
7186     group->source_res = _cairo_pdf_surface_new_object (surface);
7187     if (group->source_res.id == 0) {
7188         _cairo_pdf_smask_group_destroy (group);
7189         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7190         goto cleanup;
7191     }
7192
7193     status = _cairo_pdf_surface_add_smask_group (surface, group);
7194     if (unlikely (status)) {
7195         _cairo_pdf_smask_group_destroy (group);
7196         goto cleanup;
7197     }
7198
7199     status = _cairo_pdf_surface_add_smask (surface, group->group_res);
7200     if (unlikely (status))
7201         goto cleanup;
7202
7203     status = _cairo_pdf_surface_add_xobject (surface, group->source_res);
7204     if (unlikely (status))
7205         goto cleanup;
7206
7207     status = _cairo_pdf_operators_flush (&surface->pdf_operators);
7208     if (unlikely (status))
7209         goto cleanup;
7210
7211     _cairo_output_stream_printf (surface->output,
7212                                  "q /s%d gs /x%d Do Q\n",
7213                                  group->group_res.id,
7214                                  group->source_res.id);
7215
7216     _cairo_composite_rectangles_fini (&extents);
7217     return _cairo_output_stream_get_status (surface->output);
7218
7219 cleanup:
7220     _cairo_composite_rectangles_fini (&extents);
7221     return status;
7222 }
7223
7224 static cairo_int_status_t
7225 _cairo_pdf_surface_stroke (void                 *abstract_surface,
7226                            cairo_operator_t      op,
7227                            const cairo_pattern_t *source,
7228                            const cairo_path_fixed_t     *path,
7229                            const cairo_stroke_style_t   *style,
7230                            const cairo_matrix_t *ctm,
7231                            const cairo_matrix_t *ctm_inverse,
7232                            double                tolerance,
7233                            cairo_antialias_t     antialias,
7234                            const cairo_clip_t   *clip)
7235 {
7236     cairo_pdf_surface_t *surface = abstract_surface;
7237     cairo_pdf_smask_group_t *group;
7238     cairo_pdf_resource_t pattern_res, gstate_res;
7239     cairo_composite_rectangles_t extents;
7240     cairo_int_status_t status;
7241
7242     status = _cairo_composite_rectangles_init_for_stroke (&extents,
7243                                                           &surface->base,
7244                                                           op, source,
7245                                                           path, style, ctm,
7246                                                           clip);
7247     if (unlikely (status))
7248         return status;
7249
7250     /* use the more accurate extents */
7251     if (extents.is_bounded) {
7252         cairo_rectangle_int_t mask;
7253         cairo_box_t box;
7254
7255         status = _cairo_path_fixed_stroke_extents (path, style,
7256                                                    ctm, ctm_inverse,
7257                                                    tolerance,
7258                                                    &mask);
7259         if (unlikely (status))
7260             goto cleanup;
7261
7262         _cairo_box_from_rectangle (&box, &mask);
7263         status = _cairo_composite_rectangles_intersect_mask_extents (&extents,
7264                                                                      &box);
7265         if (unlikely (status))
7266             goto cleanup;
7267     }
7268
7269     if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
7270         status = _cairo_pdf_surface_analyze_operation (surface, op, source, &extents.bounded);
7271         goto cleanup;
7272     }
7273
7274     assert (_cairo_pdf_surface_operation_supported (surface, op, source, &extents.bounded));
7275
7276     status = _cairo_pdf_surface_set_clip (surface, &extents);
7277     if (unlikely (status))
7278         goto cleanup;
7279
7280     pattern_res.id = 0;
7281     gstate_res.id = 0;
7282     status = _cairo_pdf_surface_add_pdf_pattern (surface, source, op,
7283                                                  &extents.bounded,
7284                                                  &pattern_res, &gstate_res);
7285     if (unlikely (status))
7286         goto cleanup;
7287
7288     status = _cairo_pdf_surface_select_operator (surface, op);
7289     if (unlikely (status))
7290         goto cleanup;
7291
7292     if (gstate_res.id != 0) {
7293         group = _cairo_pdf_surface_create_smask_group (surface, &extents.bounded);
7294         if (unlikely (group == NULL)) {
7295             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7296             goto cleanup;
7297         }
7298
7299         group->operation = PDF_STROKE;
7300         status = _cairo_pattern_create_copy (&group->source, source);
7301         if (unlikely (status)) {
7302             _cairo_pdf_smask_group_destroy (group);
7303             goto cleanup;
7304         }
7305         group->source_res = pattern_res;
7306         status = _cairo_path_fixed_init_copy (&group->path, path);
7307         if (unlikely (status)) {
7308             _cairo_pdf_smask_group_destroy (group);
7309             goto cleanup;
7310         }
7311
7312         group->style = *style;
7313         group->ctm = *ctm;
7314         group->ctm_inverse = *ctm_inverse;
7315         status = _cairo_pdf_surface_add_smask_group (surface, group);
7316         if (unlikely (status)) {
7317             _cairo_pdf_smask_group_destroy (group);
7318             goto cleanup;
7319         }
7320
7321         status = _cairo_pdf_surface_add_smask (surface, gstate_res);
7322         if (unlikely (status))
7323             goto cleanup;
7324
7325         status = _cairo_pdf_surface_add_xobject (surface, group->group_res);
7326         if (unlikely (status))
7327             goto cleanup;
7328
7329         status = _cairo_pdf_operators_flush (&surface->pdf_operators);
7330         if (unlikely (status))
7331             goto cleanup;
7332
7333         _cairo_output_stream_printf (surface->output,
7334                                      "q /s%d gs /x%d Do Q\n",
7335                                      gstate_res.id,
7336                                      group->group_res.id);
7337     } else {
7338         status = _cairo_pdf_surface_select_pattern (surface, source, pattern_res, TRUE);
7339         if (unlikely (status))
7340             goto cleanup;
7341
7342         status = _cairo_pdf_operators_stroke (&surface->pdf_operators,
7343                                               path,
7344                                               style,
7345                                               ctm,
7346                                               ctm_inverse);
7347         if (unlikely (status))
7348             goto cleanup;
7349
7350         status = _cairo_pdf_surface_unselect_pattern (surface);
7351         if (unlikely (status))
7352             goto cleanup;
7353     }
7354
7355     _cairo_composite_rectangles_fini (&extents);
7356     return _cairo_output_stream_get_status (surface->output);
7357
7358 cleanup:
7359     _cairo_composite_rectangles_fini (&extents);
7360     return status;
7361 }
7362
7363 static cairo_int_status_t
7364 _cairo_pdf_surface_fill (void                   *abstract_surface,
7365                          cairo_operator_t        op,
7366                          const cairo_pattern_t  *source,
7367                          const cairo_path_fixed_t*path,
7368                          cairo_fill_rule_t       fill_rule,
7369                          double                  tolerance,
7370                          cairo_antialias_t       antialias,
7371                          const cairo_clip_t     *clip)
7372 {
7373     cairo_pdf_surface_t *surface = abstract_surface;
7374     cairo_int_status_t status;
7375     cairo_pdf_smask_group_t *group;
7376     cairo_pdf_resource_t pattern_res, gstate_res;
7377     cairo_composite_rectangles_t extents;
7378
7379     status = _cairo_composite_rectangles_init_for_fill (&extents,
7380                                                         &surface->base,
7381                                                         op, source, path,
7382                                                         clip);
7383     if (unlikely (status))
7384         return status;
7385
7386     /* use the more accurate extents */
7387     if (extents.is_bounded) {
7388         cairo_rectangle_int_t mask;
7389         cairo_box_t box;
7390
7391         _cairo_path_fixed_fill_extents (path,
7392                                         fill_rule,
7393                                         tolerance,
7394                                         &mask);
7395
7396         _cairo_box_from_rectangle (&box, &mask);
7397         status = _cairo_composite_rectangles_intersect_mask_extents (&extents,
7398                                                                      &box);
7399         if (unlikely (status))
7400             goto cleanup;
7401     }
7402
7403     if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
7404         status = _cairo_pdf_surface_analyze_operation (surface, op, source, &extents.bounded);
7405         goto cleanup;
7406     } else if (surface->paginated_mode == CAIRO_PAGINATED_MODE_FALLBACK) {
7407         status = _cairo_pdf_surface_start_fallback (surface);
7408         if (unlikely (status))
7409             goto cleanup;
7410     }
7411
7412     assert (_cairo_pdf_surface_operation_supported (surface, op, source, &extents.bounded));
7413
7414     status = _cairo_pdf_surface_set_clip (surface, &extents);
7415     if (unlikely (status))
7416         goto cleanup;
7417
7418     status = _cairo_pdf_surface_select_operator (surface, op);
7419     if (unlikely (status))
7420         goto cleanup;
7421
7422     if (_can_paint_pattern (source)) {
7423         status = _cairo_pdf_operators_flush (&surface->pdf_operators);
7424         if (unlikely (status))
7425             goto cleanup;
7426
7427         _cairo_output_stream_printf (surface->output, "q\n");
7428         status =  _cairo_pdf_operators_clip (&surface->pdf_operators,
7429                                              path,
7430                                              fill_rule);
7431         if (unlikely (status))
7432             goto cleanup;
7433
7434         status = _cairo_pdf_surface_paint_pattern (surface,
7435                                                    op,
7436                                                    source,
7437                                                    &extents.bounded,
7438                                                    FALSE);
7439         if (unlikely (status))
7440             goto cleanup;
7441
7442         _cairo_output_stream_printf (surface->output, "Q\n");
7443         status = _cairo_output_stream_get_status (surface->output);
7444         goto cleanup;
7445     }
7446
7447     pattern_res.id = 0;
7448     gstate_res.id = 0;
7449     status = _cairo_pdf_surface_add_pdf_pattern (surface, source, op,
7450                                                  &extents.bounded,
7451                                                  &pattern_res, &gstate_res);
7452     if (unlikely (status))
7453         goto cleanup;
7454
7455     if (gstate_res.id != 0) {
7456         group = _cairo_pdf_surface_create_smask_group (surface, &extents.bounded);
7457         if (unlikely (group == NULL)) {
7458             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7459             goto cleanup;
7460         }
7461
7462         group->operation = PDF_FILL;
7463         status = _cairo_pattern_create_copy (&group->source, source);
7464         if (unlikely (status)) {
7465             _cairo_pdf_smask_group_destroy (group);
7466             goto cleanup;
7467         }
7468         group->source_res = pattern_res;
7469         status = _cairo_path_fixed_init_copy (&group->path, path);
7470         if (unlikely (status)) {
7471             _cairo_pdf_smask_group_destroy (group);
7472             goto cleanup;
7473         }
7474
7475         group->fill_rule = fill_rule;
7476         status = _cairo_pdf_surface_add_smask_group (surface, group);
7477         if (unlikely (status)) {
7478             _cairo_pdf_smask_group_destroy (group);
7479             goto cleanup;
7480         }
7481
7482         status = _cairo_pdf_surface_add_smask (surface, gstate_res);
7483         if (unlikely (status))
7484             goto cleanup;
7485
7486         status = _cairo_pdf_surface_add_xobject (surface, group->group_res);
7487         if (unlikely (status))
7488             goto cleanup;
7489
7490         status = _cairo_pdf_operators_flush (&surface->pdf_operators);
7491         if (unlikely (status))
7492             goto cleanup;
7493
7494         _cairo_output_stream_printf (surface->output,
7495                                      "q /s%d gs /x%d Do Q\n",
7496                                      gstate_res.id,
7497                                      group->group_res.id);
7498     } else {
7499         status = _cairo_pdf_surface_select_pattern (surface, source, pattern_res, FALSE);
7500         if (unlikely (status))
7501             goto cleanup;
7502
7503         status = _cairo_pdf_operators_fill (&surface->pdf_operators,
7504                                             path,
7505                                             fill_rule);
7506         if (unlikely (status))
7507             goto cleanup;
7508
7509         status = _cairo_pdf_surface_unselect_pattern (surface);
7510         if (unlikely (status))
7511             goto cleanup;
7512     }
7513
7514     _cairo_composite_rectangles_fini (&extents);
7515     return _cairo_output_stream_get_status (surface->output);
7516
7517 cleanup:
7518     _cairo_composite_rectangles_fini (&extents);
7519     return status;
7520 }
7521
7522 static cairo_int_status_t
7523 _cairo_pdf_surface_fill_stroke (void                    *abstract_surface,
7524                                 cairo_operator_t         fill_op,
7525                                 const cairo_pattern_t   *fill_source,
7526                                 cairo_fill_rule_t        fill_rule,
7527                                 double                   fill_tolerance,
7528                                 cairo_antialias_t        fill_antialias,
7529                                 const cairo_path_fixed_t*path,
7530                                 cairo_operator_t         stroke_op,
7531                                 const cairo_pattern_t   *stroke_source,
7532                                 const cairo_stroke_style_t *stroke_style,
7533                                 const cairo_matrix_t    *stroke_ctm,
7534                                 const cairo_matrix_t    *stroke_ctm_inverse,
7535                                 double                   stroke_tolerance,
7536                                 cairo_antialias_t        stroke_antialias,
7537                                 const cairo_clip_t      *clip)
7538 {
7539     cairo_pdf_surface_t *surface = abstract_surface;
7540     cairo_int_status_t status;
7541     cairo_pdf_resource_t fill_pattern_res, stroke_pattern_res, gstate_res;
7542     cairo_composite_rectangles_t extents;
7543
7544     /* During analysis we return unsupported and let the _fill and
7545      * _stroke functions that are on the fallback path do the analysis
7546      * for us. During render we may still encounter unsupported
7547      * combinations of fill/stroke patterns. However we can return
7548      * unsupported anytime to let the _fill and _stroke functions take
7549      * over.
7550      */
7551     if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE)
7552         return CAIRO_INT_STATUS_UNSUPPORTED;
7553
7554     /* PDF rendering of fill-stroke is not the same as cairo when
7555      * either the fill or stroke is not opaque.
7556      */
7557     if ( !_cairo_pattern_is_opaque (fill_source, NULL) ||
7558          !_cairo_pattern_is_opaque (stroke_source, NULL))
7559     {
7560         return CAIRO_INT_STATUS_UNSUPPORTED;
7561     }
7562
7563     if (fill_op != stroke_op)
7564         return CAIRO_INT_STATUS_UNSUPPORTED;
7565
7566     /* Compute the operation extents using the stroke which will naturally
7567      * be larger than the fill extents.
7568      */
7569     status = _cairo_composite_rectangles_init_for_stroke (&extents,
7570                                                           &surface->base,
7571                                                           stroke_op, stroke_source,
7572                                                           path, stroke_style, stroke_ctm,
7573                                                           clip);
7574     if (unlikely (status))
7575         return status;
7576
7577     /* use the more accurate extents */
7578     if (extents.is_bounded) {
7579         cairo_rectangle_int_t mask;
7580         cairo_box_t box;
7581
7582         status = _cairo_path_fixed_stroke_extents (path, stroke_style,
7583                                                    stroke_ctm, stroke_ctm_inverse,
7584                                                    stroke_tolerance,
7585                                                    &mask);
7586         if (unlikely (status))
7587             goto cleanup;
7588
7589         _cairo_box_from_rectangle (&box, &mask);
7590         status = _cairo_composite_rectangles_intersect_mask_extents (&extents,
7591                                                                      &box);
7592         if (unlikely (status))
7593             goto cleanup;
7594     }
7595
7596     status = _cairo_pdf_surface_set_clip (surface, &extents);
7597     if (unlikely (status))
7598         goto cleanup;
7599
7600     status = _cairo_pdf_surface_select_operator (surface, fill_op);
7601     if (unlikely (status))
7602         goto cleanup;
7603
7604     /* use the more accurate extents */
7605     if (extents.is_bounded) {
7606         cairo_rectangle_int_t mask;
7607         cairo_box_t box;
7608
7609         _cairo_path_fixed_fill_extents (path,
7610                                         fill_rule,
7611                                         fill_tolerance,
7612                                         &mask);
7613
7614         _cairo_box_from_rectangle (&box, &mask);
7615         status = _cairo_composite_rectangles_intersect_mask_extents (&extents,
7616                                                                      &box);
7617         if (unlikely (status))
7618             goto cleanup;
7619     }
7620
7621     fill_pattern_res.id = 0;
7622     gstate_res.id = 0;
7623     status = _cairo_pdf_surface_add_pdf_pattern (surface, fill_source,
7624                                                  fill_op,
7625                                                  &extents.bounded,
7626                                                  &fill_pattern_res,
7627                                                  &gstate_res);
7628     if (unlikely (status))
7629         goto cleanup;
7630
7631     assert (gstate_res.id == 0);
7632
7633     stroke_pattern_res.id = 0;
7634     gstate_res.id = 0;
7635     status = _cairo_pdf_surface_add_pdf_pattern (surface,
7636                                                  stroke_source,
7637                                                  stroke_op,
7638                                                  &extents.bounded,
7639                                                  &stroke_pattern_res,
7640                                                  &gstate_res);
7641     if (unlikely (status))
7642         goto cleanup;
7643
7644     assert (gstate_res.id == 0);
7645
7646     /* As PDF has separate graphics state for fill and stroke we can
7647      * select both at the same time */
7648     status = _cairo_pdf_surface_select_pattern (surface, fill_source,
7649                                                 fill_pattern_res, FALSE);
7650     if (unlikely (status))
7651         goto cleanup;
7652
7653     status = _cairo_pdf_surface_select_pattern (surface, stroke_source,
7654                                                 stroke_pattern_res, TRUE);
7655     if (unlikely (status))
7656         goto cleanup;
7657
7658     status = _cairo_pdf_operators_fill_stroke (&surface->pdf_operators,
7659                                                path,
7660                                                fill_rule,
7661                                                stroke_style,
7662                                                stroke_ctm,
7663                                                stroke_ctm_inverse);
7664     if (unlikely (status))
7665         goto cleanup;
7666
7667     status = _cairo_pdf_surface_unselect_pattern (surface);
7668     if (unlikely (status))
7669         goto cleanup;
7670
7671     _cairo_composite_rectangles_fini (&extents);
7672     return _cairo_output_stream_get_status (surface->output);
7673
7674 cleanup:
7675     _cairo_composite_rectangles_fini (&extents);
7676     return status;
7677 }
7678
7679 static cairo_bool_t
7680 _cairo_pdf_surface_has_show_text_glyphs (void                   *abstract_surface)
7681 {
7682     return TRUE;
7683 }
7684
7685 static cairo_int_status_t
7686 _cairo_pdf_surface_show_text_glyphs (void                       *abstract_surface,
7687                                      cairo_operator_t            op,
7688                                      const cairo_pattern_t      *source,
7689                                      const char                 *utf8,
7690                                      int                         utf8_len,
7691                                      cairo_glyph_t              *glyphs,
7692                                      int                         num_glyphs,
7693                                      const cairo_text_cluster_t *clusters,
7694                                      int                         num_clusters,
7695                                      cairo_text_cluster_flags_t  cluster_flags,
7696                                      cairo_scaled_font_t        *scaled_font,
7697                                      const cairo_clip_t         *clip)
7698 {
7699     cairo_pdf_surface_t *surface = abstract_surface;
7700     cairo_pdf_smask_group_t *group;
7701     cairo_pdf_resource_t pattern_res, gstate_res;
7702     cairo_composite_rectangles_t extents;
7703     cairo_bool_t overlap;
7704     cairo_int_status_t status;
7705
7706     status = _cairo_composite_rectangles_init_for_glyphs (&extents,
7707                                                           &surface->base,
7708                                                           op, source,
7709                                                           scaled_font,
7710                                                           glyphs, num_glyphs,
7711                                                           clip,
7712                                                           &overlap);
7713     if (unlikely (status))
7714         return status;
7715
7716     if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE) {
7717         status = _cairo_pdf_surface_analyze_operation (surface, op, source, &extents.bounded);
7718         goto cleanup;
7719     }
7720
7721     assert (_cairo_pdf_surface_operation_supported (surface, op, source, &extents.bounded));
7722
7723     status = _cairo_pdf_surface_set_clip (surface, &extents);
7724     if (unlikely (status))
7725         goto cleanup;
7726
7727     pattern_res.id = 0;
7728     gstate_res.id = 0;
7729     status = _cairo_pdf_surface_add_pdf_pattern (surface, source, op,
7730                                                  &extents.bounded,
7731                                                  &pattern_res, &gstate_res);
7732     if (unlikely (status))
7733         goto cleanup;
7734
7735     status = _cairo_pdf_surface_select_operator (surface, op);
7736     if (unlikely (status))
7737         goto cleanup;
7738
7739     if (gstate_res.id != 0) {
7740         group = _cairo_pdf_surface_create_smask_group (surface, &extents.bounded);
7741         if (unlikely (group == NULL)) {
7742             status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7743             goto cleanup;
7744         }
7745
7746         group->operation = PDF_SHOW_GLYPHS;
7747         status = _cairo_pattern_create_copy (&group->source, source);
7748         if (unlikely (status)) {
7749             _cairo_pdf_smask_group_destroy (group);
7750             goto cleanup;
7751         }
7752         group->source_res = pattern_res;
7753
7754         if (utf8_len) {
7755             group->utf8 = malloc (utf8_len);
7756             if (unlikely (group->utf8 == NULL)) {
7757                 _cairo_pdf_smask_group_destroy (group);
7758                 status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7759                 goto cleanup;
7760             }
7761             memcpy (group->utf8, utf8, utf8_len);
7762         }
7763         group->utf8_len = utf8_len;
7764
7765         if (num_glyphs) {
7766             group->glyphs = _cairo_malloc_ab (num_glyphs, sizeof (cairo_glyph_t));
7767             if (unlikely (group->glyphs == NULL)) {
7768                 _cairo_pdf_smask_group_destroy (group);
7769                 status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7770                 goto cleanup;
7771             }
7772             memcpy (group->glyphs, glyphs, sizeof (cairo_glyph_t) * num_glyphs);
7773         }
7774         group->num_glyphs = num_glyphs;
7775
7776         if (num_clusters) {
7777             group->clusters = _cairo_malloc_ab (num_clusters, sizeof (cairo_text_cluster_t));
7778             if (unlikely (group->clusters == NULL)) {
7779                 _cairo_pdf_smask_group_destroy (group);
7780                 status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
7781                 goto cleanup;
7782             }
7783             memcpy (group->clusters, clusters, sizeof (cairo_text_cluster_t) * num_clusters);
7784         }
7785         group->num_clusters = num_clusters;
7786
7787         group->scaled_font = cairo_scaled_font_reference (scaled_font);
7788         status = _cairo_pdf_surface_add_smask_group (surface, group);
7789         if (unlikely (status)) {
7790             _cairo_pdf_smask_group_destroy (group);
7791             goto cleanup;
7792         }
7793
7794         status = _cairo_pdf_surface_add_smask (surface, gstate_res);
7795         if (unlikely (status))
7796             goto cleanup;
7797
7798         status = _cairo_pdf_surface_add_xobject (surface, group->group_res);
7799         if (unlikely (status))
7800             goto cleanup;
7801
7802         status = _cairo_pdf_operators_flush (&surface->pdf_operators);
7803         if (unlikely (status))
7804             goto cleanup;
7805
7806         _cairo_output_stream_printf (surface->output,
7807                                      "q /s%d gs /x%d Do Q\n",
7808                                      gstate_res.id,
7809                                      group->group_res.id);
7810     } else {
7811         status = _cairo_pdf_surface_select_pattern (surface, source, pattern_res, FALSE);
7812         if (unlikely (status))
7813             goto cleanup;
7814
7815         /* Each call to show_glyphs() with a transclucent pattern must
7816          * be in a separate text object otherwise overlapping text
7817          * from separate calls to show_glyphs will not composite with
7818          * each other. */
7819         if (! _cairo_pattern_is_opaque (source, &extents.bounded)) {
7820             status = _cairo_pdf_operators_flush (&surface->pdf_operators);
7821             if (unlikely (status))
7822                 goto cleanup;
7823         }
7824
7825         status = _cairo_pdf_operators_show_text_glyphs (&surface->pdf_operators,
7826                                                         utf8, utf8_len,
7827                                                         glyphs, num_glyphs,
7828                                                         clusters, num_clusters,
7829                                                         cluster_flags,
7830                                                         scaled_font);
7831         if (unlikely (status))
7832             goto cleanup;
7833
7834         status = _cairo_pdf_surface_unselect_pattern (surface);
7835         if (unlikely (status))
7836             goto cleanup;
7837     }
7838
7839     _cairo_composite_rectangles_fini (&extents);
7840     return _cairo_output_stream_get_status (surface->output);
7841
7842 cleanup:
7843     _cairo_composite_rectangles_fini (&extents);
7844     return status;
7845 }
7846
7847 static const char **
7848 _cairo_pdf_surface_get_supported_mime_types (void                *abstract_surface)
7849 {
7850     return _cairo_pdf_supported_mime_types;
7851 }
7852
7853 static void
7854 _cairo_pdf_surface_set_paginated_mode (void                     *abstract_surface,
7855                                        cairo_paginated_mode_t    paginated_mode)
7856 {
7857     cairo_pdf_surface_t *surface = abstract_surface;
7858
7859     surface->paginated_mode = paginated_mode;
7860 }
7861
7862 static const cairo_surface_backend_t cairo_pdf_surface_backend = {
7863     CAIRO_SURFACE_TYPE_PDF,
7864     _cairo_pdf_surface_finish,
7865
7866     _cairo_default_context_create,
7867
7868     NULL, /* create similar: handled by wrapper */
7869     NULL, /* create similar image */
7870     NULL, /* map to image */
7871     NULL, /* unmap image */
7872
7873     _cairo_surface_default_source,
7874     NULL, /* acquire_source_image */
7875     NULL, /* release_source_image */
7876     NULL, /* snapshot */
7877
7878     NULL,  /* _cairo_pdf_surface_copy_page */
7879     _cairo_pdf_surface_show_page,
7880
7881     _cairo_pdf_surface_get_extents,
7882     _cairo_pdf_surface_get_font_options,
7883
7884     NULL, /* flush */
7885     NULL, /* mark_dirty_rectangle */
7886
7887     /* Here are the drawing functions */
7888     _cairo_pdf_surface_paint,
7889     _cairo_pdf_surface_mask,
7890     _cairo_pdf_surface_stroke,
7891     _cairo_pdf_surface_fill,
7892     _cairo_pdf_surface_fill_stroke,
7893     NULL, /* show_glyphs */
7894     _cairo_pdf_surface_has_show_text_glyphs,
7895     _cairo_pdf_surface_show_text_glyphs,
7896     _cairo_pdf_surface_get_supported_mime_types,
7897 };
7898
7899 static const cairo_paginated_surface_backend_t
7900 cairo_pdf_surface_paginated_backend = {
7901     _cairo_pdf_surface_start_page,
7902     _cairo_pdf_surface_set_paginated_mode,
7903     NULL, /* set_bounding_box */
7904     _cairo_pdf_surface_has_fallback_images,
7905     _cairo_pdf_surface_supports_fine_grained_fallbacks,
7906 };