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;
105 }
107 unsigned int
108 PrintCairoPDF::setup(Inkscape::Extension::Print * mod)
109 {
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;
238 }
240 unsigned int
241 PrintCairoPDF::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
242 {
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 SPItem* doc_item = SP_ITEM(sp_document_root(doc));
333 sp_item_invoke_bbox(doc_item, &d, sp_item_i2r_affine(doc_item), TRUE);
334 // convert from px to pt
335 d.x0 *= PT_PER_PX;
336 d.x1 *= PT_PER_PX;
337 d.y0 *= PT_PER_PX;
338 d.y1 *= PT_PER_PX;
339 }
340 printf("%f %f\n", _width, _height);
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);
345 if (!_bitmap) {
346 cairo_scale(cr, PT_PER_PX, PT_PER_PX);
348 // from now on we can output px, but they will be treated as pt
349 // note that the we do not have to flip the y axis
350 // because Cairo's coordinate system is identical to Inkscape's
351 }
353 return 1;
354 }
356 unsigned int
357 PrintCairoPDF::finish(Inkscape::Extension::Print *mod)
358 {
359 if (!_stream) return 0;
360 if (_bitmap) return 0;
362 cairo_show_page(cr);
364 cairo_destroy(cr);
365 cairo_surface_destroy(pdf_surface);
366 cr = NULL;
367 pdf_surface = NULL;
369 /* Flush stream to be sure. */
370 (void) fflush(_stream);
372 /* fixme: should really use pclose for popen'd streams */
373 fclose(_stream);
374 _stream = 0;
376 return 1;
377 }
379 unsigned int
380 PrintCairoPDF::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
381 {
382 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
383 if (_bitmap) return 0;
385 cairo_save(cr);
386 _concat_transform(cr, transform->c[0], transform->c[1], transform->c[2], transform->c[3], transform->c[4], transform->c[5]);
387 // g_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]);
388 // remember these to be able to undo them when outputting text
389 _last_tx = transform->c[4];
390 _last_ty = transform->c[5];
392 float new_opacity = _alpha_stack.back() * opacity;
393 _alpha_stack.push_back(new_opacity);
395 return 1;
396 }
398 unsigned int
399 PrintCairoPDF::release(Inkscape::Extension::Print *mod)
400 {
401 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
402 if (_bitmap) return 0;
404 cairo_restore(cr);
405 // g_printf("release\n");
406 _alpha_stack.pop_back();
407 g_assert(_alpha_stack.size() > 0);
409 return 1;
410 }
412 unsigned int
413 PrintCairoPDF::comment(Inkscape::Extension::Print *mod, char const *comment)
414 {
415 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
416 if (_bitmap) return 0;
418 return 1;
419 }
421 cairo_pattern_t*
422 PrintCairoPDF::create_pattern_for_paint(SPPaintServer const *const paintserver, NRRect const *pbox, float alpha)
423 {
424 cairo_pattern_t *pattern = NULL;
425 bool apply_bbox2user = false;
427 if (SP_IS_LINEARGRADIENT (paintserver)) {
429 SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver);
431 sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
433 NR::Point p1 (lg->x1.computed, lg->y1.computed);
434 NR::Point p2 (lg->x2.computed, lg->y2.computed);
435 if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
436 // convert to userspace
437 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
438 p1 *= bbox2user;
439 p2 *= bbox2user;
440 }
442 // create linear gradient pattern
443 pattern = cairo_pattern_create_linear(p1[NR::X], p1[NR::Y], p2[NR::X], p2[NR::Y]);
445 // add stops
446 for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) {
447 float rgb[3];
448 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
449 cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha);
450 }
451 } else if (SP_IS_RADIALGRADIENT (paintserver)) {
453 SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver);
455 sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
457 NR::Point c (rg->cx.computed, rg->cy.computed);
458 NR::Point f (rg->fx.computed, rg->fy.computed);
459 double r = rg->r.computed;
461 NR::Coord const df = hypot(f[NR::X] - c[NR::X], f[NR::Y] - c[NR::Y]);
462 if (df >= r) {
463 f[NR::X] = c[NR::X] + (f[NR::X] - c[NR::X] ) * r / (float) df;
464 f[NR::Y] = c[NR::Y] + (f[NR::Y] - c[NR::Y] ) * r / (float) df;
465 }
467 if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
468 apply_bbox2user = true;
470 // create radial gradient pattern
471 pattern = cairo_pattern_create_radial(f[NR::X], f[NR::Y], 0, c[NR::X], c[NR::Y], r);
473 // add stops
474 for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) {
475 float rgb[3];
476 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
477 cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha);
478 }
479 }
481 if (pattern) {
482 SPGradient *g = SP_GRADIENT(paintserver);
484 // set extend type
485 SPGradientSpread spread = sp_gradient_get_spread(g);
486 switch (spread) {
487 case SP_GRADIENT_SPREAD_REPEAT:
488 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
489 break;
490 case SP_GRADIENT_SPREAD_REFLECT: // not supported by cairo-pdf yet
491 //cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT);
492 //break;
493 case SP_GRADIENT_SPREAD_PAD:
494 default:
495 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE); // PAD not supported by cairo-pdf yet
496 break;
497 }
499 cairo_matrix_t pattern_matrix;
500 if (g->gradientTransform_set) {
501 // apply gradient transformation
502 cairo_matrix_init(&pattern_matrix,
503 g->gradientTransform[0], g->gradientTransform[1],
504 g->gradientTransform[2], g->gradientTransform[3],
505 g->gradientTransform[4], g->gradientTransform[5]);
506 } else {
507 cairo_matrix_init_identity (&pattern_matrix);
508 }
510 if (apply_bbox2user) {
511 // convert to userspace
512 cairo_matrix_t bbox2user;
513 cairo_matrix_init (&bbox2user, pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
514 cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix);
515 }
516 cairo_matrix_invert(&pattern_matrix); // because Cairo expects a userspace->patternspace matrix
517 cairo_pattern_set_matrix(pattern, &pattern_matrix);
518 }
520 return pattern;
521 }
523 void
524 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
525 {
526 g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
527 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
528 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
530 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
531 float rgb[3];
532 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
534 float alpha = 1.0;
535 alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
536 alpha *= _alpha_stack.back();
538 cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
539 } else {
540 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
541 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
543 cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_FILL_SERVER(style), pbox, 1.0);
545 if (pattern) {
546 cairo_set_source(cr, pattern);
547 cairo_pattern_destroy(pattern);
548 }
549 }
550 }
552 unsigned int
553 PrintCairoPDF::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
554 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
555 {
556 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
557 if (_bitmap) return 0;
559 if ( style->fill.type == SP_PAINT_TYPE_COLOR
560 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
561 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) ) {
563 float alpha = 1.0;
564 alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
565 alpha *= _alpha_stack.back();
567 cairo_save(cr);
569 print_fill_style(cr, style, pbox);
570 print_bpath(cr, bpath->path);
571 if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
572 cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
573 } else {
574 cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
575 }
576 if (alpha != 1.0 &&
577 style->fill.type != SP_PAINT_TYPE_COLOR) {
579 cairo_clip (cr);
580 cairo_paint_with_alpha (cr, alpha);
581 } else {
582 cairo_fill(cr);
583 }
585 cairo_restore(cr);
586 }
588 return 0;
589 }
591 void
592 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
593 {
594 float alpha = 1.0;
595 alpha *= SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
596 alpha *= _alpha_stack.back();
598 if ( style->stroke.type == SP_PAINT_TYPE_COLOR ) {
599 float rgb[3];
600 sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
602 cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
603 } else if ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
604 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
606 cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
608 if (pattern) {
609 cairo_set_source(cr, pattern);
610 cairo_pattern_destroy(pattern);
611 }
612 }
614 if (style->stroke_dash.n_dash &&
615 style->stroke_dash.dash )
616 {
617 cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
618 } else {
619 cairo_set_dash(cr, NULL, 0, 0.0); // disable dashing
620 }
622 cairo_set_line_width(cr, style->stroke_width.computed);
624 // set line join type
625 cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
626 switch (style->stroke_linejoin.computed) {
627 case SP_STROKE_LINEJOIN_MITER:
628 join = CAIRO_LINE_JOIN_MITER;
629 break;
630 case SP_STROKE_LINEJOIN_ROUND:
631 join = CAIRO_LINE_JOIN_ROUND;
632 break;
633 case SP_STROKE_LINEJOIN_BEVEL:
634 join = CAIRO_LINE_JOIN_BEVEL;
635 break;
636 }
637 cairo_set_line_join(cr, join);
639 // set line cap type
640 cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
641 switch (style->stroke_linecap.computed) {
642 case SP_STROKE_LINECAP_BUTT:
643 cap = CAIRO_LINE_CAP_BUTT;
644 break;
645 case SP_STROKE_LINECAP_ROUND:
646 cap = CAIRO_LINE_CAP_ROUND;
647 break;
648 case SP_STROKE_LINECAP_SQUARE:
649 cap = CAIRO_LINE_CAP_SQUARE;
650 break;
651 }
652 cairo_set_line_cap(cr, cap);
653 cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
654 }
656 unsigned int
657 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
658 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
659 {
660 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
661 if (_bitmap) return 0;
663 if ( style->stroke.type == SP_PAINT_TYPE_COLOR ||
664 ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
665 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
667 cairo_save(cr);
669 print_stroke_style(cr, style, pbox);
670 print_bpath(cr, bpath->path);
671 cairo_stroke(cr);
673 cairo_restore(cr);
674 }
676 return 0;
677 }
679 unsigned int
680 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
681 NRMatrix const *transform, SPStyle const *style)
682 {
683 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
684 if (_bitmap) return 0;
686 guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
687 if (!px_rgba) return 0;
689 float alpha = _alpha_stack.back();
691 // make a copy of the original pixbuf with premultiplied alpha
692 // if we pass the original pixbuf it will get messed up
693 for (unsigned i = 0; i < h; i++) {
694 for (unsigned j = 0; j < w; j++) {
695 guchar const *src = px + i * rs + j * 4;
696 guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
697 guchar r, g, b, alpha_dst;
699 // calculate opacity-modified alpha
700 alpha_dst = src[3];
701 if (alpha != 1.0)
702 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
704 // premul alpha (needed because this will be undone by cairo-pdf)
705 r = src[0]*alpha_dst/255;
706 g = src[1]*alpha_dst/255;
707 b = src[2]*alpha_dst/255;
709 *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
710 }
711 }
713 cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
714 if (cairo_surface_status(image_surface)) {
715 g_printf("Error: %s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
716 return 0;
717 }
719 cairo_save(cr);
721 // scaling by width & height is not needed because it will be done by cairo-pdf
722 // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
723 cairo_matrix_t matrix;
724 cairo_matrix_init(&matrix,
725 transform->c[0]/w, transform->c[1],
726 transform->c[2], -transform->c[3]/h,
727 transform->c[4], transform->c[5] + transform->c[3]);
728 cairo_transform(cr, &matrix);
730 cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
731 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
733 cairo_set_source(cr, pattern);
734 cairo_pattern_destroy(pattern);
736 // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
737 cairo_new_path(cr);
738 cairo_rectangle(cr, 0, 0, w, h);
739 cairo_clip(cr);
741 cairo_paint(cr);
743 cairo_restore(cr);
745 cairo_surface_destroy(image_surface);
746 g_free(px_rgba);
748 return 0;
749 }
751 #define GLYPH_ARRAY_SIZE 64
753 #ifndef RENDER_WITH_PANGO_CAIRO
755 NR::Point
756 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
757 bool vertical, bool stroke)
758 {
759 cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
760 cairo_glyph_t *glyphs = glyph_array;
761 if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
762 glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
764 PangoGlyphUnit x_offset = 0, y_offset = 0;
765 PangoGlyphInfo *info;
766 int num_invalid_glyphs = 0;
767 for (gint i = 0; i < glyph_string->num_glyphs; i++) {
768 info = &glyph_string->glyphs[i];
769 // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) or have
770 // the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set
771 if (info->glyph == 0x0FFFFFFF || info->glyph & 0x10000000) {
772 num_invalid_glyphs++;
773 continue;
774 }
776 glyphs[i - num_invalid_glyphs].index = info->glyph;
777 glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
778 glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
780 if (vertical) {
781 cairo_text_extents_t extents;
782 cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
783 y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
784 }
785 else
786 x_offset += info->geometry.width;
787 }
789 if (stroke)
790 cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
791 else
792 cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
794 if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
795 g_free(glyphs);
797 return NR::Point(x_offset, y_offset);
798 }
799 #endif
803 unsigned int
804 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
805 SPStyle const *const style)
806 {
807 bool dirty_pattern = false;
809 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
810 if (_bitmap) return 0;
812 cairo_save(cr);
814 // this needs to be there to encounter Cairo's userspace locking semantics for set_source
815 // otherwise gradients won't be shown correctly
816 cairo_translate(cr, -_last_tx, -_last_ty);
818 // create pango layout and context if needed
819 if (_layout == NULL) {
820 #ifdef RENDER_WITH_PANGO_CAIRO
821 //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
822 _layout = pango_cairo_create_layout(cr);
823 #else
824 _layout = pango_layout_new((font_factory::Default())->fontContext);
825 #endif
826 }
828 // create font instance from style and use it
829 font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
830 if (tf == NULL) { // do something
831 g_printf("Warning: trouble getting font_instance\n");
832 tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
833 }
834 PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
836 pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
837 pango_layout_set_font_description(_layout, adjusted);
838 pango_layout_set_text(_layout, text, -1);
840 pango_font_description_free(adjusted);
841 tf->Unref();
843 #ifdef RENDER_WITH_PANGO_CAIRO
844 pango_cairo_update_layout(cr, _layout);
845 #else
846 pango_layout_context_changed(_layout); // is this needed?
847 #endif
849 PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
850 if (line == NULL)
851 return 0;
853 #ifndef RENDER_WITH_PANGO_CAIRO
854 // apply the selected font
855 double size;
856 PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
857 PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
858 FcPattern *fc_pattern = fc_font->font_pattern;
860 if ( style->writing_mode.set &&
861 (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
862 style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
863 {
864 FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
865 FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
866 dirty_pattern = true;
867 }
869 cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
870 cairo_set_font_face(cr, font_face);
872 if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
873 size = 12.0;
875 // adjust size and horizontal flip
876 cairo_matrix_t matrix;
877 cairo_get_font_matrix(cr, &matrix);
878 matrix.xx = size;
879 matrix.yy = -matrix.xx;
880 cairo_set_font_matrix(cr, &matrix);
881 #endif
883 if ( style->fill.type == SP_PAINT_TYPE_COLOR
884 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
885 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
886 {
887 // set fill style
888 print_fill_style(cr, style, NULL);
890 #ifndef RENDER_WITH_PANGO_CAIRO
891 NR::Point cursor(_last_tx, _last_ty);
892 for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
893 PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
894 cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
895 }
896 #else
897 cairo_new_path(cr);
898 cairo_move_to(cr, _last_tx, _last_ty);
899 pango_cairo_show_layout_line(cr, line);
900 #endif
901 }
903 if (style->stroke.type == SP_PAINT_TYPE_COLOR
904 || ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
905 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
906 {
907 // set stroke style
908 print_stroke_style(cr, style, NULL);
910 // paint stroke
911 #ifndef RENDER_WITH_PANGO_CAIRO
912 NR::Point cursor(_last_tx, _last_ty);
913 for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
914 PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
915 cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, true) / PANGO_SCALE;
916 }
917 #else
918 cairo_new_path(cr);
919 cairo_move_to(cr, _last_tx, _last_ty);
920 pango_cairo_layout_line_path(cr, line);
921 #endif
922 cairo_stroke(cr);
923 }
926 cairo_restore(cr);
928 #ifndef RENDER_WITH_PANGO_CAIRO
929 cairo_font_face_destroy(font_face);
931 if (dirty_pattern) {
932 FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
933 FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
934 }
935 #endif
936 tf->Unref();
938 return 0;
939 }
941 /* Helper functions */
943 void
944 PrintCairoPDF::print_bpath(cairo_t *cr, NArtBpath const *bp)
945 {
946 cairo_new_path(cr);
947 bool closed = false;
948 while (bp->code != NR_END) {
949 switch (bp->code) {
950 case NR_MOVETO:
951 if (closed) {
952 cairo_close_path(cr);
953 }
954 closed = true;
955 cairo_move_to(cr, bp->x3, bp->y3);
956 break;
957 case NR_MOVETO_OPEN:
958 if (closed) {
959 cairo_close_path(cr);
960 }
961 closed = false;
962 cairo_move_to(cr, bp->x3, bp->y3);
963 break;
964 case NR_LINETO:
965 cairo_line_to(cr, bp->x3, bp->y3);
966 break;
967 case NR_CURVETO:
968 cairo_curve_to(cr, bp->x1, bp->y1, bp->x2, bp->y2, bp->x3, bp->y3);
969 break;
970 default:
971 break;
972 }
973 bp += 1;
974 }
975 if (closed) {
976 cairo_close_path(cr);
977 }
978 }
980 static void
981 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
982 {
983 cairo_matrix_t matrix;
985 cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
986 cairo_transform(cr, &matrix);
987 }
989 static cairo_status_t
990 _write_callback(void *closure, const unsigned char *data, unsigned int length)
991 {
992 size_t written;
993 FILE *file = (FILE*)closure;
995 written = fwrite (data, 1, length, file);
997 if (written == length)
998 return CAIRO_STATUS_SUCCESS;
999 else
1000 return CAIRO_STATUS_WRITE_ERROR;
1001 }
1003 bool
1004 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
1005 {
1006 return ext->get_param_bool("textToPath");
1007 }
1009 #include "clear-n_.h"
1011 void
1012 PrintCairoPDF::init(void)
1013 {
1014 /* PDF out */
1015 (void) Inkscape::Extension::build_from_mem(
1016 "<inkscape-extension>\n"
1017 "<name>" N_("PDF Print") "</name>\n"
1018 "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1019 "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1020 "<param name=\"resolution\" type=\"string\">72</param>\n"
1021 "<param name=\"destination\" type=\"string\">| lp</param>\n"
1022 "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1023 "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1024 "<print/>\n"
1025 "</inkscape-extension>", new PrintCairoPDF());
1026 }
1029 } /* namespace Internal */
1030 } /* namespace Extension */
1031 } /* namespace Inkscape */
1033 /* End of GNU GPL code */
1035 #endif /* HAVE_CAIRO_PDF */
1038 /*
1039 Local Variables:
1040 mode:c++
1041 c-file-style:"stroustrup"
1042 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1043 indent-tabs-mode:nil
1044 fill-column:99
1045 End:
1046 */
1047 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :