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