Code

No more NRMatrix or NRPoint.
[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 <unit-constants.h>
60 #include "pdf-cairo.h"
61 #include "extension/system.h"
62 #include "extension/print.h"
64 #include "io/sys.h"
66 #include <cairo.h>
67 #include <cairo-pdf.h>
69 #include <pango/pango.h>
70 #include <pango/pangofc-fontmap.h>
72 #ifdef RENDER_WITH_PANGO_CAIRO
73 #include <pango/pangocairo.h>
74 #else
75 #include <cairo-ft.h>
76 #endif
77 namespace Inkscape {
78 namespace Extension {
79 namespace Internal {
81 static cairo_status_t _write_callback(void *closure, const unsigned char *data, unsigned int length);
82 static void _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0);
84 PrintCairoPDF::PrintCairoPDF() :
85     cr(NULL),
86     pdf_surface(NULL),
87     _layout(NULL),
88     _dpi(72),
89     _bitmap(false)
90 {
91 }
93 PrintCairoPDF::~PrintCairoPDF(void)
94 {
95     if (cr) cairo_destroy(cr);
96     if (pdf_surface) cairo_surface_destroy(pdf_surface);
97     if (_layout) g_object_unref(_layout);
99     /* restore default signal handling for SIGPIPE */
100 #if !defined(_WIN32) && !defined(__WIN32__)
101     (void) signal(SIGPIPE, SIG_DFL);
102 #endif
104     return;
107 unsigned int
108 PrintCairoPDF::setup(Inkscape::Extension::Print * mod)
110     static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
112 #ifdef TED
113     Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
114 #endif
116     unsigned int ret = FALSE;
118     /* Create dialog */
119     GtkTooltips *tt = gtk_tooltips_new();
120     g_object_ref((GObject *) tt);
121     gtk_object_sink((GtkObject *) tt);
123     GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
124 //            SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
125             NULL,
126             (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
127             GTK_STOCK_CANCEL,
128             GTK_RESPONSE_CANCEL,
129             GTK_STOCK_PRINT,
130             GTK_RESPONSE_OK,
131             NULL);
133     gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
135     GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
136     gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
137     /* Print properties frame */
138     GtkWidget *f = gtk_frame_new(_("Print properties"));
139     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
140     GtkWidget *vb = gtk_vbox_new(FALSE, 4);
141     gtk_container_add(GTK_CONTAINER(f), vb);
142     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
143     /* Print type */
144     bool const p2bm = mod->get_param_bool("bitmap");
145     GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PDF operators"));
146     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
147                          _("Use PDF vector operators. The resulting image is usually smaller "
148                            "in file size and can be arbitrarily scaled, but "
149                            "patterns will be lost."), NULL);
150     if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
151     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
152     rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
153     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
154                          _("Print everything as bitmap. The resulting image is usually larger "
155                            "in file size and cannot be arbitrarily scaled without quality loss, "
156                            "but all objects will be rendered exactly as displayed."), NULL);
157     if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
158     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
159     /* Resolution */
160     GtkWidget *hb = gtk_hbox_new(FALSE, 4);
161     gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
162     GtkWidget *combo = gtk_combo_new();
163     gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
164     gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
165     gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
166     gtk_widget_set_size_request(combo, 64, -1);
167     gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
168                          _("Preferred resolution (dots per inch) of bitmap"), NULL);
169     /* Setup strings */
170     GList *sl = NULL;
171     for (unsigned i = 0; pdr[i] != NULL; i++) {
172         sl = g_list_prepend(sl, (gpointer) pdr[i]);
173     }
174     sl = g_list_reverse(sl);
175     gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
176     g_list_free(sl);
177     if (1) {
178         gchar const *val = mod->get_param_string("resolution");
179         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
180     }
181     gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
182     GtkWidget *l = gtk_label_new(_("Resolution:"));
183     gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
185     /* Print destination frame */
186     f = gtk_frame_new(_("Print destination"));
187     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
188     vb = gtk_vbox_new(FALSE, 4);
189     gtk_container_add(GTK_CONTAINER(f), vb);
190     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
192     l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
193                         "leave empty to use the system default printer.\n"
194                         "Use '> filename' to print to file.\n"
195                         "Use '| prog arg...' to pipe to a program."));
196     gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
198     GtkWidget *e = gtk_entry_new();
199     if (1) {
200         gchar const *val = mod->get_param_string("destination");
201         gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
202                                            ? val
203                                            : "" ));
204     }
205     gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
207     // pressing enter in the destination field is the same as clicking Print:
208     gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
210     gtk_widget_show_all(vbox);
212     int const response = gtk_dialog_run(GTK_DIALOG(dlg));
214     g_object_unref((GObject *) tt);
216     if (response == GTK_RESPONSE_OK) {
217         gchar const *fn;
218         char const *sstr;
220         _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
221         sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
222         _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
223         /* Arrgh, have to do something */
224         fn = gtk_entry_get_text(GTK_ENTRY(e));
225         /* skip leading whitespace, bug #1068483 */
226         while (fn && *fn==' ') { fn++; }
227         /* g_print("Printing to %s\n", fn); */
229         mod->set_param_bool("bitmap", _bitmap);
230         mod->set_param_string("resolution", (gchar *)sstr);
231         mod->set_param_string("destination", (gchar *)fn);
232         ret = TRUE;
233     }
235     gtk_widget_destroy(dlg);
237     return ret;
240 unsigned int
241 PrintCairoPDF::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
243     FILE *osf = NULL;
244     FILE *osp = NULL;
246     _alpha_stack.clear();
247     _alpha_stack.push_back(1.0);
249     gsize bytesRead = 0;
250     gsize bytesWritten = 0;
251     GError *error = NULL;
252     gchar const *utf8_fn = mod->get_param_string("destination");
253     gchar *local_fn = g_filename_from_utf8( utf8_fn,
254                                             -1,  &bytesRead,  &bytesWritten, &error);
255     gchar const *fn = local_fn;
257     /* TODO: Replace the below fprintf's with something that does the right thing whether in
258      * gui or batch mode (e.g. --print=blah).  Consider throwing an exception: currently one of
259      * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
260      * return code.
261      */
262     if (fn != NULL) {
263         if (*fn == '|') {
264             fn += 1;
265             while (isspace(*fn)) fn += 1;
266 #ifndef WIN32
267             osp = popen(fn, "w");
268 #else
269             osp = _popen(fn, "w");
270 #endif
271             if (!osp) {
272                 fprintf(stderr, "inkscape: popen(%s): %s\n",
273                         fn, strerror(errno));
274                 return 0;
275             }
276             _stream = osp;
277         } else if (*fn == '>') {
278             fn += 1;
279             while (isspace(*fn)) fn += 1;
280             Inkscape::IO::dump_fopen_call(fn, "K");
281             osf = Inkscape::IO::fopen_utf8name(fn, "w+");
282             if (!osf) {
283                 fprintf(stderr, "inkscape: fopen(%s): %s\n",
284                         fn, strerror(errno));
285                 return 0;
286             }
287             _stream = osf;
288         } else {
289             /* put cwd stuff in here */
290             gchar *qn = ( *fn
291                           ? g_strdup_printf("lpr -P %s", fn)  /* FIXME: quote fn */
292                           : g_strdup("lpr") );
293 #ifndef WIN32
294             osp = popen(qn, "w");
295 #else
296             osp = _popen(qn, "w");
297 #endif
298             if (!osp) {
299                 fprintf(stderr, "inkscape: popen(%s): %s\n",
300                         qn, strerror(errno));
301                 return 0;
302             }
303             g_free(qn);
304             _stream = osp;
305         }
306     }
308     g_free(local_fn);
310     if (_stream) {
311         /* fixme: this is kinda icky */
312 #if !defined(_WIN32) && !defined(__WIN32__)
313         (void) signal(SIGPIPE, SIG_IGN);
314 #endif
315     }
317     // test output stream?
319     // width and height in pt
320     _width = sp_document_width(doc) * PT_PER_PX;
321     _height = sp_document_height(doc) * PT_PER_PX;
323     NRRect d;
324     bool   pageBoundingBox;
325     pageBoundingBox = mod->get_param_bool("pageBoundingBox");
326     // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
327     if (pageBoundingBox) {
328         d.x0 = d.y0 = 0;
329         d.x1 = _width;
330         d.y1 = _height;
331     } else {
332         // if not page, use our base, which is either root or the item we want to export
333         SPItem* doc_item = SP_ITEM(mod->base);
334         sp_item_invoke_bbox(doc_item, &d, sp_item_i2root_affine(doc_item), TRUE);
335         // convert from px to pt
336         d.x0 *= PT_PER_PX;
337         d.x1 *= PT_PER_PX;
338         d.y0 *= PT_PER_PX;
339         d.y1 *= PT_PER_PX;
340     }
341     // printf("\n _width:%f _height:%f scale:%f\n", _width, _height, PT_PER_PX);
342     pdf_surface = cairo_pdf_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, d.x1-d.x0, d.y1-d.y0);
343     cr = cairo_create(pdf_surface);
344     // move to the origin
345     cairo_translate (cr, -d.x0, -d.y0);
347     if (!_bitmap) {
348         cairo_scale(cr, PT_PER_PX, PT_PER_PX);
350         // from now on we can output px, but they will be treated as pt
351         // note that the we do not have to flip the y axis
352         // because Cairo's coordinate system is identical to Inkscape's
353     }
355     return 1;
358 unsigned int
359 PrintCairoPDF::finish(Inkscape::Extension::Print *mod)
361     if (!_stream) return 0;
362     if (_bitmap) return 0;
364     cairo_show_page(cr);
366     cairo_destroy(cr);
367     cairo_surface_destroy(pdf_surface);
368     cr = NULL;
369     pdf_surface = NULL;
371     /* Flush stream to be sure. */
372     (void) fflush(_stream);
374     /* fixme: should really use pclose for popen'd streams */
375     fclose(_stream);
376     _stream = 0;
378     return 1;
381 unsigned int
382 PrintCairoPDF::bind(Inkscape::Extension::Print *mod, NR::Matrix const *transform, float opacity)
384     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
385     if (_bitmap) return 0;
387     if (opacity < 1.0) {
388         cairo_push_group(cr);
389     } else {
390         cairo_save(cr);
391     }
392     _concat_transform(cr, (*transform)[0], (*transform)[1], (*transform)[2], (*transform)[3], (*transform)[4], (*transform)[5]);
393     // 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]);
394     // remember these to be able to undo them when outputting text
395     _last_tx = (*transform)[4];
396     _last_ty = (*transform)[5];
398     _alpha_stack.push_back(opacity);
400     return 1;
403 unsigned int
404 PrintCairoPDF::release(Inkscape::Extension::Print *mod)
406     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
407     if (_bitmap) return 0;
409     float opacity = _alpha_stack.back();
411     if (opacity < 1.0) {
412         cairo_pop_group_to_source(cr);
413         cairo_paint_with_alpha(cr, opacity);
414     } else {
415         cairo_restore(cr);
416     }
417 //    g_printf("release\n");
418     _alpha_stack.pop_back();
419     g_assert(_alpha_stack.size() > 0);
421     return 1;
424 unsigned int
425 PrintCairoPDF::comment(Inkscape::Extension::Print *mod, char const *comment)
427     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
428     if (_bitmap) return 0;
430     return 1;
433 cairo_pattern_t*
434 PrintCairoPDF::create_pattern_for_paint(SPPaintServer const *const paintserver, NRRect const *pbox, float alpha)
436     cairo_pattern_t *pattern = NULL;
437     bool apply_bbox2user = false;
439     if (SP_IS_LINEARGRADIENT (paintserver)) {
441             SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver);
443             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
445             NR::Point p1 (lg->x1.computed, lg->y1.computed);
446             NR::Point p2 (lg->x2.computed, lg->y2.computed);
447             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
448                 // convert to userspace
449                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
450                 p1 *= bbox2user;
451                 p2 *= bbox2user;
452             }
454             // create linear gradient pattern
455             pattern = cairo_pattern_create_linear(p1[NR::X], p1[NR::Y], p2[NR::X], p2[NR::Y]);
457             // add stops
458             for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) {
459                 float rgb[3];
460                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
461                 cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha);
462             }
463     } else if (SP_IS_RADIALGRADIENT (paintserver)) {
465         SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver);
467         sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
469         NR::Point c (rg->cx.computed, rg->cy.computed);
470         NR::Point f (rg->fx.computed, rg->fy.computed);
471         double r = rg->r.computed;
473         NR::Coord const df = hypot(f[NR::X] - c[NR::X], f[NR::Y] - c[NR::Y]);
474         if (df >= r) {
475             f[NR::X] = c[NR::X] + (f[NR::X] - c[NR::X] ) * r / (float) df;
476             f[NR::Y] = c[NR::Y] + (f[NR::Y] - c[NR::Y] ) * r / (float) df;
477         }
479         if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
480             apply_bbox2user = true;
482         // create radial gradient pattern
483         pattern = cairo_pattern_create_radial(f[NR::X], f[NR::Y], 0, c[NR::X], c[NR::Y], r);
485         // add stops
486         for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) {
487             float rgb[3];
488             sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
489             cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha);
490         }
491     }
493     if (pattern) {
494         SPGradient *g = SP_GRADIENT(paintserver);
496         // set extend type
497         SPGradientSpread spread = sp_gradient_get_spread(g);
498         switch (spread) {
499                 case SP_GRADIENT_SPREAD_REPEAT:
500                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
501                         break;
502                 case SP_GRADIENT_SPREAD_REFLECT:
503                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT);
504                         break;
505                 case SP_GRADIENT_SPREAD_PAD:
506             default:
507                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_PAD);
508                         break;
509         }
511         cairo_matrix_t pattern_matrix;
512         if (g->gradientTransform_set) {
513                 // apply gradient transformation
514                 cairo_matrix_init(&pattern_matrix,
515                     g->gradientTransform[0], g->gradientTransform[1],
516                     g->gradientTransform[2], g->gradientTransform[3],
517                     g->gradientTransform[4], g->gradientTransform[5]);
518         } else {
519             cairo_matrix_init_identity (&pattern_matrix);
520         }
522         if (apply_bbox2user) {
523             // convert to userspace
524             cairo_matrix_t bbox2user;
525             cairo_matrix_init (&bbox2user, pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
526             cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix);
527         }
528         cairo_matrix_invert(&pattern_matrix);   // because Cairo expects a userspace->patternspace matrix
529         cairo_pattern_set_matrix(pattern, &pattern_matrix);
530     }
532     return pattern;
535 void
536 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
538     g_return_if_fail( style->fill.isColor()
539                       || ( style->fill.isPaintserver()
540                            && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
542     if (style->fill.isColor()) {
543         float rgb[3];
544         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
546         float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
548         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
549     } else {
550         g_assert( style->fill.isPaintserver()
551                   && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
553         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_FILL_SERVER(style), pbox, 1.0);
555         if (pattern) {
556                 cairo_set_source(cr, pattern);
557             cairo_pattern_destroy(pattern);
558         }
559     }
562 unsigned int
563 PrintCairoPDF::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NR::Matrix const *ctm, SPStyle const *const style,
564               NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
566     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
567     if (_bitmap) return 0;
569     if ( style->fill.isColor()
570          || ( style->fill.isPaintserver()
571               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) ) {
573         float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
575         cairo_save(cr);
577         print_fill_style(cr, style, pbox);
578         print_bpath(cr, bpath->path);
579         if (style->fill_rule.computed == SP_WIND_RULE_EVENODD) {
580             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
581         } else {
582             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
583         }
584         if (alpha != 1.0 &&
585             !style->fill.isColor()) {
587             cairo_clip (cr);
588             cairo_paint_with_alpha (cr, alpha);
589         } else {
590             cairo_fill(cr);
591         }
593         cairo_restore(cr);
594     }
596     return 0;
599 void
600 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
602     float alpha = SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
604     if ( style->stroke.isColor() ) {
605         float rgb[3];
606         sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
608         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
609     } else if ( style->stroke.isPaintserver()
610                   && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
612         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
614         if (pattern) {
615                 cairo_set_source(cr, pattern);
616             cairo_pattern_destroy(pattern);
617         }
618     }
620     if (style->stroke_dash.n_dash   &&
621         style->stroke_dash.dash       )
622     {
623         cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
624     } else {
625         cairo_set_dash(cr, NULL, 0, 0.0);       // disable dashing
626     }
628     cairo_set_line_width(cr, style->stroke_width.computed);
630     // set line join type
631     cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
632     switch (style->stroke_linejoin.computed) {
633         case SP_STROKE_LINEJOIN_MITER:
634             join = CAIRO_LINE_JOIN_MITER;
635             break;
636         case SP_STROKE_LINEJOIN_ROUND:
637             join = CAIRO_LINE_JOIN_ROUND;
638             break;
639         case SP_STROKE_LINEJOIN_BEVEL:
640             join = CAIRO_LINE_JOIN_BEVEL;
641             break;
642     }
643     cairo_set_line_join(cr, join);
645     // set line cap type
646     cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
647     switch (style->stroke_linecap.computed) {
648         case SP_STROKE_LINECAP_BUTT:
649             cap = CAIRO_LINE_CAP_BUTT;
650             break;
651         case SP_STROKE_LINECAP_ROUND:
652             cap = CAIRO_LINE_CAP_ROUND;
653             break;
654         case SP_STROKE_LINECAP_SQUARE:
655             cap = CAIRO_LINE_CAP_SQUARE;
656             break;
657     }
658     cairo_set_line_cap(cr, cap);
659     cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
662 unsigned int
663 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NR::Matrix const *ctm, SPStyle const *style,
664                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
666     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
667     if (_bitmap) return 0;
669     if ( style->stroke.isColor() ||
670          ( style->stroke.isPaintserver()
671               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
673         cairo_save(cr);
675         print_stroke_style(cr, style, pbox);
676         print_bpath(cr, bpath->path);
677         cairo_stroke(cr);
679         cairo_restore(cr);
680     }
682     return 0;
685 unsigned int
686 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
687                NR::Matrix const *transform, SPStyle const *style)
689     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
690     if (_bitmap) return 0;
692     guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
693     if (!px_rgba) return 0;
695     float alpha = _alpha_stack.back();
697     // make a copy of the original pixbuf with premultiplied alpha
698     // if we pass the original pixbuf it will get messed up
699     for (unsigned i = 0; i < h; i++) {
700         for (unsigned j = 0; j < w; j++) {
701             guchar const *src = px + i * rs + j * 4;
702             guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
703             guchar r, g, b, alpha_dst;
705             // calculate opacity-modified alpha
706             alpha_dst = src[3];
707             if (alpha != 1.0)
708                 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
710             // premul alpha (needed because this will be undone by cairo-pdf)
711             r = src[0]*alpha_dst/255;
712             g = src[1]*alpha_dst/255;
713             b = src[2]*alpha_dst/255;
715             *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
716         }
717     }
719     cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
720     if (cairo_surface_status(image_surface)) {
721         g_printf("Error: %s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
722         return 0;
723     }
725     cairo_save(cr);
727         // scaling by width & height is not needed because it will be done by cairo-pdf
728         // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
729     cairo_matrix_t matrix;
730     cairo_matrix_init(&matrix,
731                     (*transform)[0]/w, (*transform)[1],
732                     (*transform)[2], -(*transform)[3]/h,
733                     (*transform)[4], (*transform)[5] + (*transform)[3]);
734     cairo_transform(cr, &matrix);
736     cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
737     cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
739     cairo_set_source(cr, pattern);
740     cairo_pattern_destroy(pattern);
742     // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
743     cairo_new_path(cr);
744     cairo_rectangle(cr, 0, 0, w, h);
745     cairo_clip(cr);
747     cairo_paint(cr);
749     cairo_restore(cr);
751     cairo_surface_destroy(image_surface);
752     g_free(px_rgba);
754     return 0;
757 #define GLYPH_ARRAY_SIZE 64
759 #ifndef RENDER_WITH_PANGO_CAIRO
761 NR::Point
762 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
763                bool vertical, bool stroke)
765     cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
766     cairo_glyph_t *glyphs = glyph_array;
767     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
768         glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
770     PangoGlyphUnit x_offset = 0, y_offset = 0;
771     PangoGlyphInfo *info;
772     int num_invalid_glyphs = 0;
773     for (gint i = 0; i < glyph_string->num_glyphs; i++) {
774         info = &glyph_string->glyphs[i];
775         // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) or have
776         // the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set
777         if (info->glyph == 0x0FFFFFFF || info->glyph & 0x10000000) {
778             num_invalid_glyphs++;
779             continue;
780         }
782         glyphs[i - num_invalid_glyphs].index = info->glyph;
783         glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
784         glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
786         if (vertical) {
787             cairo_text_extents_t extents;
788             cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
789             y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
790         }
791         else
792             x_offset += info->geometry.width;
793     }
795     if (stroke)
796         cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
797     else
798         cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
800     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
801         g_free(glyphs);
803     return NR::Point(x_offset, y_offset);
805 #endif
809 unsigned int
810 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
811               SPStyle const *const style)
813     bool dirty_pattern = false;
815     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
816     if (_bitmap) return 0;
818     cairo_save(cr);
820     // this needs to be there to encounter Cairo's userspace locking semantics for set_source
821     // otherwise gradients won't be shown correctly
822     // printf("\n _last_tx:%f _last_ty:%f", _last_tx, _last_ty);
823     cairo_translate(cr, -_last_tx, -_last_ty);
825     // create pango layout and context if needed
826     if (_layout == NULL) {
827 #ifdef RENDER_WITH_PANGO_CAIRO
828         //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
829         _layout = pango_cairo_create_layout(cr);
830 #else
831         _layout = pango_layout_new((font_factory::Default())->fontContext);
832 #endif
833     }
835     // create font instance from style and use it
836     font_instance *tf = font_factory::Default()->FaceFromStyle(style);
837     if (tf == NULL) {   // do something
838         g_printf("Warning: trouble getting font_instance\n");
839         tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
840     }
841     PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
843     pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
844     pango_layout_set_font_description(_layout, adjusted);
845     pango_layout_set_text(_layout, text, -1);
847     pango_font_description_free(adjusted);
848     tf->Unref();
850 #ifdef RENDER_WITH_PANGO_CAIRO
851     pango_cairo_update_layout(cr, _layout);
852 #else
853     pango_layout_context_changed(_layout);   // is this needed?
854 #endif
856     PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
857     if (line == NULL)
858         return 0;
860 #ifndef RENDER_WITH_PANGO_CAIRO
861     // apply the selected font
862     double size;
863     PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
864     PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
865     FcPattern *fc_pattern = fc_font->font_pattern;
867     if ( style->writing_mode.set &&
868        (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
869         style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
870     {
871         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
872         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
873         dirty_pattern = true;
874     }
876     cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
877     cairo_set_font_face(cr, font_face);
879     if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
880         size = 12.0;
882     // adjust size and horizontal flip
883     cairo_matrix_t matrix;
884     cairo_get_font_matrix(cr, &matrix);
885     matrix.xx = size;
886     matrix.yy = -matrix.xx;
887     cairo_set_font_matrix(cr, &matrix);
888 #endif
890     if ( style->fill.isColor()
891          || ( style->fill.isPaintserver()
892               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
893     {
894         // set fill style
895         print_fill_style(cr, style, NULL);
897 #ifndef RENDER_WITH_PANGO_CAIRO
898         NR::Point cursor(_last_tx, _last_ty);
899         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
900             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
901             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
902         }
903 #else
904         cairo_new_path(cr);
905         // as pango has inverted origin we simulate the moveto and apply the vertical flip
906         //cairo_move_to(cr, _last_tx, _last_ty);
907         cairo_translate(cr, _last_tx, _last_ty);
908         cairo_scale(cr, 1, -1);
909         cairo_move_to(cr, 0, 0);
910         pango_cairo_show_layout_line(cr, line);
911         cairo_scale(cr, 1, -1);
912         cairo_translate(cr, -_last_tx, -_last_ty);
914 #endif
915     }
917     if (style->stroke.isColor()
918         || ( style->stroke.isPaintserver()
919               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
920     {
921         // set stroke style
922         print_stroke_style(cr, style, NULL);
924         // paint stroke
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, true) / 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_layout_line_path(cr, line);
939         cairo_scale(cr, 1, -1);
940         cairo_translate(cr, -_last_tx, -_last_ty);
941 #endif
942         cairo_stroke(cr);
943     }
946     cairo_restore(cr);
948 #ifndef RENDER_WITH_PANGO_CAIRO
949     cairo_font_face_destroy(font_face);
951     if (dirty_pattern) {
952         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
953         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
954     }
955 #endif
957     return 0;
960 /* Helper functions */
962 void
963 PrintCairoPDF::print_bpath(cairo_t *cr, NArtBpath const *bp)
965     cairo_new_path(cr);
966     bool closed = false;
967     while (bp->code != NR_END) {
968         switch (bp->code) {
969             case NR_MOVETO:
970                 if (closed) {
971                     cairo_close_path(cr);
972                 }
973                 closed = true;
974                 cairo_move_to(cr, bp->x3, bp->y3);
975                 break;
976             case NR_MOVETO_OPEN:
977                 if (closed) {
978                     cairo_close_path(cr);
979                 }
980                 closed = false;
981                 cairo_move_to(cr, bp->x3, bp->y3);
982                 break;
983             case NR_LINETO:
984                 cairo_line_to(cr, bp->x3, bp->y3);
985                 break;
986             case NR_CURVETO:
987                 cairo_curve_to(cr, bp->x1, bp->y1, bp->x2, bp->y2, bp->x3, bp->y3);
988                 break;
989             default:
990                 break;
991         }
992         bp += 1;
993     }
994     if (closed) {
995         cairo_close_path(cr);
996     }
999 static void
1000 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
1002     cairo_matrix_t matrix;
1004     cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
1005     cairo_transform(cr, &matrix);
1008 static cairo_status_t
1009 _write_callback(void *closure, const unsigned char *data, unsigned int length)
1011     size_t written;
1012     FILE *file = (FILE*)closure;
1014     written = fwrite (data, 1, length, file);
1016     if (written == length)
1017         return CAIRO_STATUS_SUCCESS;
1018     else
1019         return CAIRO_STATUS_WRITE_ERROR;
1022 bool
1023 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
1025     return ext->get_param_bool("textToPath");
1028 #include "clear-n_.h"
1030 void
1031 PrintCairoPDF::init(void)
1033     /* PDF out */
1034     (void) Inkscape::Extension::build_from_mem(
1035         "<inkscape-extension>\n"
1036         "<name>" N_("PDF Print") "</name>\n"
1037         "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1038         "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1039         "<param name=\"resolution\" type=\"string\">72</param>\n"
1040         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1041         "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1042         "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1043         "<param name=\"exportDrawing\" type=\"boolean\">FALSE</param>\n"
1044         "<param name=\"exportId\" type=\"string\"></param>\n"
1045         "<print/>\n"
1046         "</inkscape-extension>", new PrintCairoPDF());
1050 }  /* namespace Internal */
1051 }  /* namespace Extension */
1052 }  /* namespace Inkscape */
1054 /* End of GNU GPL code */
1056 #endif /* HAVE_CAIRO_PDF */
1059 /*
1060   Local Variables:
1061   mode:c++
1062   c-file-style:"stroustrup"
1063   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1064   indent-tabs-mode:nil
1065   fill-column:99
1066   End:
1067 */
1068 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :