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