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/pango.h>
69 #include <pango/pangofc-fontmap.h>
71 #ifdef RENDER_WITH_PANGO_CAIRO
72 #include <pango/pangocairo.h>
73 #endif
75 namespace Inkscape {
76 namespace Extension {
77 namespace Internal {
79 static cairo_status_t _write_callback(void *closure, const unsigned char *data, unsigned int length);
80 static void _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0);
82 PrintCairoPDF::PrintCairoPDF() :
83 cr(NULL),
84 pdf_surface(NULL),
85 _layout(NULL),
86 _dpi(72),
87 _bitmap(false)
88 {
89 _num_alphas = 8;
90 _alpha_stack = (float*)malloc(sizeof(float) * _num_alphas);
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 free(_alpha_stack);
101 /* restore default signal handling for SIGPIPE */
102 #if !defined(_WIN32) && !defined(__WIN32__)
103 (void) signal(SIGPIPE, SIG_DFL);
104 #endif
106 return;
107 }
109 unsigned int
110 PrintCairoPDF::setup(Inkscape::Extension::Print * mod)
111 {
112 static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
114 #ifdef TED
115 Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
116 #endif
118 unsigned int ret = FALSE;
120 /* Create dialog */
121 GtkTooltips *tt = gtk_tooltips_new();
122 g_object_ref((GObject *) tt);
123 gtk_object_sink((GtkObject *) tt);
125 GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
126 // SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
127 NULL,
128 (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
129 GTK_STOCK_CANCEL,
130 GTK_RESPONSE_CANCEL,
131 GTK_STOCK_PRINT,
132 GTK_RESPONSE_OK,
133 NULL);
135 gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
137 GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
138 gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
139 /* Print properties frame */
140 GtkWidget *f = gtk_frame_new(_("Print properties"));
141 gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
142 GtkWidget *vb = gtk_vbox_new(FALSE, 4);
143 gtk_container_add(GTK_CONTAINER(f), vb);
144 gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
145 /* Print type */
146 bool const p2bm = mod->get_param_bool("bitmap");
147 GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PDF operators"));
148 gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
149 _("Use PDF vector operators. The resulting image is usually smaller "
150 "in file size and can be arbitrarily scaled, but "
151 "patterns will be lost."), 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 rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
155 gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
156 _("Print everything as bitmap. The resulting image is usually larger "
157 "in file size and cannot be arbitrarily scaled without quality loss, "
158 "but all objects will be rendered exactly as displayed."), NULL);
159 if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
160 gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
161 /* Resolution */
162 GtkWidget *hb = gtk_hbox_new(FALSE, 4);
163 gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
164 GtkWidget *combo = gtk_combo_new();
165 gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
166 gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
167 gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
168 gtk_widget_set_size_request(combo, 64, -1);
169 gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
170 _("Preferred resolution (dots per inch) of bitmap"), NULL);
171 /* Setup strings */
172 GList *sl = NULL;
173 for (unsigned i = 0; pdr[i] != NULL; i++) {
174 sl = g_list_prepend(sl, (gpointer) pdr[i]);
175 }
176 sl = g_list_reverse(sl);
177 gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
178 g_list_free(sl);
179 if (1) {
180 gchar const *val = mod->get_param_string("resolution");
181 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
182 }
183 gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
184 GtkWidget *l = gtk_label_new(_("Resolution:"));
185 gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
187 /* Print destination frame */
188 f = gtk_frame_new(_("Print destination"));
189 gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
190 vb = gtk_vbox_new(FALSE, 4);
191 gtk_container_add(GTK_CONTAINER(f), vb);
192 gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
194 l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
195 "leave empty to use the system default printer.\n"
196 "Use '> filename' to print to file.\n"
197 "Use '| prog arg...' to pipe to a program."));
198 gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
200 GtkWidget *e = gtk_entry_new();
201 if (1) {
202 gchar const *val = mod->get_param_string("destination");
203 gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
204 ? val
205 : "" ));
206 }
207 gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
209 // pressing enter in the destination field is the same as clicking Print:
210 gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
212 gtk_widget_show_all(vbox);
214 int const response = gtk_dialog_run(GTK_DIALOG(dlg));
216 g_object_unref((GObject *) tt);
218 if (response == GTK_RESPONSE_OK) {
219 gchar const *fn;
220 char const *sstr;
222 _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
223 sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
224 _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
225 /* Arrgh, have to do something */
226 fn = gtk_entry_get_text(GTK_ENTRY(e));
227 /* skip leading whitespace, bug #1068483 */
228 while (fn && *fn==' ') { fn++; }
229 /* g_print("Printing to %s\n", fn); */
231 mod->set_param_bool("bitmap", _bitmap);
232 mod->set_param_string("resolution", (gchar *)sstr);
233 mod->set_param_string("destination", (gchar *)fn);
234 ret = TRUE;
235 }
237 gtk_widget_destroy(dlg);
239 return ret;
240 }
242 unsigned int
243 PrintCairoPDF::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
244 {
245 FILE *osf = NULL;
246 FILE *osp = NULL;
248 _alpha_ptr = 0;
249 _alpha_stack[_alpha_ptr] = 1.0;
251 gsize bytesRead = 0;
252 gsize bytesWritten = 0;
253 GError *error = NULL;
254 gchar const *utf8_fn = mod->get_param_string("destination");
255 gchar *local_fn = g_filename_from_utf8( utf8_fn,
256 -1, &bytesRead, &bytesWritten, &error);
257 gchar const *fn = local_fn;
259 /* TODO: Replace the below fprintf's with something that does the right thing whether in
260 * gui or batch mode (e.g. --print=blah). Consider throwing an exception: currently one of
261 * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
262 * return code.
263 */
264 if (fn != NULL) {
265 if (*fn == '|') {
266 fn += 1;
267 while (isspace(*fn)) fn += 1;
268 #ifndef WIN32
269 osp = popen(fn, "w");
270 #else
271 osp = _popen(fn, "w");
272 #endif
273 if (!osp) {
274 fprintf(stderr, "inkscape: popen(%s): %s\n",
275 fn, strerror(errno));
276 return 0;
277 }
278 _stream = osp;
279 } else if (*fn == '>') {
280 fn += 1;
281 while (isspace(*fn)) fn += 1;
282 Inkscape::IO::dump_fopen_call(fn, "K");
283 osf = Inkscape::IO::fopen_utf8name(fn, "w+");
284 if (!osf) {
285 fprintf(stderr, "inkscape: fopen(%s): %s\n",
286 fn, strerror(errno));
287 return 0;
288 }
289 _stream = osf;
290 } else {
291 /* put cwd stuff in here */
292 gchar *qn = ( *fn
293 ? g_strdup_printf("lpr -P %s", fn) /* FIXME: quote fn */
294 : g_strdup("lpr") );
295 #ifndef WIN32
296 osp = popen(qn, "w");
297 #else
298 osp = _popen(qn, "w");
299 #endif
300 if (!osp) {
301 fprintf(stderr, "inkscape: popen(%s): %s\n",
302 qn, strerror(errno));
303 return 0;
304 }
305 g_free(qn);
306 _stream = osp;
307 }
308 }
310 g_free(local_fn);
312 if (_stream) {
313 /* fixme: this is kinda icky */
314 #if !defined(_WIN32) && !defined(__WIN32__)
315 (void) signal(SIGPIPE, SIG_IGN);
316 #endif
317 }
319 // test output stream?
321 // width and height in pt
322 _width = sp_document_width(doc) * PT_PER_PX;
323 _height = sp_document_height(doc) * PT_PER_PX;
325 NRRect d;
326 bool pageBoundingBox;
327 pageBoundingBox = mod->get_param_bool("pageBoundingBox");
328 // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
329 if (pageBoundingBox) {
330 d.x0 = d.y0 = 0;
331 d.x1 = ceil(_width);
332 d.y1 = ceil(_height);
333 } else {
334 SPItem* doc_item = SP_ITEM(sp_document_root(doc));
335 sp_item_invoke_bbox(doc_item, &d, sp_item_i2r_affine(doc_item), TRUE);
336 // convert from px to pt
337 d.x0 *= PT_PER_PX;
338 d.x1 *= PT_PER_PX;
339 d.y0 *= PT_PER_PX;
340 d.y1 *= PT_PER_PX;
341 }
342 printf("%f %f\n", _width, _height);
344 pdf_surface = cairo_pdf_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, d.x1-d.x0, d.y1-d.y0);
345 cr = cairo_create(pdf_surface);
347 if (!_bitmap) {
348 cairo_scale(cr, PT_PER_PX, PT_PER_PX);
350 // from now on we can output px, but they will be treated as pt
351 // note that the we do not have to flip the y axis
352 // because Cairo's coordinate system is identical to Inkscape's
353 }
355 return 1;
356 }
358 unsigned int
359 PrintCairoPDF::finish(Inkscape::Extension::Print *mod)
360 {
361 if (!_stream) return 0;
362 if (_bitmap) return 0;
364 cairo_show_page(cr);
366 cairo_destroy(cr);
367 cairo_surface_destroy(pdf_surface);
368 cr = NULL;
369 pdf_surface = NULL;
371 /* Flush stream to be sure. */
372 (void) fflush(_stream);
374 /* fixme: should really use pclose for popen'd streams */
375 fclose(_stream);
376 _stream = 0;
378 return 0;
379 }
381 unsigned int
382 PrintCairoPDF::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
383 {
384 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
385 if (_bitmap) return 0;
387 cairo_save(cr);
388 _concat_transform(cr, transform->c[0], transform->c[1], transform->c[2], transform->c[3], transform->c[4], transform->c[5]);
389 // 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]);
390 // remember these to be able to undo them when outputting text
391 _last_tx = transform->c[4];
392 _last_ty = transform->c[5];
394 if (_num_alphas <= ++_alpha_ptr) {
395 _num_alphas *= 2;
396 _alpha_stack = (float*)realloc((void*)_alpha_stack, sizeof(float) * _num_alphas);
397 }
398 _alpha_stack[_alpha_ptr] = _alpha_stack[_alpha_ptr-1] * opacity;
400 return 1;
401 }
403 unsigned int
404 PrintCairoPDF::release(Inkscape::Extension::Print *mod)
405 {
406 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
407 if (_bitmap) return 0;
409 cairo_restore(cr);
410 // g_printf("release\n");
411 if (_alpha_ptr > 0)
412 _alpha_ptr--;
414 return 1;
415 }
417 unsigned int
418 PrintCairoPDF::comment(Inkscape::Extension::Print *mod, char const *comment)
419 {
420 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
421 if (_bitmap) return 0;
423 return 1;
424 }
426 cairo_pattern_t*
427 PrintCairoPDF::create_pattern_for_paint(SPPaintServer const *const paintserver, NRRect const *pbox, float alpha)
428 {
429 cairo_pattern_t *pattern = NULL;
430 bool apply_bbox2user = false;
432 if (SP_IS_LINEARGRADIENT (paintserver)) {
434 SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver);
436 sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
438 NR::Point p1 (lg->x1.computed, lg->y1.computed);
439 NR::Point p2 (lg->x2.computed, lg->y2.computed);
440 if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
441 // convert to userspace
442 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
443 p1 *= bbox2user;
444 p2 *= bbox2user;
445 }
447 // create linear gradient pattern
448 pattern = cairo_pattern_create_linear(p1[NR::X], p1[NR::Y], p2[NR::X], p2[NR::Y]);
450 // add stops
451 for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) {
452 float rgb[3];
453 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
454 cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha);
455 }
456 } else if (SP_IS_RADIALGRADIENT (paintserver)) {
458 SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver);
460 sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
462 NR::Point c (rg->cx.computed, rg->cy.computed);
463 NR::Point f (rg->fx.computed, rg->fy.computed);
464 double r = rg->r.computed;
465 if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
466 apply_bbox2user = true;
468 // create radial gradient pattern
469 pattern = cairo_pattern_create_radial(f[NR::X], f[NR::Y], 0, c[NR::X], c[NR::Y], r);
471 // add stops
472 for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) {
473 float rgb[3];
474 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
475 cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha);
476 }
477 }
479 if (pattern) {
480 SPGradient *g = SP_GRADIENT(paintserver);
482 // set extend type
483 SPGradientSpread spread = sp_gradient_get_spread(g);
484 switch (spread) {
485 case SP_GRADIENT_SPREAD_REPEAT:
486 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
487 break;
488 case SP_GRADIENT_SPREAD_REFLECT: // not supported by cairo-pdf yet
489 //cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT);
490 //break;
491 case SP_GRADIENT_SPREAD_PAD:
492 default:
493 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE); // PAD not supported by cairo-pdf yet
494 break;
495 }
497 cairo_matrix_t pattern_matrix;
498 if (g->gradientTransform_set) {
499 // apply gradient transformation
500 cairo_matrix_init(&pattern_matrix,
501 g->gradientTransform[0], g->gradientTransform[1],
502 g->gradientTransform[2], g->gradientTransform[3],
503 g->gradientTransform[4], g->gradientTransform[5]);
504 } else {
505 cairo_matrix_init_identity (&pattern_matrix);
506 }
508 if (apply_bbox2user) {
509 // convert to userspace
510 cairo_matrix_t bbox2user;
511 cairo_matrix_init (&bbox2user, pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
512 cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix);
513 }
514 cairo_matrix_invert(&pattern_matrix); // because Cairo expects a userspace->patternspace matrix
515 cairo_pattern_set_matrix(pattern, &pattern_matrix);
516 }
518 return pattern;
519 }
521 void
522 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
523 {
524 g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
525 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
526 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
528 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
529 float rgb[3];
530 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
532 float alpha = 1.0;
533 alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
534 alpha *= _alpha_stack[_alpha_ptr];
536 cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
537 } else {
538 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
539 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
541 cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_FILL_SERVER(style), pbox, 1.0);
543 if (pattern) {
544 cairo_set_source(cr, pattern);
545 cairo_pattern_destroy(pattern);
546 }
547 }
548 }
550 unsigned int
551 PrintCairoPDF::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
552 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
553 {
554 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
555 if (_bitmap) return 0;
557 if ( style->fill.type == SP_PAINT_TYPE_COLOR
558 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
559 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) ) {
561 float alpha = 1.0;
562 alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
563 if (alpha != 1.0)
564 g_printf( "fa: %f a:%f fa*a = %f\n", alpha, _alpha_stack[_alpha_ptr], alpha*_alpha_stack[_alpha_ptr]);
565 alpha *= _alpha_stack[_alpha_ptr];
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[_alpha_ptr];
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[_alpha_ptr];
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("%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 empty or unknown glyphs
770 #if defined(PANGO_GLYPH_EMPTY) && defined(PANGO_GLYPH_UNKNOWN_FLAG)
771 if (info->glyph == PANGO_GLYPH_EMPTY || info->glyph & PANGO_GLYPH_UNKNOWN_FLAG) {
772 num_invalid_glyphs++;
773 continue;
774 }
775 #endif
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 */
1036 /*
1037 Local Variables:
1038 mode:c++
1039 c-file-style:"stroustrup"
1040 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1041 indent-tabs-mode:nil
1042 fill-column:99
1043 End:
1044 */
1045 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :