Code

add todo comment to make code prettier
[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, from_2geom(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 = from_2geom(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_finish(pdf_surface);
387     cairo_status_t status = cairo_surface_status(pdf_surface);
388     cairo_surface_destroy(pdf_surface);
389     cr = NULL;
390     pdf_surface = NULL;
392     /* Flush stream to be sure. */
393     (void) fflush(_stream);
395     /* fixme: should really use pclose for popen'd streams */
396     fclose(_stream);
397     _stream = 0;
399     if (status == CAIRO_STATUS_SUCCESS)
400         return true;
401     else
402         return false;
405 unsigned int
406 PrintCairoPDF::bind(Inkscape::Extension::Print *mod, NR::Matrix const *transform, float opacity)
408     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
409     if (_bitmap) return 0;
411     if (opacity < 1.0) {
412         cairo_push_group(cr);
413     } else {
414         cairo_save(cr);
415     }
416     _concat_transform(cr, (*transform)[0], (*transform)[1], (*transform)[2], (*transform)[3], (*transform)[4], (*transform)[5]);
417     // 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]);
418     // remember these to be able to undo them when outputting text
419     _last_tx = (*transform)[4];
420     _last_ty = (*transform)[5];
422     _alpha_stack.push_back(opacity);
424     return 1;
427 unsigned int
428 PrintCairoPDF::release(Inkscape::Extension::Print *mod)
430     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
431     if (_bitmap) return 0;
433     float opacity = _alpha_stack.back();
435     if (opacity < 1.0) {
436         cairo_pop_group_to_source(cr);
437         cairo_paint_with_alpha(cr, opacity);
438     } else {
439         cairo_restore(cr);
440     }
441 //    g_printf("release\n");
442     _alpha_stack.pop_back();
443     g_assert(_alpha_stack.size() > 0);
445     return 1;
448 unsigned int
449 PrintCairoPDF::comment(Inkscape::Extension::Print *mod, char const *comment)
451     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
452     if (_bitmap) return 0;
454     return 1;
457 cairo_pattern_t*
458 PrintCairoPDF::create_pattern_for_paint(SPPaintServer const *const paintserver, NRRect const *pbox, float alpha)
460     cairo_pattern_t *pattern = NULL;
461     bool apply_bbox2user = false;
463     if (SP_IS_LINEARGRADIENT (paintserver)) {
465             SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver);
467             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
469             NR::Point p1 (lg->x1.computed, lg->y1.computed);
470             NR::Point p2 (lg->x2.computed, lg->y2.computed);
471             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
472                 // convert to userspace
473                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
474                 p1 *= bbox2user;
475                 p2 *= bbox2user;
476             }
478             // create linear gradient pattern
479             pattern = cairo_pattern_create_linear(p1[NR::X], p1[NR::Y], p2[NR::X], p2[NR::Y]);
481             // add stops
482             for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) {
483                 float rgb[3];
484                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
485                 cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha);
486             }
487     } else if (SP_IS_RADIALGRADIENT (paintserver)) {
489         SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver);
491         sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
493         NR::Point c (rg->cx.computed, rg->cy.computed);
494         NR::Point f (rg->fx.computed, rg->fy.computed);
495         double r = rg->r.computed;
497         NR::Coord const df = hypot(f[NR::X] - c[NR::X], f[NR::Y] - c[NR::Y]);
498         if (df >= r) {
499             f[NR::X] = c[NR::X] + (f[NR::X] - c[NR::X] ) * r / (float) df;
500             f[NR::Y] = c[NR::Y] + (f[NR::Y] - c[NR::Y] ) * r / (float) df;
501         }
503         if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
504             apply_bbox2user = true;
506         // create radial gradient pattern
507         pattern = cairo_pattern_create_radial(f[NR::X], f[NR::Y], 0, c[NR::X], c[NR::Y], r);
509         // add stops
510         for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) {
511             float rgb[3];
512             sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
513             cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha);
514         }
515     }
517     if (pattern) {
518         SPGradient *g = SP_GRADIENT(paintserver);
520         // set extend type
521         SPGradientSpread spread = sp_gradient_get_spread(g);
522         switch (spread) {
523                 case SP_GRADIENT_SPREAD_REPEAT:
524                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
525                         break;
526                 case SP_GRADIENT_SPREAD_REFLECT:
527                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT);
528                         break;
529                 case SP_GRADIENT_SPREAD_PAD:
530             default:
531                         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_PAD);
532                         break;
533         }
535         cairo_matrix_t pattern_matrix;
536         if (g->gradientTransform_set) {
537                 // apply gradient transformation
538                 cairo_matrix_init(&pattern_matrix,
539                     g->gradientTransform[0], g->gradientTransform[1],
540                     g->gradientTransform[2], g->gradientTransform[3],
541                     g->gradientTransform[4], g->gradientTransform[5]);
542         } else {
543             cairo_matrix_init_identity (&pattern_matrix);
544         }
546         if (apply_bbox2user) {
547             // convert to userspace
548             cairo_matrix_t bbox2user;
549             cairo_matrix_init (&bbox2user, pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
550             cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix);
551         }
552         cairo_matrix_invert(&pattern_matrix);   // because Cairo expects a userspace->patternspace matrix
553         cairo_pattern_set_matrix(pattern, &pattern_matrix);
554     }
556     return pattern;
559 void
560 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
562     g_return_if_fail( style->fill.isColor()
563                       || ( style->fill.isPaintserver()
564                            && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
566     if (style->fill.isColor()) {
567         float rgb[3];
568         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
570         float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
572         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
573     } else {
574         g_assert( style->fill.isPaintserver()
575                   && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
577         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_FILL_SERVER(style), pbox, 1.0);
579         if (pattern) {
580                 cairo_set_source(cr, pattern);
581             cairo_pattern_destroy(pattern);
582         }
583     }
586 unsigned int
587 PrintCairoPDF::fill(Inkscape::Extension::Print *mod, const_NRBPath const *bpath, NR::Matrix const *ctm, SPStyle const *const style,
588               NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
590     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
591     if (_bitmap) return 0;
593     if ( style->fill.isColor()
594          || ( style->fill.isPaintserver()
595               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) ) {
597         float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
599         cairo_save(cr);
601         print_fill_style(cr, style, pbox);
602         print_bpath(cr, bpath->path);
603         if (style->fill_rule.computed == SP_WIND_RULE_EVENODD) {
604             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
605         } else {
606             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
607         }
608         if (alpha != 1.0 &&
609             !style->fill.isColor()) {
611             cairo_clip (cr);
612             cairo_paint_with_alpha (cr, alpha);
613         } else {
614             cairo_fill(cr);
615         }
617         cairo_restore(cr);
618     }
620     return 0;
623 void
624 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
626     float alpha = SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
628     if ( style->stroke.isColor() ) {
629         float rgb[3];
630         sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
632         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
633     } else if ( style->stroke.isPaintserver()
634                   && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
636         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
638         if (pattern) {
639                 cairo_set_source(cr, pattern);
640             cairo_pattern_destroy(pattern);
641         }
642     }
644     if (style->stroke_dash.n_dash   &&
645         style->stroke_dash.dash       )
646     {
647         cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
648     } else {
649         cairo_set_dash(cr, NULL, 0, 0.0);       // disable dashing
650     }
652     cairo_set_line_width(cr, style->stroke_width.computed);
654     // set line join type
655     cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
656     switch (style->stroke_linejoin.computed) {
657         case SP_STROKE_LINEJOIN_MITER:
658             join = CAIRO_LINE_JOIN_MITER;
659             break;
660         case SP_STROKE_LINEJOIN_ROUND:
661             join = CAIRO_LINE_JOIN_ROUND;
662             break;
663         case SP_STROKE_LINEJOIN_BEVEL:
664             join = CAIRO_LINE_JOIN_BEVEL;
665             break;
666     }
667     cairo_set_line_join(cr, join);
669     // set line cap type
670     cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
671     switch (style->stroke_linecap.computed) {
672         case SP_STROKE_LINECAP_BUTT:
673             cap = CAIRO_LINE_CAP_BUTT;
674             break;
675         case SP_STROKE_LINECAP_ROUND:
676             cap = CAIRO_LINE_CAP_ROUND;
677             break;
678         case SP_STROKE_LINECAP_SQUARE:
679             cap = CAIRO_LINE_CAP_SQUARE;
680             break;
681     }
682     cairo_set_line_cap(cr, cap);
683     cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
686 unsigned int
687 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, const_NRBPath const *bpath, NR::Matrix const *ctm, SPStyle const *style,
688                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
690     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
691     if (_bitmap) return 0;
693     if ( style->stroke.isColor() ||
694          ( style->stroke.isPaintserver()
695               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
697         cairo_save(cr);
699         print_stroke_style(cr, style, pbox);
700         print_bpath(cr, bpath->path);
701         cairo_stroke(cr);
703         cairo_restore(cr);
704     }
706     return 0;
709 unsigned int
710 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
711                NR::Matrix const *transform, SPStyle const *style)
713     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
714     if (_bitmap) return 0;
716     guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
717     if (!px_rgba) return 0;
719     float alpha = _alpha_stack.back();
721     // make a copy of the original pixbuf with premultiplied alpha
722     // if we pass the original pixbuf it will get messed up
723     for (unsigned i = 0; i < h; i++) {
724         for (unsigned j = 0; j < w; j++) {
725             guchar const *src = px + i * rs + j * 4;
726             guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
727             guchar r, g, b, alpha_dst;
729             // calculate opacity-modified alpha
730             alpha_dst = src[3];
731             if (alpha != 1.0)
732                 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
734             // premul alpha (needed because this will be undone by cairo-pdf)
735             r = src[0]*alpha_dst/255;
736             g = src[1]*alpha_dst/255;
737             b = src[2]*alpha_dst/255;
739             *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
740         }
741     }
743     cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
744     if (cairo_surface_status(image_surface)) {
745         g_printf("Error: %s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
746         return 0;
747     }
749     cairo_save(cr);
751         // scaling by width & height is not needed because it will be done by cairo-pdf
752         // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
753     cairo_matrix_t matrix;
754     cairo_matrix_init(&matrix,
755                     (*transform)[0]/w, (*transform)[1],
756                     (*transform)[2], -(*transform)[3]/h,
757                     (*transform)[4], (*transform)[5] + (*transform)[3]);
758     cairo_transform(cr, &matrix);
760     cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
761     cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
763     cairo_set_source(cr, pattern);
764     cairo_pattern_destroy(pattern);
766     // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
767     cairo_new_path(cr);
768     cairo_rectangle(cr, 0, 0, w, h);
769     cairo_clip(cr);
771     cairo_paint(cr);
773     cairo_restore(cr);
775     cairo_surface_destroy(image_surface);
776     g_free(px_rgba);
778     return 0;
781 #define GLYPH_ARRAY_SIZE 64
783 #ifndef RENDER_WITH_PANGO_CAIRO
785 NR::Point
786 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
787                bool vertical, bool stroke)
789     cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
790     cairo_glyph_t *glyphs = glyph_array;
791     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
792         glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
794     PangoGlyphUnit x_offset = 0, y_offset = 0;
795     PangoGlyphInfo *info;
796     int num_invalid_glyphs = 0;
797     for (gint i = 0; i < glyph_string->num_glyphs; i++) {
798         info = &glyph_string->glyphs[i];
799         // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) or have
800         // the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set
801         if (info->glyph == 0x0FFFFFFF || info->glyph & 0x10000000) {
802             num_invalid_glyphs++;
803             continue;
804         }
806         glyphs[i - num_invalid_glyphs].index = info->glyph;
807         glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
808         glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
810         if (vertical) {
811             cairo_text_extents_t extents;
812             cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
813             y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
814         }
815         else
816             x_offset += info->geometry.width;
817     }
819     if (stroke)
820         cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
821     else
822         cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
824     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
825         g_free(glyphs);
827     return NR::Point(x_offset, y_offset);
829 #endif
833 unsigned int
834 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
835               SPStyle const *const style)
837     bool dirty_pattern = false;
839     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
840     if (_bitmap) return 0;
842     cairo_save(cr);
844     // this needs to be there to encounter Cairo's userspace locking semantics for set_source
845     // otherwise gradients won't be shown correctly
846     // printf("\n _last_tx:%f _last_ty:%f", _last_tx, _last_ty);
847     cairo_translate(cr, -_last_tx, -_last_ty);
849     // create pango layout and context if needed
850     if (_layout == NULL) {
851 #ifdef RENDER_WITH_PANGO_CAIRO
852         //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
853         _layout = pango_cairo_create_layout(cr);
854 #else
855         _layout = pango_layout_new((font_factory::Default())->fontContext);
856 #endif
857     }
859     // create font instance from style and use it
860     font_instance *tf = font_factory::Default()->FaceFromStyle(style);
861     if (tf == NULL) {   // do something
862         g_printf("Warning: trouble getting font_instance\n");
863         tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
864     }
865     PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
867     pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
868     pango_layout_set_font_description(_layout, adjusted);
869     pango_layout_set_text(_layout, text, -1);
871     pango_font_description_free(adjusted);
872     tf->Unref();
874 #ifdef RENDER_WITH_PANGO_CAIRO
875     pango_cairo_update_layout(cr, _layout);
876 #else
877     pango_layout_context_changed(_layout);   // is this needed?
878 #endif
880     PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
881     if (line == NULL)
882         return 0;
884 #ifndef RENDER_WITH_PANGO_CAIRO
885     // apply the selected font
886     double size;
887     PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
888     PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
889     FcPattern *fc_pattern = fc_font->font_pattern;
891     if ( style->writing_mode.set &&
892        (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
893         style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
894     {
895         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
896         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
897         dirty_pattern = true;
898     }
900     cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
901     cairo_set_font_face(cr, font_face);
903     if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
904         size = 12.0;
906     // adjust size and horizontal flip
907     cairo_matrix_t matrix;
908     cairo_get_font_matrix(cr, &matrix);
909     matrix.xx = size;
910     matrix.yy = -matrix.xx;
911     cairo_set_font_matrix(cr, &matrix);
912 #endif
914     if ( style->fill.isColor()
915          || ( style->fill.isPaintserver()
916               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
917     {
918         // set fill style
919         print_fill_style(cr, style, NULL);
921 #ifndef RENDER_WITH_PANGO_CAIRO
922         NR::Point cursor(_last_tx, _last_ty);
923         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
924             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
925             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
926         }
927 #else
928         cairo_new_path(cr);
929         // as pango has inverted origin we simulate the moveto and apply the vertical flip
930         //cairo_move_to(cr, _last_tx, _last_ty);
931         cairo_translate(cr, _last_tx, _last_ty);
932         cairo_scale(cr, 1, -1);
933         cairo_move_to(cr, 0, 0);
934         pango_cairo_show_layout_line(cr, line);
935         cairo_scale(cr, 1, -1);
936         cairo_translate(cr, -_last_tx, -_last_ty);
938 #endif
939     }
941     if (style->stroke.isColor()
942         || ( style->stroke.isPaintserver()
943               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
944     {
945         // set stroke style
946         print_stroke_style(cr, style, NULL);
948         // paint stroke
949 #ifndef RENDER_WITH_PANGO_CAIRO
950         NR::Point cursor(_last_tx, _last_ty);
951         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
952             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
953             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, true) / PANGO_SCALE;
954         }
955 #else
956         cairo_new_path(cr);
957         // as pango has inverted origin we simulate the moveto and apply the vertical flip
958         //cairo_move_to(cr, _last_tx, _last_ty);
959         cairo_translate(cr, _last_tx, _last_ty);
960         cairo_scale(cr, 1, -1);
961         cairo_move_to(cr, 0, 0);
962         pango_cairo_layout_line_path(cr, line);
963         cairo_scale(cr, 1, -1);
964         cairo_translate(cr, -_last_tx, -_last_ty);
965 #endif
966         cairo_stroke(cr);
967     }
970     cairo_restore(cr);
972 #ifndef RENDER_WITH_PANGO_CAIRO
973     cairo_font_face_destroy(font_face);
975     if (dirty_pattern) {
976         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
977         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
978     }
979 #endif
981     return 0;
984 /* Helper functions */
986 void
987 PrintCairoPDF::print_bpath(cairo_t *cr, NArtBpath const *bp)
989     cairo_new_path(cr);
990     bool closed = false;
991     while (bp->code != NR_END) {
992         switch (bp->code) {
993             case NR_MOVETO:
994                 if (closed) {
995                     cairo_close_path(cr);
996                 }
997                 closed = true;
998                 cairo_move_to(cr, bp->x3, bp->y3);
999                 break;
1000             case NR_MOVETO_OPEN:
1001                 if (closed) {
1002                     cairo_close_path(cr);
1003                 }
1004                 closed = false;
1005                 cairo_move_to(cr, bp->x3, bp->y3);
1006                 break;
1007             case NR_LINETO:
1008                 cairo_line_to(cr, bp->x3, bp->y3);
1009                 break;
1010             case NR_CURVETO:
1011                 cairo_curve_to(cr, bp->x1, bp->y1, bp->x2, bp->y2, bp->x3, bp->y3);
1012                 break;
1013             default:
1014                 break;
1015         }
1016         bp += 1;
1017     }
1018     if (closed) {
1019         cairo_close_path(cr);
1020     }
1023 static void
1024 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
1026     cairo_matrix_t matrix;
1028     cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
1029     cairo_transform(cr, &matrix);
1032 static cairo_status_t
1033 _write_callback(void *closure, const unsigned char *data, unsigned int length)
1035     size_t written;
1036     FILE *file = (FILE*)closure;
1038     written = fwrite (data, 1, length, file);
1040     if (written == length)
1041         return CAIRO_STATUS_SUCCESS;
1042     else
1043         return CAIRO_STATUS_WRITE_ERROR;
1046 bool
1047 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
1049     return ext->get_param_bool("textToPath");
1052 #include "clear-n_.h"
1054 void
1055 PrintCairoPDF::init(void)
1057     /* PDF out */
1058     (void) Inkscape::Extension::build_from_mem(
1059         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
1060         "<name>" N_("PDF Print") "</name>\n"
1061         "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1062         "<param name=\"bitmap\" type=\"boolean\">false</param>\n"
1063         "<param name=\"resolution\" type=\"string\">72</param>\n"
1064         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1065         "<param name=\"pageBoundingBox\" type=\"boolean\">true</param>\n"
1066         "<param name=\"textToPath\" type=\"boolean\">true</param>\n"
1067         "<param name=\"exportDrawing\" type=\"boolean\">false</param>\n"
1068         "<param name=\"exportCanvas\" type=\"boolean\">false</param>\n"
1069         "<param name=\"exportId\" type=\"string\"></param>\n"
1070         "<print/>\n"
1071         "</inkscape-extension>", new PrintCairoPDF());
1075 }  /* namespace Internal */
1076 }  /* namespace Extension */
1077 }  /* namespace Inkscape */
1079 /* End of GNU GPL code */
1081 #endif /* HAVE_CAIRO_PDF */
1084 /*
1085   Local Variables:
1086   mode:c++
1087   c-file-style:"stroustrup"
1088   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1089   indent-tabs-mode:nil
1090   fill-column:99
1091   End:
1092 */
1093 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :