Code

remove no longer needed inclusions
[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         feed_pathvector_to_cairo(cr, pathv);
604         if (style->fill_rule.computed == SP_WIND_RULE_EVENODD) {
605             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
606         } else {
607             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
608         }
609         if (alpha != 1.0 &&
610             !style->fill.isColor()) {
612             cairo_clip (cr);
613             cairo_paint_with_alpha (cr, alpha);
614         } else {
615             cairo_fill(cr);
616         }
618         cairo_restore(cr);
619     }
621     return 0;
624 void
625 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
627     float alpha = SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
629     if ( style->stroke.isColor() ) {
630         float rgb[3];
631         sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
633         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
634     } else if ( style->stroke.isPaintserver()
635                   && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
637         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
639         if (pattern) {
640                 cairo_set_source(cr, pattern);
641             cairo_pattern_destroy(pattern);
642         }
643     }
645     if (style->stroke_dash.n_dash   &&
646         style->stroke_dash.dash       )
647     {
648         cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
649     } else {
650         cairo_set_dash(cr, NULL, 0, 0.0);       // disable dashing
651     }
653     cairo_set_line_width(cr, style->stroke_width.computed);
655     // set line join type
656     cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
657     switch (style->stroke_linejoin.computed) {
658         case SP_STROKE_LINEJOIN_MITER:
659             join = CAIRO_LINE_JOIN_MITER;
660             break;
661         case SP_STROKE_LINEJOIN_ROUND:
662             join = CAIRO_LINE_JOIN_ROUND;
663             break;
664         case SP_STROKE_LINEJOIN_BEVEL:
665             join = CAIRO_LINE_JOIN_BEVEL;
666             break;
667     }
668     cairo_set_line_join(cr, join);
670     // set line cap type
671     cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
672     switch (style->stroke_linecap.computed) {
673         case SP_STROKE_LINECAP_BUTT:
674             cap = CAIRO_LINE_CAP_BUTT;
675             break;
676         case SP_STROKE_LINECAP_ROUND:
677             cap = CAIRO_LINE_CAP_ROUND;
678             break;
679         case SP_STROKE_LINECAP_SQUARE:
680             cap = CAIRO_LINE_CAP_SQUARE;
681             break;
682     }
683     cairo_set_line_cap(cr, cap);
684     cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
687 unsigned int
688 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, Geom::PathVector const &pathv, NR::Matrix const *ctm, SPStyle const *style,
689                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
691     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
692     if (_bitmap) return 0;
694     if ( style->stroke.isColor() ||
695          ( style->stroke.isPaintserver()
696               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
698         cairo_save(cr);
700         print_stroke_style(cr, style, pbox);
702         feed_pathvector_to_cairo(cr, pathv);
703         cairo_stroke(cr);
705         cairo_restore(cr);
706     }
708     return 0;
711 unsigned int
712 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
713                NR::Matrix const *transform, SPStyle const *style)
715     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
716     if (_bitmap) return 0;
718     guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
719     if (!px_rgba) return 0;
721     float alpha = _alpha_stack.back();
723     // make a copy of the original pixbuf with premultiplied alpha
724     // if we pass the original pixbuf it will get messed up
725     for (unsigned i = 0; i < h; i++) {
726         for (unsigned j = 0; j < w; j++) {
727             guchar const *src = px + i * rs + j * 4;
728             guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
729             guchar r, g, b, alpha_dst;
731             // calculate opacity-modified alpha
732             alpha_dst = src[3];
733             if (alpha != 1.0)
734                 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
736             // premul alpha (needed because this will be undone by cairo-pdf)
737             r = src[0]*alpha_dst/255;
738             g = src[1]*alpha_dst/255;
739             b = src[2]*alpha_dst/255;
741             *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
742         }
743     }
745     cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
746     if (cairo_surface_status(image_surface)) {
747         g_printf("Error: %s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
748         return 0;
749     }
751     cairo_save(cr);
753         // scaling by width & height is not needed because it will be done by cairo-pdf
754         // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
755     cairo_matrix_t matrix;
756     cairo_matrix_init(&matrix,
757                     (*transform)[0]/w, (*transform)[1],
758                     (*transform)[2], -(*transform)[3]/h,
759                     (*transform)[4], (*transform)[5] + (*transform)[3]);
760     cairo_transform(cr, &matrix);
762     cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
763     cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
765     cairo_set_source(cr, pattern);
766     cairo_pattern_destroy(pattern);
768     // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
769     cairo_new_path(cr);
770     cairo_rectangle(cr, 0, 0, w, h);
771     cairo_clip(cr);
773     cairo_paint(cr);
775     cairo_restore(cr);
777     cairo_surface_destroy(image_surface);
778     g_free(px_rgba);
780     return 0;
783 #define GLYPH_ARRAY_SIZE 64
785 #ifndef RENDER_WITH_PANGO_CAIRO
787 NR::Point
788 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
789                bool vertical, bool stroke)
791     cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
792     cairo_glyph_t *glyphs = glyph_array;
793     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
794         glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
796     PangoGlyphUnit x_offset = 0, y_offset = 0;
797     PangoGlyphInfo *info;
798     int num_invalid_glyphs = 0;
799     for (gint i = 0; i < glyph_string->num_glyphs; i++) {
800         info = &glyph_string->glyphs[i];
801         // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) or have
802         // the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set
803         if (info->glyph == 0x0FFFFFFF || info->glyph & 0x10000000) {
804             num_invalid_glyphs++;
805             continue;
806         }
808         glyphs[i - num_invalid_glyphs].index = info->glyph;
809         glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
810         glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
812         if (vertical) {
813             cairo_text_extents_t extents;
814             cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
815             y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
816         }
817         else
818             x_offset += info->geometry.width;
819     }
821     if (stroke)
822         cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
823     else
824         cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
826     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
827         g_free(glyphs);
829     return NR::Point(x_offset, y_offset);
831 #endif
835 unsigned int
836 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
837               SPStyle const *const style)
839     bool dirty_pattern = false;
841     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
842     if (_bitmap) return 0;
844     cairo_save(cr);
846     // this needs to be there to encounter Cairo's userspace locking semantics for set_source
847     // otherwise gradients won't be shown correctly
848     // printf("\n _last_tx:%f _last_ty:%f", _last_tx, _last_ty);
849     cairo_translate(cr, -_last_tx, -_last_ty);
851     // create pango layout and context if needed
852     if (_layout == NULL) {
853 #ifdef RENDER_WITH_PANGO_CAIRO
854         //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
855         _layout = pango_cairo_create_layout(cr);
856 #else
857         _layout = pango_layout_new((font_factory::Default())->fontContext);
858 #endif
859     }
861     // create font instance from style and use it
862     font_instance *tf = font_factory::Default()->FaceFromStyle(style);
863     if (tf == NULL) {   // do something
864         g_printf("Warning: trouble getting font_instance\n");
865         tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
866     }
867     PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
869     pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
870     pango_layout_set_font_description(_layout, adjusted);
871     pango_layout_set_text(_layout, text, -1);
873     pango_font_description_free(adjusted);
874     tf->Unref();
876 #ifdef RENDER_WITH_PANGO_CAIRO
877     pango_cairo_update_layout(cr, _layout);
878 #else
879     pango_layout_context_changed(_layout);   // is this needed?
880 #endif
882     PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
883     if (line == NULL)
884         return 0;
886 #ifndef RENDER_WITH_PANGO_CAIRO
887     // apply the selected font
888     double size;
889     PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
890     PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
891     FcPattern *fc_pattern = fc_font->font_pattern;
893     if ( style->writing_mode.set &&
894        (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
895         style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
896     {
897         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
898         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
899         dirty_pattern = true;
900     }
902     cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
903     cairo_set_font_face(cr, font_face);
905     if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
906         size = 12.0;
908     // adjust size and horizontal flip
909     cairo_matrix_t matrix;
910     cairo_get_font_matrix(cr, &matrix);
911     matrix.xx = size;
912     matrix.yy = -matrix.xx;
913     cairo_set_font_matrix(cr, &matrix);
914 #endif
916     if ( style->fill.isColor()
917          || ( style->fill.isPaintserver()
918               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
919     {
920         // set fill style
921         print_fill_style(cr, style, NULL);
923 #ifndef RENDER_WITH_PANGO_CAIRO
924         NR::Point cursor(_last_tx, _last_ty);
925         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
926             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
927             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
928         }
929 #else
930         cairo_new_path(cr);
931         // as pango has inverted origin we simulate the moveto and apply the vertical flip
932         //cairo_move_to(cr, _last_tx, _last_ty);
933         cairo_translate(cr, _last_tx, _last_ty);
934         cairo_scale(cr, 1, -1);
935         cairo_move_to(cr, 0, 0);
936         pango_cairo_show_layout_line(cr, line);
937         cairo_scale(cr, 1, -1);
938         cairo_translate(cr, -_last_tx, -_last_ty);
940 #endif
941     }
943     if (style->stroke.isColor()
944         || ( style->stroke.isPaintserver()
945               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
946     {
947         // set stroke style
948         print_stroke_style(cr, style, NULL);
950         // paint stroke
951 #ifndef RENDER_WITH_PANGO_CAIRO
952         NR::Point cursor(_last_tx, _last_ty);
953         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
954             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
955             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, true) / PANGO_SCALE;
956         }
957 #else
958         cairo_new_path(cr);
959         // as pango has inverted origin we simulate the moveto and apply the vertical flip
960         //cairo_move_to(cr, _last_tx, _last_ty);
961         cairo_translate(cr, _last_tx, _last_ty);
962         cairo_scale(cr, 1, -1);
963         cairo_move_to(cr, 0, 0);
964         pango_cairo_layout_line_path(cr, line);
965         cairo_scale(cr, 1, -1);
966         cairo_translate(cr, -_last_tx, -_last_ty);
967 #endif
968         cairo_stroke(cr);
969     }
972     cairo_restore(cr);
974 #ifndef RENDER_WITH_PANGO_CAIRO
975     cairo_font_face_destroy(font_face);
977     if (dirty_pattern) {
978         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
979         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
980     }
981 #endif
983     return 0;
986 /* Helper functions */
988 static void
989 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
991     cairo_matrix_t matrix;
993     cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
994     cairo_transform(cr, &matrix);
997 static cairo_status_t
998 _write_callback(void *closure, const unsigned char *data, unsigned int length)
1000     size_t written;
1001     FILE *file = (FILE*)closure;
1003     written = fwrite (data, 1, length, file);
1005     if (written == length)
1006         return CAIRO_STATUS_SUCCESS;
1007     else
1008         return CAIRO_STATUS_WRITE_ERROR;
1011 bool
1012 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
1014     return ext->get_param_bool("textToPath");
1017 #include "clear-n_.h"
1019 void
1020 PrintCairoPDF::init(void)
1022     /* PDF out */
1023     (void) Inkscape::Extension::build_from_mem(
1024         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
1025         "<name>" N_("PDF Print") "</name>\n"
1026         "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1027         "<param name=\"bitmap\" type=\"boolean\">false</param>\n"
1028         "<param name=\"resolution\" type=\"string\">72</param>\n"
1029         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1030         "<param name=\"pageBoundingBox\" type=\"boolean\">true</param>\n"
1031         "<param name=\"textToPath\" type=\"boolean\">true</param>\n"
1032         "<param name=\"exportDrawing\" type=\"boolean\">false</param>\n"
1033         "<param name=\"exportCanvas\" type=\"boolean\">false</param>\n"
1034         "<param name=\"exportId\" type=\"string\"></param>\n"
1035         "<print/>\n"
1036         "</inkscape-extension>", new PrintCairoPDF());
1040 }  /* namespace Internal */
1041 }  /* namespace Extension */
1042 }  /* namespace Inkscape */
1044 /* End of GNU GPL code */
1046 #endif /* HAVE_CAIRO_PDF */
1049 /*
1050   Local Variables:
1051   mode:c++
1052   c-file-style:"stroustrup"
1053   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1054   indent-tabs-mode:nil
1055   fill-column:99
1056   End:
1057 */
1058 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :