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