Code

a couple of trivial %d -> %u changes.
[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 <libnr/n-art-bpath.h>
37 #include <glib/gmem.h>
38 #include <gtk/gtkstock.h>
39 #include <gtk/gtkvbox.h>
40 #include <gtk/gtkframe.h>
41 #include <gtk/gtkradiobutton.h>
42 #include <gtk/gtkcombo.h>
43 #include <gtk/gtklabel.h>
44 #include <gtk/gtkentry.h>
45 #include <gtk/gtktooltips.h>
47 #include <glibmm/i18n.h>
48 #include "display/nr-arena-item.h"
49 #include "display/canvas-bpath.h"
50 #include "sp-item.h"
51 #include "style.h"
52 #include "sp-linear-gradient.h"
53 #include "sp-radial-gradient.h"
55 #include "libnrtype/font-instance.h"
56 #include "libnrtype/font-style-to-pos.h"
58 #include "libnr/nr-matrix.h"
59 #include "libnr/nr-matrix-fns.h"
60 #include "libnr/nr-matrix-ops.h"
62 #include <unit-constants.h>
64 #include "pdf-cairo.h"
65 #include "extension/system.h"
66 #include "extension/print.h"
68 #include "io/sys.h"
70 #include <cairo.h>
71 #include <cairo-pdf.h>
73 #include <pango/pango.h>
74 #include <pango/pangofc-fontmap.h>
76 #ifdef RENDER_WITH_PANGO_CAIRO
77 #include <pango/pangocairo.h>
78 #else
79 #include <cairo-ft.h>
80 #endif
81 namespace Inkscape {
82 namespace Extension {
83 namespace Internal {
85 static cairo_status_t _write_callback(void *closure, const unsigned char *data, unsigned int length);
86 static void _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0);
88 PrintCairoPDF::PrintCairoPDF() :
89     cr(NULL),
90     pdf_surface(NULL),
91     _layout(NULL),
92     _dpi(72),
93     _bitmap(false)
94 {
95 }
97 PrintCairoPDF::~PrintCairoPDF(void)
98 {
99     if (cr) cairo_destroy(cr);
100     if (pdf_surface) cairo_surface_destroy(pdf_surface);
101     if (_layout) g_object_unref(_layout);
103     /* restore default signal handling for SIGPIPE */
104 #if !defined(_WIN32) && !defined(__WIN32__)
105     (void) signal(SIGPIPE, SIG_DFL);
106 #endif
108     return;
111 unsigned int
112 PrintCairoPDF::setup(Inkscape::Extension::Print * mod)
114     static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
116 #ifdef TED
117     Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
118 #endif
120     unsigned int ret = FALSE;
122     /* Create dialog */
123     GtkTooltips *tt = gtk_tooltips_new();
124     g_object_ref((GObject *) tt);
125     gtk_object_sink((GtkObject *) tt);
127     GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
128 //            SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
129             NULL,
130             (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
131             GTK_STOCK_CANCEL,
132             GTK_RESPONSE_CANCEL,
133             GTK_STOCK_PRINT,
134             GTK_RESPONSE_OK,
135             NULL);
137     gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
139     GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
140     gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
141     /* Print properties frame */
142     GtkWidget *f = gtk_frame_new(_("Print properties"));
143     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
144     GtkWidget *vb = gtk_vbox_new(FALSE, 4);
145     gtk_container_add(GTK_CONTAINER(f), vb);
146     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
147     /* Print type */
148     bool const p2bm = mod->get_param_bool("bitmap");
149     GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PDF operators"));
150     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
151                          _("Use PDF vector operators. The resulting image is usually smaller "
152                            "in file size and can be arbitrarily scaled, but "
153                            "patterns will be lost."), NULL);
154     if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
155     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
156     rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
157     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
158                          _("Print everything as bitmap. The resulting image is usually larger "
159                            "in file size and cannot be arbitrarily scaled without quality loss, "
160                            "but all objects will be rendered exactly as displayed."), NULL);
161     if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
162     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
163     /* Resolution */
164     GtkWidget *hb = gtk_hbox_new(FALSE, 4);
165     gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
166     GtkWidget *combo = gtk_combo_new();
167     gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
168     gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
169     gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
170     gtk_widget_set_size_request(combo, 64, -1);
171     gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
172                          _("Preferred resolution (dots per inch) of bitmap"), NULL);
173     /* Setup strings */
174     GList *sl = NULL;
175     for (unsigned i = 0; pdr[i] != NULL; i++) {
176         sl = g_list_prepend(sl, (gpointer) pdr[i]);
177     }
178     sl = g_list_reverse(sl);
179     gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
180     g_list_free(sl);
181     if (1) {
182         gchar const *val = mod->get_param_string("resolution");
183         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
184     }
185     gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
186     GtkWidget *l = gtk_label_new(_("Resolution:"));
187     gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
189     /* Print destination frame */
190     f = gtk_frame_new(_("Print destination"));
191     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
192     vb = gtk_vbox_new(FALSE, 4);
193     gtk_container_add(GTK_CONTAINER(f), vb);
194     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
196     l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
197                         "leave empty to use the system default printer.\n"
198                         "Use '> filename' to print to file.\n"
199                         "Use '| prog arg...' to pipe to a program."));
200     gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
202     GtkWidget *e = gtk_entry_new();
203     if (1) {
204         gchar const *val = mod->get_param_string("destination");
205         gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
206                                            ? val
207                                            : "" ));
208     }
209     gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
211     // pressing enter in the destination field is the same as clicking Print:
212     gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
214     gtk_widget_show_all(vbox);
216     int const response = gtk_dialog_run(GTK_DIALOG(dlg));
218     g_object_unref((GObject *) tt);
220     if (response == GTK_RESPONSE_OK) {
221         gchar const *fn;
222         char const *sstr;
224         _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
225         sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
226         _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
227         /* Arrgh, have to do something */
228         fn = gtk_entry_get_text(GTK_ENTRY(e));
229         /* skip leading whitespace, bug #1068483 */
230         while (fn && *fn==' ') { fn++; }
231         /* g_print("Printing to %s\n", fn); */
233         mod->set_param_bool("bitmap", _bitmap);
234         mod->set_param_string("resolution", (gchar *)sstr);
235         mod->set_param_string("destination", (gchar *)fn);
236         ret = TRUE;
237     }
239     gtk_widget_destroy(dlg);
241     return ret;
244 unsigned int
245 PrintCairoPDF::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
247     FILE *osf = NULL;
248     FILE *osp = NULL;
250     _alpha_stack.clear();
251     _alpha_stack.push_back(1.0);
253     gsize bytesRead = 0;
254     gsize bytesWritten = 0;
255     GError *error = NULL;
256     gchar const *utf8_fn = mod->get_param_string("destination");
257     gchar *local_fn = g_filename_from_utf8( utf8_fn,
258                                             -1,  &bytesRead,  &bytesWritten, &error);
259     gchar const *fn = local_fn;
261     /* TODO: Replace the below fprintf's with something that does the right thing whether in
262      * gui or batch mode (e.g. --print=blah).  Consider throwing an exception: currently one of
263      * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
264      * return code.
265      */
266     if (fn != NULL) {
267         if (*fn == '|') {
268             fn += 1;
269             while (isspace(*fn)) fn += 1;
270 #ifndef WIN32
271             osp = popen(fn, "w");
272 #else
273             osp = _popen(fn, "w");
274 #endif
275             if (!osp) {
276                 fprintf(stderr, "inkscape: popen(%s): %s\n",
277                         fn, strerror(errno));
278                 return 0;
279             }
280             _stream = osp;
281         } else if (*fn == '>') {
282             fn += 1;
283             while (isspace(*fn)) fn += 1;
284             Inkscape::IO::dump_fopen_call(fn, "K");
285             osf = Inkscape::IO::fopen_utf8name(fn, "w+");
286             if (!osf) {
287                 fprintf(stderr, "inkscape: fopen(%s): %s\n",
288                         fn, strerror(errno));
289                 return 0;
290             }
291             _stream = osf;
292         } else {
293             /* put cwd stuff in here */
294             gchar *qn = ( *fn
295                           ? g_strdup_printf("lpr -P %s", fn)  /* FIXME: quote fn */
296                           : g_strdup("lpr") );
297 #ifndef WIN32
298             osp = popen(qn, "w");
299 #else
300             osp = _popen(qn, "w");
301 #endif
302             if (!osp) {
303                 fprintf(stderr, "inkscape: popen(%s): %s\n",
304                         qn, strerror(errno));
305                 return 0;
306             }
307             g_free(qn);
308             _stream = osp;
309         }
310     }
312     g_free(local_fn);
314     if (_stream) {
315         /* fixme: this is kinda icky */
316 #if !defined(_WIN32) && !defined(__WIN32__)
317         (void) signal(SIGPIPE, SIG_IGN);
318 #endif
319     }
321     // test output stream?
323     // width and height in pt
324     _width = sp_document_width(doc) * PT_PER_PX;
325     _height = sp_document_height(doc) * PT_PER_PX;
327     NRRect d;
328     bool   pageBoundingBox = mod->get_param_bool("pageBoundingBox");
329     SPItem* doc_item = SP_ITEM(mod->base);
330     // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
331     NR::Matrix t (NR::identity());
332     if (pageBoundingBox) {
333         d.x0 = d.y0 = 0;
334         d.x1 = _width;
335         d.y1 = _height;
336     } else {
337         // if not page, use our base, which is either root or the item we want to export
338         sp_item_invoke_bbox(doc_item, &d, sp_item_i2doc_affine (doc_item), TRUE);
339         // convert from px to pt
340         d.x0 *= PT_PER_PX;
341         d.x1 *= PT_PER_PX;
342         d.y0 *= PT_PER_PX;
343         d.y1 *= PT_PER_PX;
344     }
346     // When rendering a standalone object, we must set cairo's transform to the accumulated
347     // ancestor transform of that item - e.g. it may be rotated or skewed by its parent group, and
348     // we must reproduce that in the export even though we start traversing the tree from the
349     // object itself, ignoring its ancestors
351     // complete transform, including doc_item's own transform
352     t = sp_item_i2doc_affine (doc_item);
353     // subreact doc_item's transform (comes first) from it
354     t = NR::Matrix(doc_item->transform).inverse() * t;
356     // create cairo context
357     pdf_surface = cairo_pdf_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, d.x1-d.x0, d.y1-d.y0);
358     cr = cairo_create(pdf_surface);
360     // move to the origin
361     cairo_translate (cr, -d.x0, -d.y0);
363     // set cairo transform;  we must scale the translation values to pt
364     _concat_transform (cr, t[0], t[1], t[2], t[3], t[4]*PT_PER_PX, t[5]*PT_PER_PX);
366     if (!_bitmap) {
367         cairo_scale(cr, PT_PER_PX, PT_PER_PX);
369         // from now on we can output px, but they will be treated as pt
370         // note that the we do not have to flip the y axis
371         // because Cairo's coordinate system is identical to Inkscape's
372     }
374     return 1;
377 unsigned int
378 PrintCairoPDF::finish(Inkscape::Extension::Print *mod)
380     if (!_stream) return 0;
381     if (_bitmap) return 0;
383     cairo_show_page(cr);
385     cairo_destroy(cr);
386     cairo_surface_destroy(pdf_surface);
387     cr = NULL;
388     pdf_surface = NULL;
390     /* Flush stream to be sure. */
391     (void) fflush(_stream);
393     /* fixme: should really use pclose for popen'd streams */
394     fclose(_stream);
395     _stream = 0;
397     return 1;
400 unsigned int
401 PrintCairoPDF::bind(Inkscape::Extension::Print *mod, NR::Matrix const *transform, float opacity)
403     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
404     if (_bitmap) return 0;
406     if (opacity < 1.0) {
407         cairo_push_group(cr);
408     } else {
409         cairo_save(cr);
410     }
411     _concat_transform(cr, (*transform)[0], (*transform)[1], (*transform)[2], (*transform)[3], (*transform)[4], (*transform)[5]);
412     // 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]);
413     // remember these to be able to undo them when outputting text
414     _last_tx = (*transform)[4];
415     _last_ty = (*transform)[5];
417     _alpha_stack.push_back(opacity);
419     return 1;
422 unsigned int
423 PrintCairoPDF::release(Inkscape::Extension::Print *mod)
425     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
426     if (_bitmap) return 0;
428     float opacity = _alpha_stack.back();
430     if (opacity < 1.0) {
431         cairo_pop_group_to_source(cr);
432         cairo_paint_with_alpha(cr, opacity);
433     } else {
434         cairo_restore(cr);
435     }
436 //    g_printf("release\n");
437     _alpha_stack.pop_back();
438     g_assert(_alpha_stack.size() > 0);
440     return 1;
443 unsigned int
444 PrintCairoPDF::comment(Inkscape::Extension::Print *mod, char const *comment)
446     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
447     if (_bitmap) return 0;
449     return 1;
452 cairo_pattern_t*
453 PrintCairoPDF::create_pattern_for_paint(SPPaintServer const *const paintserver, NRRect const *pbox, float alpha)
455     cairo_pattern_t *pattern = NULL;
456     bool apply_bbox2user = false;
458     if (SP_IS_LINEARGRADIENT (paintserver)) {
460             SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver);
462             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
464             NR::Point p1 (lg->x1.computed, lg->y1.computed);
465             NR::Point p2 (lg->x2.computed, lg->y2.computed);
466             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
467                 // convert to userspace
468                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
469                 p1 *= bbox2user;
470                 p2 *= bbox2user;
471             }
473             // create linear gradient pattern
474             pattern = cairo_pattern_create_linear(p1[NR::X], p1[NR::Y], p2[NR::X], p2[NR::Y]);
476             // add stops
477             for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) {
478                 float rgb[3];
479                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
480                 cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha);
481             }
482     } else if (SP_IS_RADIALGRADIENT (paintserver)) {
484         SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver);
486         sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
488         NR::Point c (rg->cx.computed, rg->cy.computed);
489         NR::Point f (rg->fx.computed, rg->fy.computed);
490         double r = rg->r.computed;
492         NR::Coord const df = hypot(f[NR::X] - c[NR::X], f[NR::Y] - c[NR::Y]);
493         if (df >= r) {
494             f[NR::X] = c[NR::X] + (f[NR::X] - c[NR::X] ) * r / (float) df;
495             f[NR::Y] = c[NR::Y] + (f[NR::Y] - c[NR::Y] ) * r / (float) df;
496         }
498         if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
499             apply_bbox2user = true;
501         // create radial gradient pattern
502         pattern = cairo_pattern_create_radial(f[NR::X], f[NR::Y], 0, c[NR::X], c[NR::Y], r);
504         // add stops
505         for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) {
506             float rgb[3];
507             sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
508             cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha);
509         }
510     }
512     if (pattern) {
513         SPGradient *g = SP_GRADIENT(paintserver);
515         // set extend type
516         SPGradientSpread spread = sp_gradient_get_spread(g);
517         switch (spread) {
518                 case SP_GRADIENT_SPREAD_REPEAT:
519                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
520                         break;
521                 case SP_GRADIENT_SPREAD_REFLECT:
522                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT);
523                         break;
524                 case SP_GRADIENT_SPREAD_PAD:
525             default:
526                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_PAD);
527                         break;
528         }
530         cairo_matrix_t pattern_matrix;
531         if (g->gradientTransform_set) {
532                 // apply gradient transformation
533                 cairo_matrix_init(&pattern_matrix,
534                     g->gradientTransform[0], g->gradientTransform[1],
535                     g->gradientTransform[2], g->gradientTransform[3],
536                     g->gradientTransform[4], g->gradientTransform[5]);
537         } else {
538             cairo_matrix_init_identity (&pattern_matrix);
539         }
541         if (apply_bbox2user) {
542             // convert to userspace
543             cairo_matrix_t bbox2user;
544             cairo_matrix_init (&bbox2user, pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
545             cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix);
546         }
547         cairo_matrix_invert(&pattern_matrix);   // because Cairo expects a userspace->patternspace matrix
548         cairo_pattern_set_matrix(pattern, &pattern_matrix);
549     }
551     return pattern;
554 void
555 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
557     g_return_if_fail( style->fill.isColor()
558                       || ( style->fill.isPaintserver()
559                            && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
561     if (style->fill.isColor()) {
562         float rgb[3];
563         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
565         float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
567         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
568     } else {
569         g_assert( style->fill.isPaintserver()
570                   && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
572         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_FILL_SERVER(style), pbox, 1.0);
574         if (pattern) {
575                 cairo_set_source(cr, pattern);
576             cairo_pattern_destroy(pattern);
577         }
578     }
581 unsigned int
582 PrintCairoPDF::fill(Inkscape::Extension::Print *mod, const_NRBPath const *bpath, NR::Matrix const *ctm, SPStyle const *const style,
583               NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
585     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
586     if (_bitmap) return 0;
588     if ( style->fill.isColor()
589          || ( style->fill.isPaintserver()
590               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) ) {
592         float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
594         cairo_save(cr);
596         print_fill_style(cr, style, pbox);
597         print_bpath(cr, bpath->path);
598         if (style->fill_rule.computed == SP_WIND_RULE_EVENODD) {
599             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
600         } else {
601             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
602         }
603         if (alpha != 1.0 &&
604             !style->fill.isColor()) {
606             cairo_clip (cr);
607             cairo_paint_with_alpha (cr, alpha);
608         } else {
609             cairo_fill(cr);
610         }
612         cairo_restore(cr);
613     }
615     return 0;
618 void
619 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
621     float alpha = SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
623     if ( style->stroke.isColor() ) {
624         float rgb[3];
625         sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
627         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
628     } else if ( style->stroke.isPaintserver()
629                   && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
631         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
633         if (pattern) {
634                 cairo_set_source(cr, pattern);
635             cairo_pattern_destroy(pattern);
636         }
637     }
639     if (style->stroke_dash.n_dash   &&
640         style->stroke_dash.dash       )
641     {
642         cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
643     } else {
644         cairo_set_dash(cr, NULL, 0, 0.0);       // disable dashing
645     }
647     cairo_set_line_width(cr, style->stroke_width.computed);
649     // set line join type
650     cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
651     switch (style->stroke_linejoin.computed) {
652         case SP_STROKE_LINEJOIN_MITER:
653             join = CAIRO_LINE_JOIN_MITER;
654             break;
655         case SP_STROKE_LINEJOIN_ROUND:
656             join = CAIRO_LINE_JOIN_ROUND;
657             break;
658         case SP_STROKE_LINEJOIN_BEVEL:
659             join = CAIRO_LINE_JOIN_BEVEL;
660             break;
661     }
662     cairo_set_line_join(cr, join);
664     // set line cap type
665     cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
666     switch (style->stroke_linecap.computed) {
667         case SP_STROKE_LINECAP_BUTT:
668             cap = CAIRO_LINE_CAP_BUTT;
669             break;
670         case SP_STROKE_LINECAP_ROUND:
671             cap = CAIRO_LINE_CAP_ROUND;
672             break;
673         case SP_STROKE_LINECAP_SQUARE:
674             cap = CAIRO_LINE_CAP_SQUARE;
675             break;
676     }
677     cairo_set_line_cap(cr, cap);
678     cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
681 unsigned int
682 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, const_NRBPath const *bpath, NR::Matrix const *ctm, SPStyle const *style,
683                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
685     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
686     if (_bitmap) return 0;
688     if ( style->stroke.isColor() ||
689          ( style->stroke.isPaintserver()
690               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
692         cairo_save(cr);
694         print_stroke_style(cr, style, pbox);
695         print_bpath(cr, bpath->path);
696         cairo_stroke(cr);
698         cairo_restore(cr);
699     }
701     return 0;
704 unsigned int
705 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
706                NR::Matrix const *transform, SPStyle const *style)
708     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
709     if (_bitmap) return 0;
711     guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
712     if (!px_rgba) return 0;
714     float alpha = _alpha_stack.back();
716     // make a copy of the original pixbuf with premultiplied alpha
717     // if we pass the original pixbuf it will get messed up
718     for (unsigned i = 0; i < h; i++) {
719         for (unsigned j = 0; j < w; j++) {
720             guchar const *src = px + i * rs + j * 4;
721             guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
722             guchar r, g, b, alpha_dst;
724             // calculate opacity-modified alpha
725             alpha_dst = src[3];
726             if (alpha != 1.0)
727                 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
729             // premul alpha (needed because this will be undone by cairo-pdf)
730             r = src[0]*alpha_dst/255;
731             g = src[1]*alpha_dst/255;
732             b = src[2]*alpha_dst/255;
734             *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
735         }
736     }
738     cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
739     if (cairo_surface_status(image_surface)) {
740         g_printf("Error: %s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
741         return 0;
742     }
744     cairo_save(cr);
746         // scaling by width & height is not needed because it will be done by cairo-pdf
747         // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
748     cairo_matrix_t matrix;
749     cairo_matrix_init(&matrix,
750                     (*transform)[0]/w, (*transform)[1],
751                     (*transform)[2], -(*transform)[3]/h,
752                     (*transform)[4], (*transform)[5] + (*transform)[3]);
753     cairo_transform(cr, &matrix);
755     cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
756     cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
758     cairo_set_source(cr, pattern);
759     cairo_pattern_destroy(pattern);
761     // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
762     cairo_new_path(cr);
763     cairo_rectangle(cr, 0, 0, w, h);
764     cairo_clip(cr);
766     cairo_paint(cr);
768     cairo_restore(cr);
770     cairo_surface_destroy(image_surface);
771     g_free(px_rgba);
773     return 0;
776 #define GLYPH_ARRAY_SIZE 64
778 #ifndef RENDER_WITH_PANGO_CAIRO
780 NR::Point
781 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
782                bool vertical, bool stroke)
784     cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
785     cairo_glyph_t *glyphs = glyph_array;
786     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
787         glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
789     PangoGlyphUnit x_offset = 0, y_offset = 0;
790     PangoGlyphInfo *info;
791     int num_invalid_glyphs = 0;
792     for (gint i = 0; i < glyph_string->num_glyphs; i++) {
793         info = &glyph_string->glyphs[i];
794         // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) or have
795         // the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set
796         if (info->glyph == 0x0FFFFFFF || info->glyph & 0x10000000) {
797             num_invalid_glyphs++;
798             continue;
799         }
801         glyphs[i - num_invalid_glyphs].index = info->glyph;
802         glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
803         glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
805         if (vertical) {
806             cairo_text_extents_t extents;
807             cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
808             y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
809         }
810         else
811             x_offset += info->geometry.width;
812     }
814     if (stroke)
815         cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
816     else
817         cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
819     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
820         g_free(glyphs);
822     return NR::Point(x_offset, y_offset);
824 #endif
828 unsigned int
829 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
830               SPStyle const *const style)
832     bool dirty_pattern = false;
834     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
835     if (_bitmap) return 0;
837     cairo_save(cr);
839     // this needs to be there to encounter Cairo's userspace locking semantics for set_source
840     // otherwise gradients won't be shown correctly
841     // printf("\n _last_tx:%f _last_ty:%f", _last_tx, _last_ty);
842     cairo_translate(cr, -_last_tx, -_last_ty);
844     // create pango layout and context if needed
845     if (_layout == NULL) {
846 #ifdef RENDER_WITH_PANGO_CAIRO
847         //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
848         _layout = pango_cairo_create_layout(cr);
849 #else
850         _layout = pango_layout_new((font_factory::Default())->fontContext);
851 #endif
852     }
854     // create font instance from style and use it
855     font_instance *tf = font_factory::Default()->FaceFromStyle(style);
856     if (tf == NULL) {   // do something
857         g_printf("Warning: trouble getting font_instance\n");
858         tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
859     }
860     PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
862     pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
863     pango_layout_set_font_description(_layout, adjusted);
864     pango_layout_set_text(_layout, text, -1);
866     pango_font_description_free(adjusted);
867     tf->Unref();
869 #ifdef RENDER_WITH_PANGO_CAIRO
870     pango_cairo_update_layout(cr, _layout);
871 #else
872     pango_layout_context_changed(_layout);   // is this needed?
873 #endif
875     PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
876     if (line == NULL)
877         return 0;
879 #ifndef RENDER_WITH_PANGO_CAIRO
880     // apply the selected font
881     double size;
882     PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
883     PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
884     FcPattern *fc_pattern = fc_font->font_pattern;
886     if ( style->writing_mode.set &&
887        (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
888         style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
889     {
890         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
891         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
892         dirty_pattern = true;
893     }
895     cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
896     cairo_set_font_face(cr, font_face);
898     if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
899         size = 12.0;
901     // adjust size and horizontal flip
902     cairo_matrix_t matrix;
903     cairo_get_font_matrix(cr, &matrix);
904     matrix.xx = size;
905     matrix.yy = -matrix.xx;
906     cairo_set_font_matrix(cr, &matrix);
907 #endif
909     if ( style->fill.isColor()
910          || ( style->fill.isPaintserver()
911               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
912     {
913         // set fill style
914         print_fill_style(cr, style, NULL);
916 #ifndef RENDER_WITH_PANGO_CAIRO
917         NR::Point cursor(_last_tx, _last_ty);
918         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
919             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
920             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
921         }
922 #else
923         cairo_new_path(cr);
924         // as pango has inverted origin we simulate the moveto and apply the vertical flip
925         //cairo_move_to(cr, _last_tx, _last_ty);
926         cairo_translate(cr, _last_tx, _last_ty);
927         cairo_scale(cr, 1, -1);
928         cairo_move_to(cr, 0, 0);
929         pango_cairo_show_layout_line(cr, line);
930         cairo_scale(cr, 1, -1);
931         cairo_translate(cr, -_last_tx, -_last_ty);
933 #endif
934     }
936     if (style->stroke.isColor()
937         || ( style->stroke.isPaintserver()
938               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
939     {
940         // set stroke style
941         print_stroke_style(cr, style, NULL);
943         // paint stroke
944 #ifndef RENDER_WITH_PANGO_CAIRO
945         NR::Point cursor(_last_tx, _last_ty);
946         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
947             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
948             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, true) / PANGO_SCALE;
949         }
950 #else
951         cairo_new_path(cr);
952         // as pango has inverted origin we simulate the moveto and apply the vertical flip
953         //cairo_move_to(cr, _last_tx, _last_ty);
954         cairo_translate(cr, _last_tx, _last_ty);
955         cairo_scale(cr, 1, -1);
956         cairo_move_to(cr, 0, 0);
957         pango_cairo_layout_line_path(cr, line);
958         cairo_scale(cr, 1, -1);
959         cairo_translate(cr, -_last_tx, -_last_ty);
960 #endif
961         cairo_stroke(cr);
962     }
965     cairo_restore(cr);
967 #ifndef RENDER_WITH_PANGO_CAIRO
968     cairo_font_face_destroy(font_face);
970     if (dirty_pattern) {
971         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
972         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
973     }
974 #endif
976     return 0;
979 /* Helper functions */
981 void
982 PrintCairoPDF::print_bpath(cairo_t *cr, NArtBpath const *bp)
984     cairo_new_path(cr);
985     bool closed = false;
986     while (bp->code != NR_END) {
987         switch (bp->code) {
988             case NR_MOVETO:
989                 if (closed) {
990                     cairo_close_path(cr);
991                 }
992                 closed = true;
993                 cairo_move_to(cr, bp->x3, bp->y3);
994                 break;
995             case NR_MOVETO_OPEN:
996                 if (closed) {
997                     cairo_close_path(cr);
998                 }
999                 closed = false;
1000                 cairo_move_to(cr, bp->x3, bp->y3);
1001                 break;
1002             case NR_LINETO:
1003                 cairo_line_to(cr, bp->x3, bp->y3);
1004                 break;
1005             case NR_CURVETO:
1006                 cairo_curve_to(cr, bp->x1, bp->y1, bp->x2, bp->y2, bp->x3, bp->y3);
1007                 break;
1008             default:
1009                 break;
1010         }
1011         bp += 1;
1012     }
1013     if (closed) {
1014         cairo_close_path(cr);
1015     }
1018 static void
1019 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
1021     cairo_matrix_t matrix;
1023     cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
1024     cairo_transform(cr, &matrix);
1027 static cairo_status_t
1028 _write_callback(void *closure, const unsigned char *data, unsigned int length)
1030     size_t written;
1031     FILE *file = (FILE*)closure;
1033     written = fwrite (data, 1, length, file);
1035     if (written == length)
1036         return CAIRO_STATUS_SUCCESS;
1037     else
1038         return CAIRO_STATUS_WRITE_ERROR;
1041 bool
1042 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
1044     return ext->get_param_bool("textToPath");
1047 #include "clear-n_.h"
1049 void
1050 PrintCairoPDF::init(void)
1052     /* PDF out */
1053     (void) Inkscape::Extension::build_from_mem(
1054         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
1055         "<name>" N_("PDF Print") "</name>\n"
1056         "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1057         "<param name=\"bitmap\" type=\"boolean\">false</param>\n"
1058         "<param name=\"resolution\" type=\"string\">72</param>\n"
1059         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1060         "<param name=\"pageBoundingBox\" type=\"boolean\">true</param>\n"
1061         "<param name=\"textToPath\" type=\"boolean\">true</param>\n"
1062         "<param name=\"exportDrawing\" type=\"boolean\">false</param>\n"
1063         "<param name=\"exportCanvas\" type=\"boolean\">false</param>\n"
1064         "<param name=\"exportId\" type=\"string\"></param>\n"
1065         "<print/>\n"
1066         "</inkscape-extension>", new PrintCairoPDF());
1070 }  /* namespace Internal */
1071 }  /* namespace Extension */
1072 }  /* namespace Inkscape */
1074 /* End of GNU GPL code */
1076 #endif /* HAVE_CAIRO_PDF */
1079 /*
1080   Local Variables:
1081   mode:c++
1082   c-file-style:"stroustrup"
1083   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1084   indent-tabs-mode:nil
1085   fill-column:99
1086   End:
1087 */
1088 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :