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 #define PANGO_ENABLE_BACKEND
18 #define PANGO_ENABLE_ENGINE
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
24 #include <signal.h>
25 #include <errno.h>
27 #include <libnr/n-art-bpath.h>
29 #include <glib/gmem.h>
30 #include <gtk/gtkstock.h>
31 #include <gtk/gtkvbox.h>
32 #include <gtk/gtkframe.h>
33 #include <gtk/gtkradiobutton.h>
34 #include <gtk/gtkcombo.h>
35 #include <gtk/gtklabel.h>
36 #include <gtk/gtkentry.h>
37 #include <gtk/gtktooltips.h>
39 #include <glibmm/i18n.h>
40 #include "display/nr-arena-item.h"
41 #include "display/canvas-bpath.h"
42 #include "sp-item.h"
43 #include "style.h"
44 #include "sp-linear-gradient.h"
45 #include "sp-radial-gradient.h"
47 #include "libnrtype/font-instance.h"
48 #include "libnrtype/font-style-to-pos.h"
50 #include <unit-constants.h>
52 #include "pdf-cairo.h"
53 #include "extension/system.h"
54 #include "extension/print.h"
56 #include "io/sys.h"
58 #include "cairo.h"
59 #include "cairo-pdf.h"
60 #include "cairo-ft.h"
62 #include <pango/pangofc-fontmap.h>
64 #ifdef USE_PANGO_CAIRO
65 #include <pango/pangocairo.h>
66 #endif
68 namespace Inkscape {
69 namespace Extension {
70 namespace Internal {
72 static cairo_status_t _write_callback(void *closure, const unsigned char *data, unsigned int length);
73 static void _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0);
75 PrintCairoPDF::PrintCairoPDF() :
76 cr(NULL),
77 pdf_surface(NULL),
78 _layout(NULL),
79 _dpi(72),
80 _bitmap(false)
81 {
82 _num_alphas = 8;
83 _alpha_stack = (float*)malloc(sizeof(float) * _num_alphas);
84 }
86 PrintCairoPDF::~PrintCairoPDF(void)
87 {
88 if (cr) cairo_destroy(cr);
89 if (pdf_surface) cairo_surface_destroy(pdf_surface);
90 if (_layout) g_object_unref(_layout);
92 free(_alpha_stack);
94 /* restore default signal handling for SIGPIPE */
95 #if !defined(_WIN32) && !defined(__WIN32__)
96 (void) signal(SIGPIPE, SIG_DFL);
97 #endif
99 return;
100 }
102 unsigned int
103 PrintCairoPDF::setup(Inkscape::Extension::Print * mod)
104 {
105 static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
107 #ifdef TED
108 Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
109 #endif
111 unsigned int ret = FALSE;
113 /* Create dialog */
114 GtkTooltips *tt = gtk_tooltips_new();
115 g_object_ref((GObject *) tt);
116 gtk_object_sink((GtkObject *) tt);
118 GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
119 // SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
120 NULL,
121 (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
122 GTK_STOCK_CANCEL,
123 GTK_RESPONSE_CANCEL,
124 GTK_STOCK_PRINT,
125 GTK_RESPONSE_OK,
126 NULL);
128 gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
130 GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
131 gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
132 /* Print properties frame */
133 GtkWidget *f = gtk_frame_new(_("Print properties"));
134 gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
135 GtkWidget *vb = gtk_vbox_new(FALSE, 4);
136 gtk_container_add(GTK_CONTAINER(f), vb);
137 gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
138 /* Print type */
139 bool const p2bm = mod->get_param_bool("bitmap");
140 GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PDF operators"));
141 gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
142 _("Use PDF vector operators. The resulting image is usually smaller "
143 "in file size and can be arbitrarily scaled, but "
144 "patterns will be lost."), NULL);
145 if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
146 gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
147 rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
148 gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
149 _("Print everything as bitmap. The resulting image is usually larger "
150 "in file size and cannot be arbitrarily scaled without quality loss, "
151 "but all objects will be rendered exactly as displayed."), NULL);
152 if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
153 gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
154 /* Resolution */
155 GtkWidget *hb = gtk_hbox_new(FALSE, 4);
156 gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
157 GtkWidget *combo = gtk_combo_new();
158 gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
159 gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
160 gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
161 gtk_widget_set_size_request(combo, 64, -1);
162 gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
163 _("Preferred resolution (dots per inch) of bitmap"), NULL);
164 /* Setup strings */
165 GList *sl = NULL;
166 for (unsigned i = 0; pdr[i] != NULL; i++) {
167 sl = g_list_prepend(sl, (gpointer) pdr[i]);
168 }
169 sl = g_list_reverse(sl);
170 gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
171 g_list_free(sl);
172 if (1) {
173 gchar const *val = mod->get_param_string("resolution");
174 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
175 }
176 gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
177 GtkWidget *l = gtk_label_new(_("Resolution:"));
178 gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
180 /* Print destination frame */
181 f = gtk_frame_new(_("Print destination"));
182 gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
183 vb = gtk_vbox_new(FALSE, 4);
184 gtk_container_add(GTK_CONTAINER(f), vb);
185 gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
187 l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
188 "leave empty to use the system default printer.\n"
189 "Use '> filename' to print to file.\n"
190 "Use '| prog arg...' to pipe to a program."));
191 gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
193 GtkWidget *e = gtk_entry_new();
194 if (1) {
195 gchar const *val = mod->get_param_string("destination");
196 gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
197 ? val
198 : "" ));
199 }
200 gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
202 // pressing enter in the destination field is the same as clicking Print:
203 gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
205 gtk_widget_show_all(vbox);
207 int const response = gtk_dialog_run(GTK_DIALOG(dlg));
209 g_object_unref((GObject *) tt);
211 if (response == GTK_RESPONSE_OK) {
212 gchar const *fn;
213 char const *sstr;
215 _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
216 sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
217 _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
218 /* Arrgh, have to do something */
219 fn = gtk_entry_get_text(GTK_ENTRY(e));
220 /* skip leading whitespace, bug #1068483 */
221 while (fn && *fn==' ') { fn++; }
222 /* g_print("Printing to %s\n", fn); */
224 mod->set_param_bool("bitmap", _bitmap);
225 mod->set_param_string("resolution", (gchar *)sstr);
226 mod->set_param_string("destination", (gchar *)fn);
227 ret = TRUE;
228 }
230 gtk_widget_destroy(dlg);
232 return ret;
233 }
235 unsigned int
236 PrintCairoPDF::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
237 {
238 FILE *osf = NULL;
239 FILE *osp = NULL;
241 _alpha_ptr = 0;
242 _alpha_stack[_alpha_ptr] = 1.0;
244 gsize bytesRead = 0;
245 gsize bytesWritten = 0;
246 GError *error = NULL;
247 gchar const *utf8_fn = mod->get_param_string("destination");
248 gchar *local_fn = g_filename_from_utf8( utf8_fn,
249 -1, &bytesRead, &bytesWritten, &error);
250 gchar const *fn = local_fn;
252 /* TODO: Replace the below fprintf's with something that does the right thing whether in
253 * gui or batch mode (e.g. --print=blah). Consider throwing an exception: currently one of
254 * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
255 * return code.
256 */
257 if (fn != NULL) {
258 if (*fn == '|') {
259 fn += 1;
260 while (isspace(*fn)) fn += 1;
261 #ifndef WIN32
262 osp = popen(fn, "w");
263 #else
264 osp = _popen(fn, "w");
265 #endif
266 if (!osp) {
267 fprintf(stderr, "inkscape: popen(%s): %s\n",
268 fn, strerror(errno));
269 return 0;
270 }
271 _stream = osp;
272 } else if (*fn == '>') {
273 fn += 1;
274 while (isspace(*fn)) fn += 1;
275 Inkscape::IO::dump_fopen_call(fn, "K");
276 osf = Inkscape::IO::fopen_utf8name(fn, "w+");
277 if (!osf) {
278 fprintf(stderr, "inkscape: fopen(%s): %s\n",
279 fn, strerror(errno));
280 return 0;
281 }
282 _stream = osf;
283 } else {
284 /* put cwd stuff in here */
285 gchar *qn = ( *fn
286 ? g_strdup_printf("lpr -P %s", fn) /* FIXME: quote fn */
287 : g_strdup("lpr") );
288 #ifndef WIN32
289 osp = popen(qn, "w");
290 #else
291 osp = _popen(qn, "w");
292 #endif
293 if (!osp) {
294 fprintf(stderr, "inkscape: popen(%s): %s\n",
295 qn, strerror(errno));
296 return 0;
297 }
298 g_free(qn);
299 _stream = osp;
300 }
301 }
303 g_free(local_fn);
305 if (_stream) {
306 /* fixme: this is kinda icky */
307 #if !defined(_WIN32) && !defined(__WIN32__)
308 (void) signal(SIGPIPE, SIG_IGN);
309 #endif
310 }
312 // test output stream?
314 // width and height in pt
315 _width = sp_document_width(doc) * PT_PER_PX;
316 _height = sp_document_height(doc) * PT_PER_PX;
318 NRRect d;
319 bool pageBoundingBox;
320 pageBoundingBox = mod->get_param_bool("pageBoundingBox");
321 // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
322 if (pageBoundingBox) {
323 d.x0 = d.y0 = 0;
324 d.x1 = ceil(_width);
325 d.y1 = ceil(_height);
326 } else {
327 SPItem* doc_item = SP_ITEM(sp_document_root(doc));
328 sp_item_invoke_bbox(doc_item, &d, sp_item_i2r_affine(doc_item), TRUE);
329 // convert from px to pt
330 d.x0 *= PT_PER_PX;
331 d.x1 *= PT_PER_PX;
332 d.y0 *= PT_PER_PX;
333 d.y1 *= PT_PER_PX;
334 }
335 printf("%f %f\n", _width, _height);
337 pdf_surface = cairo_pdf_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, d.x1-d.x0, d.y1-d.y0);
338 cr = cairo_create(pdf_surface);
340 if (!_bitmap) {
341 cairo_scale(cr, PT_PER_PX, PT_PER_PX);
343 // from now on we can output px, but they will be treated as pt
344 // note that the we do not have to flip the y axis
345 // because Cairo's coordinate system is identical to Inkscape's
346 }
348 return 1;
349 }
351 unsigned int
352 PrintCairoPDF::finish(Inkscape::Extension::Print *mod)
353 {
354 if (!_stream) return 0;
355 if (_bitmap) return 0;
357 cairo_show_page(cr);
359 cairo_destroy(cr);
360 cairo_surface_destroy(pdf_surface);
361 cr = NULL;
362 pdf_surface = NULL;
364 /* Flush stream to be sure. */
365 (void) fflush(_stream);
367 /* fixme: should really use pclose for popen'd streams */
368 fclose(_stream);
369 _stream = 0;
371 return 0;
372 }
374 unsigned int
375 PrintCairoPDF::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
376 {
377 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
378 if (_bitmap) return 0;
380 cairo_save(cr);
381 _concat_transform(cr, transform->c[0], transform->c[1], transform->c[2], transform->c[3], transform->c[4], transform->c[5]);
382 // 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]);
383 // remember these to be able to undo them when outputting text
384 _last_tx = transform->c[4];
385 _last_ty = transform->c[5];
387 if (_num_alphas <= ++_alpha_ptr) {
388 _num_alphas *= 2;
389 _alpha_stack = (float*)realloc((void*)_alpha_stack, sizeof(float) * _num_alphas);
390 }
391 _alpha_stack[_alpha_ptr] = _alpha_stack[_alpha_ptr-1] * opacity;
393 return 1;
394 }
396 unsigned int
397 PrintCairoPDF::release(Inkscape::Extension::Print *mod)
398 {
399 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
400 if (_bitmap) return 0;
402 cairo_restore(cr);
403 // g_printf("release\n");
404 if (_alpha_ptr > 0)
405 _alpha_ptr--;
407 return 1;
408 }
410 unsigned int
411 PrintCairoPDF::comment(Inkscape::Extension::Print *mod, char const *comment)
412 {
413 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
414 if (_bitmap) return 0;
416 return 1;
417 }
419 cairo_pattern_t*
420 PrintCairoPDF::create_pattern_for_paint(SPPaintServer const *const paintserver, NRRect const *pbox, float alpha)
421 {
422 cairo_pattern_t *pattern = NULL;
423 bool apply_bbox2user = false;
425 if (SP_IS_LINEARGRADIENT (paintserver)) {
427 SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver);
429 sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
431 NR::Point p1 (lg->x1.computed, lg->y1.computed);
432 NR::Point p2 (lg->x2.computed, lg->y2.computed);
433 if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
434 // convert to userspace
435 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
436 p1 *= bbox2user;
437 p2 *= bbox2user;
438 }
440 // create linear gradient pattern
441 pattern = cairo_pattern_create_linear(p1[NR::X], p1[NR::Y], p2[NR::X], p2[NR::Y]);
443 // add stops
444 for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) {
445 float rgb[3];
446 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
447 cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha);
448 }
449 } else if (SP_IS_RADIALGRADIENT (paintserver)) {
451 SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver);
453 sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
455 NR::Point c (rg->cx.computed, rg->cy.computed);
456 NR::Point f (rg->fx.computed, rg->fy.computed);
457 double r = rg->r.computed;
458 if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
459 apply_bbox2user = true;
461 // create radial gradient pattern
462 pattern = cairo_pattern_create_radial(f[NR::X], f[NR::Y], 0, c[NR::X], c[NR::Y], r);
464 // add stops
465 for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) {
466 float rgb[3];
467 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
468 cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha);
469 }
470 }
472 if (pattern) {
473 SPGradient *g = SP_GRADIENT(paintserver);
475 // set extend type
476 SPGradientSpread spread = sp_gradient_get_spread(g);
477 switch (spread) {
478 case SP_GRADIENT_SPREAD_REPEAT:
479 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
480 break;
481 case SP_GRADIENT_SPREAD_REFLECT: // not supported by cairo-pdf yet
482 //cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT);
483 //break;
484 case SP_GRADIENT_SPREAD_PAD:
485 default:
486 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE); // PAD not supported by cairo-pdf yet
487 break;
488 }
490 cairo_matrix_t pattern_matrix;
491 if (g->gradientTransform_set) {
492 // apply gradient transformation
493 cairo_matrix_init(&pattern_matrix,
494 g->gradientTransform[0], g->gradientTransform[1],
495 g->gradientTransform[2], g->gradientTransform[3],
496 g->gradientTransform[4], g->gradientTransform[5]);
497 } else {
498 cairo_matrix_init_identity (&pattern_matrix);
499 }
501 if (apply_bbox2user) {
502 // convert to userspace
503 cairo_matrix_t bbox2user;
504 cairo_matrix_init (&bbox2user, pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
505 cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix);
506 }
507 cairo_matrix_invert(&pattern_matrix); // because Cairo expects a userspace->patternspace matrix
508 cairo_pattern_set_matrix(pattern, &pattern_matrix);
509 }
511 return pattern;
512 }
514 void
515 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
516 {
517 g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
518 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
519 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
521 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
522 float rgb[3];
523 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
525 float alpha = 1.0;
526 alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
527 alpha *= _alpha_stack[_alpha_ptr];
529 cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
530 } else {
531 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
532 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
534 cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_FILL_SERVER(style), pbox, 1.0);
536 if (pattern) {
537 cairo_set_source(cr, pattern);
538 cairo_pattern_destroy(pattern);
539 }
540 }
541 }
543 unsigned int
544 PrintCairoPDF::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
545 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
546 {
547 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
548 if (_bitmap) return 0;
550 if ( style->fill.type == SP_PAINT_TYPE_COLOR
551 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
552 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) ) {
554 float alpha = 1.0;
555 alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
556 if (alpha != 1.0)
557 g_printf( "fa: %f a:%f fa*a = %f\n", alpha, _alpha_stack[_alpha_ptr], alpha*_alpha_stack[_alpha_ptr]);
558 alpha *= _alpha_stack[_alpha_ptr];
560 cairo_save(cr);
562 print_fill_style(cr, style, pbox);
563 print_bpath(cr, bpath->path);
564 if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
565 cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
566 } else {
567 cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
568 }
569 if (alpha != 1.0 &&
570 style->fill.type != SP_PAINT_TYPE_COLOR) {
572 cairo_clip (cr);
573 cairo_paint_with_alpha (cr, alpha);
574 } else {
575 cairo_fill(cr);
576 }
578 cairo_restore(cr);
579 }
581 return 0;
582 }
584 void
585 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
586 {
587 float alpha = 1.0;
588 alpha *= SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
589 alpha *= _alpha_stack[_alpha_ptr];
591 if ( style->stroke.type == SP_PAINT_TYPE_COLOR ) {
592 float rgb[3];
593 sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
595 cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
596 } else if ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
597 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
599 cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
601 if (pattern) {
602 cairo_set_source(cr, pattern);
603 cairo_pattern_destroy(pattern);
604 }
605 }
607 if (style->stroke_dash.n_dash &&
608 style->stroke_dash.dash )
609 {
610 cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
611 } else {
612 cairo_set_dash(cr, NULL, 0, 0.0); // disable dashing
613 }
615 cairo_set_line_width(cr, style->stroke_width.computed);
617 // set line join type
618 cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
619 switch (style->stroke_linejoin.computed) {
620 case SP_STROKE_LINEJOIN_MITER:
621 join = CAIRO_LINE_JOIN_MITER;
622 break;
623 case SP_STROKE_LINEJOIN_ROUND:
624 join = CAIRO_LINE_JOIN_ROUND;
625 break;
626 case SP_STROKE_LINEJOIN_BEVEL:
627 join = CAIRO_LINE_JOIN_BEVEL;
628 break;
629 }
630 cairo_set_line_join(cr, join);
632 // set line cap type
633 cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
634 switch (style->stroke_linecap.computed) {
635 case SP_STROKE_LINECAP_BUTT:
636 cap = CAIRO_LINE_CAP_BUTT;
637 break;
638 case SP_STROKE_LINECAP_ROUND:
639 cap = CAIRO_LINE_CAP_ROUND;
640 break;
641 case SP_STROKE_LINECAP_SQUARE:
642 cap = CAIRO_LINE_CAP_SQUARE;
643 break;
644 }
645 cairo_set_line_cap(cr, cap);
646 cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
647 }
649 unsigned int
650 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
651 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
652 {
653 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
654 if (_bitmap) return 0;
656 if ( style->stroke.type == SP_PAINT_TYPE_COLOR ||
657 ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
658 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
660 cairo_save(cr);
662 print_stroke_style(cr, style, pbox);
663 print_bpath(cr, bpath->path);
664 cairo_stroke(cr);
666 cairo_restore(cr);
667 }
669 return 0;
670 }
672 unsigned int
673 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
674 NRMatrix const *transform, SPStyle const *style)
675 {
676 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
677 if (_bitmap) return 0;
679 guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
680 if (!px_rgba) return 0;
682 float alpha = _alpha_stack[_alpha_ptr];
684 // make a copy of the original pixbuf with premultiplied alpha
685 // if we pass the original pixbuf it will get messed up
686 for (unsigned i = 0; i < h; i++) {
687 for (unsigned j = 0; j < w; j++) {
688 guchar const *src = px + i * rs + j * 4;
689 guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
690 guchar r, g, b, alpha_dst;
692 // calculate opacity-modified alpha
693 alpha_dst = src[3];
694 if (alpha != 1.0)
695 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
697 // premul alpha (needed because this will be undone by cairo-pdf)
698 r = src[0]*alpha_dst/255;
699 g = src[1]*alpha_dst/255;
700 b = src[2]*alpha_dst/255;
702 *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
703 }
704 }
706 cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
707 if (cairo_surface_status(image_surface)) {
708 g_printf("%s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
709 return 0;
710 }
712 cairo_save(cr);
714 // scaling by width & height is not needed because it will be done by cairo-pdf
715 // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
716 cairo_matrix_t matrix;
717 cairo_matrix_init(&matrix,
718 transform->c[0]/w, transform->c[1],
719 transform->c[2], -transform->c[3]/h,
720 transform->c[4], transform->c[5] + transform->c[3]);
721 cairo_transform(cr, &matrix);
723 cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
724 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
726 cairo_set_source(cr, pattern);
727 cairo_pattern_destroy(pattern);
729 // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
730 cairo_new_path(cr);
731 cairo_rectangle(cr, 0, 0, w, h);
732 cairo_clip(cr);
734 cairo_paint(cr);
736 cairo_restore(cr);
738 cairo_surface_destroy(image_surface);
739 g_free(px_rgba);
741 return 0;
742 }
744 #define GLYPH_ARRAY_SIZE 64
746 NR::Point
747 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
748 bool vertical, bool stroke)
749 {
750 cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
751 cairo_glyph_t *glyphs = glyph_array;
752 if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
753 glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
755 PangoGlyphUnit x_offset = 0, y_offset = 0;
756 PangoGlyphInfo *info;
757 int num_invalid_glyphs = 0;
758 for (gint i = 0; i < glyph_string->num_glyphs; i++) {
759 info = &glyph_string->glyphs[i];
760 // skip empty or unknown glyphs
761 if (info->glyph == PANGO_GLYPH_EMPTY || info->glyph & PANGO_GLYPH_UNKNOWN_FLAG) {
762 num_invalid_glyphs++;
763 continue;
764 }
765 glyphs[i - num_invalid_glyphs].index = info->glyph;
766 glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
767 glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
769 if (vertical) {
770 cairo_text_extents_t extents;
771 cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
772 y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
773 }
774 else
775 x_offset += info->geometry.width;
776 }
778 if (stroke)
779 cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
780 else
781 cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
783 if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
784 g_free(glyphs);
786 return NR::Point(x_offset, y_offset);
787 }
789 unsigned int
790 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
791 SPStyle const *const style)
792 {
793 bool dirty_pattern = false;
795 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
796 if (_bitmap) return 0;
798 cairo_save(cr);
800 // this needs to be there to encounter Cairo's userspace locking semantics for set_source
801 // otherwise gradients won't be shown correctly
802 cairo_translate(cr, -_last_tx, -_last_ty);
804 // create pango layout and context if needed
805 if (_layout == NULL) {
806 #ifdef USE_PANGO_CAIRO
807 //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
808 _layout = pango_cairo_create_layout(cr);
809 #else
810 _layout = pango_layout_new((font_factory::Default())->fontContext);
811 #endif
812 }
814 // create font instance from style and use it
815 font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
816 if (tf == NULL) { // do something
817 g_printf("Warning: trouble getting font_instance\n");
818 tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
819 }
820 PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
822 pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
823 pango_layout_set_font_description(_layout, adjusted);
824 pango_layout_set_text(_layout, text, -1);
826 pango_font_description_free(adjusted);
827 tf->Unref();
829 #ifdef USE_PANGO_CAIRO
830 pango_cairo_update_layout(cr, _layout);
831 #else
832 pango_layout_context_changed(_layout); // is this needed?
833 #endif
835 PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
836 if (line == NULL)
837 return 0;
839 #ifndef USE_PANGO_CAIRO
840 // apply the selected font
841 double size;
842 PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
843 PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
844 FcPattern *fc_pattern = fc_font->font_pattern;
846 if ( style->writing_mode.set &&
847 (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
848 style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
849 {
850 FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
851 FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
852 dirty_pattern = true;
853 }
855 cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
856 cairo_set_font_face(cr, font_face);
858 if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
859 size = 12.0;
861 // adjust size and horizontal flip
862 cairo_matrix_t matrix;
863 cairo_get_font_matrix(cr, &matrix);
864 matrix.xx = size;
865 matrix.yy = -matrix.xx;
866 cairo_set_font_matrix(cr, &matrix);
867 #endif
869 if ( style->fill.type == SP_PAINT_TYPE_COLOR
870 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
871 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
872 {
873 // set fill style
874 print_fill_style(cr, style, NULL);
876 #ifndef USE_PANGO_CAIRO
877 NR::Point cursor(_last_tx, _last_ty);
878 for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
879 PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
880 cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
881 }
882 #else
883 cairo_new_path(cr);
884 cairo_move_to(cr, _last_tx, _last_ty);
885 pango_cairo_show_layout_line(cr, line);
886 #endif
887 }
889 if (style->stroke.type == SP_PAINT_TYPE_COLOR
890 || ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
891 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
892 {
893 // set stroke style
894 print_stroke_style(cr, style, NULL);
896 // paint stroke
897 #ifndef USE_PANGO_CAIRO
898 NR::Point cursor(_last_tx, _last_ty);
899 for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
900 PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
901 cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, true) / PANGO_SCALE;
902 }
903 #else
904 cairo_new_path(cr);
905 cairo_move_to(cr, _last_tx, _last_ty);
906 pango_cairo_layout_line_path(cr, line);
907 #endif
908 cairo_stroke(cr);
909 }
911 cairo_font_face_destroy(font_face);
913 cairo_restore(cr);
915 #ifndef USE_PANGO_CAIRO
916 if (dirty_pattern) {
917 FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
918 FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
919 }
920 #endif
921 tf->Unref();
923 return 0;
924 }
926 /* Helper functions */
928 void
929 PrintCairoPDF::print_bpath(cairo_t *cr, NArtBpath const *bp)
930 {
931 cairo_new_path(cr);
932 bool closed = false;
933 while (bp->code != NR_END) {
934 switch (bp->code) {
935 case NR_MOVETO:
936 if (closed) {
937 cairo_close_path(cr);
938 }
939 closed = true;
940 cairo_move_to(cr, bp->x3, bp->y3);
941 break;
942 case NR_MOVETO_OPEN:
943 if (closed) {
944 cairo_close_path(cr);
945 }
946 closed = false;
947 cairo_move_to(cr, bp->x3, bp->y3);
948 break;
949 case NR_LINETO:
950 cairo_line_to(cr, bp->x3, bp->y3);
951 break;
952 case NR_CURVETO:
953 cairo_curve_to(cr, bp->x1, bp->y1, bp->x2, bp->y2, bp->x3, bp->y3);
954 break;
955 default:
956 break;
957 }
958 bp += 1;
959 }
960 if (closed) {
961 cairo_close_path(cr);
962 }
963 }
965 static void
966 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
967 {
968 cairo_matrix_t matrix;
970 cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
971 cairo_transform(cr, &matrix);
972 }
974 static cairo_status_t
975 _write_callback(void *closure, const unsigned char *data, unsigned int length)
976 {
977 size_t written;
978 FILE *file = (FILE*)closure;
980 written = fwrite (data, 1, length, file);
982 if (written == length)
983 return CAIRO_STATUS_SUCCESS;
984 else
985 return CAIRO_STATUS_WRITE_ERROR;
986 }
988 bool
989 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
990 {
991 return ext->get_param_bool("textToPath");
992 }
994 #include "clear-n_.h"
996 void
997 PrintCairoPDF::init(void)
998 {
999 /* PDF out */
1000 (void) Inkscape::Extension::build_from_mem(
1001 "<inkscape-extension>\n"
1002 "<name>" N_("PDF Print") "</name>\n"
1003 "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1004 "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1005 "<param name=\"resolution\" type=\"string\">72</param>\n"
1006 "<param name=\"destination\" type=\"string\">| lp</param>\n"
1007 "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1008 "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1009 "<print/>\n"
1010 "</inkscape-extension>", new PrintCairoPDF());
1011 }
1014 } /* namespace Internal */
1015 } /* namespace Extension */
1016 } /* namespace Inkscape */
1018 /* End of GNU GPL code */
1021 /*
1022 Local Variables:
1023 mode:c++
1024 c-file-style:"stroustrup"
1025 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1026 indent-tabs-mode:nil
1027 fill-column:99
1028 End:
1029 */
1030 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :