Code

0ff57127529263254f220ed147f9a21b5bae4535
[inkscape.git] / src / extension / internal / pdf-cairo.cpp
1 #define __SP_PDF_CAIRO_C__
3 /** \file
4  * PDF printing with Cairo.
5  */
6 /*
7  * Authors:
8  *   Miklós Erdélyi <erdelyim@gmail.com>
9  *
10  * Based on pdf.cpp
11  *
12  * Licensed under GNU GPL
13  */
15 /* Plain Print */
17 #ifdef HAVE_CONFIG_H
18 # include "config.h"
19 #endif
21 #ifdef HAVE_CAIRO_PDF
23 #ifndef PANGO_ENABLE_BACKEND
24 #define PANGO_ENABLE_BACKEND
25 #endif
27 #ifndef PANGO_ENABLE_ENGINE
28 #define PANGO_ENABLE_ENGINE
29 #endif
32 #include <signal.h>
33 #include <errno.h>
35 #include <glib/gmem.h>
36 #include <gtk/gtkstock.h>
37 #include <gtk/gtkvbox.h>
38 #include <gtk/gtkframe.h>
39 #include <gtk/gtkradiobutton.h>
40 #include <gtk/gtkcombo.h>
41 #include <gtk/gtklabel.h>
42 #include <gtk/gtkentry.h>
43 #include <gtk/gtktooltips.h>
45 #include <glibmm/i18n.h>
46 #include "display/nr-arena-item.h"
47 #include "display/canvas-bpath.h"
48 #include "display/inkscape-cairo.h"
49 #include "sp-item.h"
50 #include "style.h"
51 #include "sp-linear-gradient.h"
52 #include "sp-radial-gradient.h"
54 #include "libnrtype/font-instance.h"
55 #include "libnrtype/font-style-to-pos.h"
57 #include "libnr/nr-matrix.h"
58 #include "libnr/nr-matrix-fns.h"
59 #include "libnr/nr-matrix-ops.h"
61 #include <unit-constants.h>
63 #include "pdf-cairo.h"
64 #include "extension/system.h"
65 #include "extension/print.h"
67 #include "io/sys.h"
69 #include <cairo.h>
70 #include <cairo-pdf.h>
72 #include <pango/pango.h>
73 #include <pango/pangofc-fontmap.h>
75 #ifdef RENDER_WITH_PANGO_CAIRO
76 #include <pango/pangocairo.h>
77 #else
78 #include <cairo-ft.h>
79 #endif
80 namespace Inkscape {
81 namespace Extension {
82 namespace Internal {
84 static cairo_status_t _write_callback(void *closure, const unsigned char *data, unsigned int length);
85 static void _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0);
87 PrintCairoPDF::PrintCairoPDF() :
88     cr(NULL),
89     pdf_surface(NULL),
90     _layout(NULL),
91     _dpi(72),
92     _bitmap(false)
93 {
94 }
96 PrintCairoPDF::~PrintCairoPDF(void)
97 {
98     if (cr) cairo_destroy(cr);
99     if (pdf_surface) cairo_surface_destroy(pdf_surface);
100     if (_layout) g_object_unref(_layout);
102     /* restore default signal handling for SIGPIPE */
103 #if !defined(_WIN32) && !defined(__WIN32__)
104     (void) signal(SIGPIPE, SIG_DFL);
105 #endif
107     return;
110 unsigned int
111 PrintCairoPDF::setup(Inkscape::Extension::Print * mod)
113     static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
115 #ifdef TED
116     Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
117 #endif
119     unsigned int ret = FALSE;
121     /* Create dialog */
122     GtkTooltips *tt = gtk_tooltips_new();
123     g_object_ref((GObject *) tt);
124     gtk_object_sink((GtkObject *) tt);
126     GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
127 //            SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
128             NULL,
129             (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
130             GTK_STOCK_CANCEL,
131             GTK_RESPONSE_CANCEL,
132             GTK_STOCK_PRINT,
133             GTK_RESPONSE_OK,
134             NULL);
136     gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
138     GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
139     gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
140     /* Print properties frame */
141     GtkWidget *f = gtk_frame_new(_("Print properties"));
142     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
143     GtkWidget *vb = gtk_vbox_new(FALSE, 4);
144     gtk_container_add(GTK_CONTAINER(f), vb);
145     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
146     /* Print type */
147     bool const p2bm = mod->get_param_bool("bitmap");
148     GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PDF operators"));
149     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
150                          _("Use PDF vector operators. The resulting image is usually smaller "
151                            "in file size and can be arbitrarily scaled, but "
152                            "patterns will be lost."), NULL);
153     if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
154     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
155     rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
156     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
157                          _("Print everything as bitmap. The resulting image is usually larger "
158                            "in file size and cannot be arbitrarily scaled without quality loss, "
159                            "but all objects will be rendered exactly as displayed."), NULL);
160     if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
161     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
162     /* Resolution */
163     GtkWidget *hb = gtk_hbox_new(FALSE, 4);
164     gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
165     GtkWidget *combo = gtk_combo_new();
166     gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
167     gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
168     gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
169     gtk_widget_set_size_request(combo, 64, -1);
170     gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
171                          _("Preferred resolution (dots per inch) of bitmap"), NULL);
172     /* Setup strings */
173     GList *sl = NULL;
174     for (unsigned i = 0; pdr[i] != NULL; i++) {
175         sl = g_list_prepend(sl, (gpointer) pdr[i]);
176     }
177     sl = g_list_reverse(sl);
178     gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
179     g_list_free(sl);
180     if (1) {
181         gchar const *val = mod->get_param_string("resolution");
182         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
183     }
184     gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
185     GtkWidget *l = gtk_label_new(_("Resolution:"));
186     gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
188     /* Print destination frame */
189     f = gtk_frame_new(_("Print destination"));
190     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
191     vb = gtk_vbox_new(FALSE, 4);
192     gtk_container_add(GTK_CONTAINER(f), vb);
193     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
195     l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
196                         "leave empty to use the system default printer.\n"
197                         "Use '> filename' to print to file.\n"
198                         "Use '| prog arg...' to pipe to a program."));
199     gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
201     GtkWidget *e = gtk_entry_new();
202     if (1) {
203         gchar const *val = mod->get_param_string("destination");
204         gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
205                                            ? val
206                                            : "" ));
207     }
208     gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
210     // pressing enter in the destination field is the same as clicking Print:
211     gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
213     gtk_widget_show_all(vbox);
215     int const response = gtk_dialog_run(GTK_DIALOG(dlg));
217     g_object_unref((GObject *) tt);
219     if (response == GTK_RESPONSE_OK) {
220         gchar const *fn;
221         char const *sstr;
223         _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
224         sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
225         _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
226         /* Arrgh, have to do something */
227         fn = gtk_entry_get_text(GTK_ENTRY(e));
228         /* skip leading whitespace, bug #1068483 */
229         while (fn && *fn==' ') { fn++; }
230         /* g_print("Printing to %s\n", fn); */
232         mod->set_param_bool("bitmap", _bitmap);
233         mod->set_param_string("resolution", (gchar *)sstr);
234         mod->set_param_string("destination", (gchar *)fn);
235         ret = TRUE;
236     }
238     gtk_widget_destroy(dlg);
240     return ret;
243 unsigned int
244 PrintCairoPDF::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
246     FILE *osf = NULL;
247     FILE *osp = NULL;
249     _alpha_stack.clear();
250     _alpha_stack.push_back(1.0);
252     gsize bytesRead = 0;
253     gsize bytesWritten = 0;
254     GError *error = NULL;
255     gchar const *utf8_fn = mod->get_param_string("destination");
256     gchar *local_fn = g_filename_from_utf8( utf8_fn,
257                                             -1,  &bytesRead,  &bytesWritten, &error);
258     gchar const *fn = local_fn;
260     /* TODO: Replace the below fprintf's with something that does the right thing whether in
261      * gui or batch mode (e.g. --print=blah).  Consider throwing an exception: currently one of
262      * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
263      * return code.
264      */
265     if (fn != NULL) {
266         if (*fn == '|') {
267             fn += 1;
268             while (isspace(*fn)) fn += 1;
269 #ifndef WIN32
270             osp = popen(fn, "w");
271 #else
272             osp = _popen(fn, "w");
273 #endif
274             if (!osp) {
275                 fprintf(stderr, "inkscape: popen(%s): %s\n",
276                         fn, strerror(errno));
277                 return 0;
278             }
279             _stream = osp;
280         } else if (*fn == '>') {
281             fn += 1;
282             while (isspace(*fn)) fn += 1;
283             Inkscape::IO::dump_fopen_call(fn, "K");
284             osf = Inkscape::IO::fopen_utf8name(fn, "w+");
285             if (!osf) {
286                 fprintf(stderr, "inkscape: fopen(%s): %s\n",
287                         fn, strerror(errno));
288                 return 0;
289             }
290             _stream = osf;
291         } else {
292             /* put cwd stuff in here */
293             gchar *qn = ( *fn
294                           ? g_strdup_printf("lpr -P %s", fn)  /* FIXME: quote fn */
295                           : g_strdup("lpr") );
296 #ifndef WIN32
297             osp = popen(qn, "w");
298 #else
299             osp = _popen(qn, "w");
300 #endif
301             if (!osp) {
302                 fprintf(stderr, "inkscape: popen(%s): %s\n",
303                         qn, strerror(errno));
304                 return 0;
305             }
306             g_free(qn);
307             _stream = osp;
308         }
309     }
311     g_free(local_fn);
313     if (_stream) {
314         /* fixme: this is kinda icky */
315 #if !defined(_WIN32) && !defined(__WIN32__)
316         (void) signal(SIGPIPE, SIG_IGN);
317 #endif
318     }
320     // test output stream?
322     // width and height in pt
323     _width = sp_document_width(doc) * PT_PER_PX;
324     _height = sp_document_height(doc) * PT_PER_PX;
326     NRRect d;
327     bool   pageBoundingBox = mod->get_param_bool("pageBoundingBox");
328     SPItem* doc_item = SP_ITEM(mod->base);
329     // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
330     NR::Matrix t (NR::identity());
331     if (pageBoundingBox) {
332         d.x0 = d.y0 = 0;
333         d.x1 = _width;
334         d.y1 = _height;
335     } else {
336         // if not page, use our base, which is either root or the item we want to export
337         sp_item_invoke_bbox(doc_item, &d, from_2geom(sp_item_i2doc_affine (doc_item)), TRUE);
338         // convert from px to pt
339         d.x0 *= PT_PER_PX;
340         d.x1 *= PT_PER_PX;
341         d.y0 *= PT_PER_PX;
342         d.y1 *= PT_PER_PX;
343     }
345     // When rendering a standalone object, we must set cairo's transform to the accumulated
346     // ancestor transform of that item - e.g. it may be rotated or skewed by its parent group, and
347     // we must reproduce that in the export even though we start traversing the tree from the
348     // object itself, ignoring its ancestors
350     // complete transform, including doc_item's own transform
351     t = from_2geom(sp_item_i2doc_affine (doc_item));
352     // subreact doc_item's transform (comes first) from it
353     t = NR::Matrix(doc_item->transform).inverse() * t;
355     // create cairo context
356     pdf_surface = cairo_pdf_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, d.x1-d.x0, d.y1-d.y0);
357     cr = cairo_create(pdf_surface);
359     // move to the origin
360     cairo_translate (cr, -d.x0, -d.y0);
362     // set cairo transform;  we must scale the translation values to pt
363     _concat_transform (cr, t[0], t[1], t[2], t[3], t[4]*PT_PER_PX, t[5]*PT_PER_PX);
365     if (!_bitmap) {
366         cairo_scale(cr, PT_PER_PX, PT_PER_PX);
368         // from now on we can output px, but they will be treated as pt
369         // note that the we do not have to flip the y axis
370         // because Cairo's coordinate system is identical to Inkscape's
371     }
373     return 1;
376 unsigned int
377 PrintCairoPDF::finish(Inkscape::Extension::Print *mod)
379     if (!_stream) return 0;
380     if (_bitmap) return 0;
382     cairo_show_page(cr);
384     cairo_destroy(cr);
385     cairo_surface_finish(pdf_surface);
386     cairo_status_t status = cairo_surface_status(pdf_surface);
387     cairo_surface_destroy(pdf_surface);
388     cr = NULL;
389     pdf_surface = NULL;
391     /* Flush stream to be sure. */
392     (void) fflush(_stream);
394     /* fixme: should really use pclose for popen'd streams */
395     fclose(_stream);
396     _stream = 0;
398     if (status == CAIRO_STATUS_SUCCESS)
399         return true;
400     else
401         return false;
404 unsigned int
405 PrintCairoPDF::bind(Inkscape::Extension::Print *mod, NR::Matrix const *transform, float opacity)
407     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
408     if (_bitmap) return 0;
410     if (opacity < 1.0) {
411         cairo_push_group(cr);
412     } else {
413         cairo_save(cr);
414     }
415     _concat_transform(cr, (*transform)[0], (*transform)[1], (*transform)[2], (*transform)[3], (*transform)[4], (*transform)[5]);
416     // printf("bind: (%f) %f %f %f %f %f %f\n", opacity, transform->c[0], transform->c[1], transform->c[2], transform->c[3], transform->c[4], transform->c[5]);
417     // remember these to be able to undo them when outputting text
418     _last_tx = (*transform)[4];
419     _last_ty = (*transform)[5];
421     _alpha_stack.push_back(opacity);
423     return 1;
426 unsigned int
427 PrintCairoPDF::release(Inkscape::Extension::Print *mod)
429     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
430     if (_bitmap) return 0;
432     float opacity = _alpha_stack.back();
434     if (opacity < 1.0) {
435         cairo_pop_group_to_source(cr);
436         cairo_paint_with_alpha(cr, opacity);
437     } else {
438         cairo_restore(cr);
439     }
440 //    g_printf("release\n");
441     _alpha_stack.pop_back();
442     g_assert(_alpha_stack.size() > 0);
444     return 1;
447 unsigned int
448 PrintCairoPDF::comment(Inkscape::Extension::Print *mod, char const *comment)
450     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
451     if (_bitmap) return 0;
453     return 1;
456 cairo_pattern_t*
457 PrintCairoPDF::create_pattern_for_paint(SPPaintServer const *const paintserver, NRRect const *pbox, float alpha)
459     cairo_pattern_t *pattern = NULL;
460     bool apply_bbox2user = false;
462     if (SP_IS_LINEARGRADIENT (paintserver)) {
464             SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver);
466             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
468             NR::Point p1 (lg->x1.computed, lg->y1.computed);
469             NR::Point p2 (lg->x2.computed, lg->y2.computed);
470             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
471                 // convert to userspace
472                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
473                 p1 *= bbox2user;
474                 p2 *= bbox2user;
475             }
477             // create linear gradient pattern
478             pattern = cairo_pattern_create_linear(p1[NR::X], p1[NR::Y], p2[NR::X], p2[NR::Y]);
480             // add stops
481             for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) {
482                 float rgb[3];
483                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
484                 cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha);
485             }
486     } else if (SP_IS_RADIALGRADIENT (paintserver)) {
488         SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver);
490         sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
492         NR::Point c (rg->cx.computed, rg->cy.computed);
493         NR::Point f (rg->fx.computed, rg->fy.computed);
494         double r = rg->r.computed;
496         NR::Coord const df = hypot(f[NR::X] - c[NR::X], f[NR::Y] - c[NR::Y]);
497         if (df >= r) {
498             f[NR::X] = c[NR::X] + (f[NR::X] - c[NR::X] ) * r / (float) df;
499             f[NR::Y] = c[NR::Y] + (f[NR::Y] - c[NR::Y] ) * r / (float) df;
500         }
502         if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
503             apply_bbox2user = true;
505         // create radial gradient pattern
506         pattern = cairo_pattern_create_radial(f[NR::X], f[NR::Y], 0, c[NR::X], c[NR::Y], r);
508         // add stops
509         for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) {
510             float rgb[3];
511             sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
512             cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha);
513         }
514     }
516     if (pattern) {
517         SPGradient *g = SP_GRADIENT(paintserver);
519         // set extend type
520         SPGradientSpread spread = sp_gradient_get_spread(g);
521         switch (spread) {
522                 case SP_GRADIENT_SPREAD_REPEAT:
523                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
524                         break;
525                 case SP_GRADIENT_SPREAD_REFLECT:
526                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT);
527                         break;
528                 case SP_GRADIENT_SPREAD_PAD:
529             default:
530                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_PAD);
531                         break;
532         }
534         cairo_matrix_t pattern_matrix;
535         if (g->gradientTransform_set) {
536                 // apply gradient transformation
537                 cairo_matrix_init(&pattern_matrix,
538                     g->gradientTransform[0], g->gradientTransform[1],
539                     g->gradientTransform[2], g->gradientTransform[3],
540                     g->gradientTransform[4], g->gradientTransform[5]);
541         } else {
542             cairo_matrix_init_identity (&pattern_matrix);
543         }
545         if (apply_bbox2user) {
546             // convert to userspace
547             cairo_matrix_t bbox2user;
548             cairo_matrix_init (&bbox2user, pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
549             cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix);
550         }
551         cairo_matrix_invert(&pattern_matrix);   // because Cairo expects a userspace->patternspace matrix
552         cairo_pattern_set_matrix(pattern, &pattern_matrix);
553     }
555     return pattern;
558 void
559 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
561     g_return_if_fail( style->fill.isColor()
562                       || ( style->fill.isPaintserver()
563                            && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
565     if (style->fill.isColor()) {
566         float rgb[3];
567         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
569         float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
571         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
572     } else {
573         g_assert( style->fill.isPaintserver()
574                   && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
576         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_FILL_SERVER(style), pbox, 1.0);
578         if (pattern) {
579                 cairo_set_source(cr, pattern);
580             cairo_pattern_destroy(pattern);
581         }
582     }
585 unsigned int
586 PrintCairoPDF::fill(Inkscape::Extension::Print *mod, Geom::PathVector const &pathv, NR::Matrix const *ctm, SPStyle const *const style,
587               NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
589     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
590     if (_bitmap) return 0;
592     if ( style->fill.isColor()
593          || ( style->fill.isPaintserver()
594               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) ) {
596         float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
598         cairo_save(cr);
600         print_fill_style(cr, style, pbox);
602         cairo_new_path(cr);
603         feed_pathvector_to_cairo(cr, pathv);
605         if (style->fill_rule.computed == SP_WIND_RULE_EVENODD) {
606             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
607         } else {
608             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
609         }
610         if (alpha != 1.0 &&
611             !style->fill.isColor()) {
613             cairo_clip (cr);
614             cairo_paint_with_alpha (cr, alpha);
615         } else {
616             cairo_fill(cr);
617         }
619         cairo_restore(cr);
620     }
622     return 0;
625 void
626 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
628     float alpha = SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
630     if ( style->stroke.isColor() ) {
631         float rgb[3];
632         sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
634         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
635     } else if ( style->stroke.isPaintserver()
636                   && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
638         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
640         if (pattern) {
641                 cairo_set_source(cr, pattern);
642             cairo_pattern_destroy(pattern);
643         }
644     }
646     if (style->stroke_dash.n_dash   &&
647         style->stroke_dash.dash       )
648     {
649         cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
650     } else {
651         cairo_set_dash(cr, NULL, 0, 0.0);       // disable dashing
652     }
654     cairo_set_line_width(cr, style->stroke_width.computed);
656     // set line join type
657     cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
658     switch (style->stroke_linejoin.computed) {
659         case SP_STROKE_LINEJOIN_MITER:
660             join = CAIRO_LINE_JOIN_MITER;
661             break;
662         case SP_STROKE_LINEJOIN_ROUND:
663             join = CAIRO_LINE_JOIN_ROUND;
664             break;
665         case SP_STROKE_LINEJOIN_BEVEL:
666             join = CAIRO_LINE_JOIN_BEVEL;
667             break;
668     }
669     cairo_set_line_join(cr, join);
671     // set line cap type
672     cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
673     switch (style->stroke_linecap.computed) {
674         case SP_STROKE_LINECAP_BUTT:
675             cap = CAIRO_LINE_CAP_BUTT;
676             break;
677         case SP_STROKE_LINECAP_ROUND:
678             cap = CAIRO_LINE_CAP_ROUND;
679             break;
680         case SP_STROKE_LINECAP_SQUARE:
681             cap = CAIRO_LINE_CAP_SQUARE;
682             break;
683     }
684     cairo_set_line_cap(cr, cap);
685     cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
688 unsigned int
689 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, Geom::PathVector const &pathv, NR::Matrix const *ctm, SPStyle const *style,
690                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
692     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
693     if (_bitmap) return 0;
695     if ( style->stroke.isColor() ||
696          ( style->stroke.isPaintserver()
697               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
699         cairo_save(cr);
701         cairo_new_path(cr);
702         print_stroke_style(cr, style, pbox);
704         feed_pathvector_to_cairo(cr, pathv);
705         cairo_stroke(cr);
707         cairo_restore(cr);
708     }
710     return 0;
713 unsigned int
714 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
715                NR::Matrix const *transform, SPStyle const *style)
717     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
718     if (_bitmap) return 0;
720     guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
721     if (!px_rgba) return 0;
723     float alpha = _alpha_stack.back();
725     // make a copy of the original pixbuf with premultiplied alpha
726     // if we pass the original pixbuf it will get messed up
727     for (unsigned i = 0; i < h; i++) {
728         for (unsigned j = 0; j < w; j++) {
729             guchar const *src = px + i * rs + j * 4;
730             guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
731             guchar r, g, b, alpha_dst;
733             // calculate opacity-modified alpha
734             alpha_dst = src[3];
735             if (alpha != 1.0)
736                 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
738             // premul alpha (needed because this will be undone by cairo-pdf)
739             r = src[0]*alpha_dst/255;
740             g = src[1]*alpha_dst/255;
741             b = src[2]*alpha_dst/255;
743             *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
744         }
745     }
747     cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
748     if (cairo_surface_status(image_surface)) {
749         g_printf("Error: %s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
750         return 0;
751     }
753     cairo_save(cr);
755         // scaling by width & height is not needed because it will be done by cairo-pdf
756         // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
757     cairo_matrix_t matrix;
758     cairo_matrix_init(&matrix,
759                     (*transform)[0]/w, (*transform)[1],
760                     (*transform)[2], -(*transform)[3]/h,
761                     (*transform)[4], (*transform)[5] + (*transform)[3]);
762     cairo_transform(cr, &matrix);
764     cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
765     cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
767     cairo_set_source(cr, pattern);
768     cairo_pattern_destroy(pattern);
770     // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
771     cairo_new_path(cr);
772     cairo_rectangle(cr, 0, 0, w, h);
773     cairo_clip(cr);
775     cairo_paint(cr);
777     cairo_restore(cr);
779     cairo_surface_destroy(image_surface);
780     g_free(px_rgba);
782     return 0;
785 #define GLYPH_ARRAY_SIZE 64
787 #ifndef RENDER_WITH_PANGO_CAIRO
789 NR::Point
790 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
791                bool vertical, bool stroke)
793     cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
794     cairo_glyph_t *glyphs = glyph_array;
795     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
796         glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
798     PangoGlyphUnit x_offset = 0, y_offset = 0;
799     PangoGlyphInfo *info;
800     int num_invalid_glyphs = 0;
801     for (gint i = 0; i < glyph_string->num_glyphs; i++) {
802         info = &glyph_string->glyphs[i];
803         // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) or have
804         // the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set
805         if (info->glyph == 0x0FFFFFFF || info->glyph & 0x10000000) {
806             num_invalid_glyphs++;
807             continue;
808         }
810         glyphs[i - num_invalid_glyphs].index = info->glyph;
811         glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
812         glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
814         if (vertical) {
815             cairo_text_extents_t extents;
816             cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
817             y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
818         }
819         else
820             x_offset += info->geometry.width;
821     }
823     if (stroke)
824         cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
825     else
826         cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
828     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
829         g_free(glyphs);
831     return NR::Point(x_offset, y_offset);
833 #endif
837 unsigned int
838 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
839               SPStyle const *const style)
841     bool dirty_pattern = false;
843     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
844     if (_bitmap) return 0;
846     cairo_save(cr);
848     // this needs to be there to encounter Cairo's userspace locking semantics for set_source
849     // otherwise gradients won't be shown correctly
850     // printf("\n _last_tx:%f _last_ty:%f", _last_tx, _last_ty);
851     cairo_translate(cr, -_last_tx, -_last_ty);
853     // create pango layout and context if needed
854     if (_layout == NULL) {
855 #ifdef RENDER_WITH_PANGO_CAIRO
856         //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
857         _layout = pango_cairo_create_layout(cr);
858 #else
859         _layout = pango_layout_new((font_factory::Default())->fontContext);
860 #endif
861     }
863     // create font instance from style and use it
864     font_instance *tf = font_factory::Default()->FaceFromStyle(style);
865     if (tf == NULL) {   // do something
866         g_printf("Warning: trouble getting font_instance\n");
867         tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
868     }
869     PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
871     pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
872     pango_layout_set_font_description(_layout, adjusted);
873     pango_layout_set_text(_layout, text, -1);
875     pango_font_description_free(adjusted);
876     tf->Unref();
878 #ifdef RENDER_WITH_PANGO_CAIRO
879     pango_cairo_update_layout(cr, _layout);
880 #else
881     pango_layout_context_changed(_layout);   // is this needed?
882 #endif
884     PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
885     if (line == NULL)
886         return 0;
888 #ifndef RENDER_WITH_PANGO_CAIRO
889     // apply the selected font
890     double size;
891     PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
892     PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
893     FcPattern *fc_pattern = fc_font->font_pattern;
895     if ( style->writing_mode.set &&
896        (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
897         style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
898     {
899         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
900         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
901         dirty_pattern = true;
902     }
904     cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
905     cairo_set_font_face(cr, font_face);
907     if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
908         size = 12.0;
910     // adjust size and horizontal flip
911     cairo_matrix_t matrix;
912     cairo_get_font_matrix(cr, &matrix);
913     matrix.xx = size;
914     matrix.yy = -matrix.xx;
915     cairo_set_font_matrix(cr, &matrix);
916 #endif
918     if ( style->fill.isColor()
919          || ( style->fill.isPaintserver()
920               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
921     {
922         // set fill style
923         print_fill_style(cr, style, NULL);
925 #ifndef RENDER_WITH_PANGO_CAIRO
926         NR::Point cursor(_last_tx, _last_ty);
927         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
928             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
929             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
930         }
931 #else
932         cairo_new_path(cr);
933         // as pango has inverted origin we simulate the moveto and apply the vertical flip
934         //cairo_move_to(cr, _last_tx, _last_ty);
935         cairo_translate(cr, _last_tx, _last_ty);
936         cairo_scale(cr, 1, -1);
937         cairo_move_to(cr, 0, 0);
938         pango_cairo_show_layout_line(cr, line);
939         cairo_scale(cr, 1, -1);
940         cairo_translate(cr, -_last_tx, -_last_ty);
942 #endif
943     }
945     if (style->stroke.isColor()
946         || ( style->stroke.isPaintserver()
947               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
948     {
949         // set stroke style
950         print_stroke_style(cr, style, NULL);
952         // paint stroke
953 #ifndef RENDER_WITH_PANGO_CAIRO
954         NR::Point cursor(_last_tx, _last_ty);
955         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
956             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
957             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, true) / PANGO_SCALE;
958         }
959 #else
960         cairo_new_path(cr);
961         // as pango has inverted origin we simulate the moveto and apply the vertical flip
962         //cairo_move_to(cr, _last_tx, _last_ty);
963         cairo_translate(cr, _last_tx, _last_ty);
964         cairo_scale(cr, 1, -1);
965         cairo_move_to(cr, 0, 0);
966         pango_cairo_layout_line_path(cr, line);
967         cairo_scale(cr, 1, -1);
968         cairo_translate(cr, -_last_tx, -_last_ty);
969 #endif
970         cairo_stroke(cr);
971     }
974     cairo_restore(cr);
976 #ifndef RENDER_WITH_PANGO_CAIRO
977     cairo_font_face_destroy(font_face);
979     if (dirty_pattern) {
980         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
981         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
982     }
983 #endif
985     return 0;
988 /* Helper functions */
990 static void
991 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
993     cairo_matrix_t matrix;
995     cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
996     cairo_transform(cr, &matrix);
999 static cairo_status_t
1000 _write_callback(void *closure, const unsigned char *data, unsigned int length)
1002     size_t written;
1003     FILE *file = (FILE*)closure;
1005     written = fwrite (data, 1, length, file);
1007     if (written == length)
1008         return CAIRO_STATUS_SUCCESS;
1009     else
1010         return CAIRO_STATUS_WRITE_ERROR;
1013 bool
1014 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
1016     return ext->get_param_bool("textToPath");
1019 #include "clear-n_.h"
1021 void
1022 PrintCairoPDF::init(void)
1024     /* PDF out */
1025     (void) Inkscape::Extension::build_from_mem(
1026         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
1027         "<name>" N_("PDF Print") "</name>\n"
1028         "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1029         "<param name=\"bitmap\" type=\"boolean\">false</param>\n"
1030         "<param name=\"resolution\" type=\"string\">72</param>\n"
1031         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1032         "<param name=\"pageBoundingBox\" type=\"boolean\">true</param>\n"
1033         "<param name=\"textToPath\" type=\"boolean\">true</param>\n"
1034         "<param name=\"exportDrawing\" type=\"boolean\">false</param>\n"
1035         "<param name=\"exportCanvas\" type=\"boolean\">false</param>\n"
1036         "<param name=\"exportId\" type=\"string\"></param>\n"
1037         "<print/>\n"
1038         "</inkscape-extension>", new PrintCairoPDF());
1042 }  /* namespace Internal */
1043 }  /* namespace Extension */
1044 }  /* namespace Inkscape */
1046 /* End of GNU GPL code */
1048 #endif /* HAVE_CAIRO_PDF */
1051 /*
1052   Local Variables:
1053   mode:c++
1054   c-file-style:"stroustrup"
1055   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1056   indent-tabs-mode:nil
1057   fill-column:99
1058   End:
1059 */
1060 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :