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 = _width;
332 d.y1 = _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 1;
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;
466 NR::Coord const df = hypot(f[NR::X] - c[NR::X], f[NR::Y] - c[NR::Y]);
467 if (df >= r) {
468 f[NR::X] = c[NR::X] + (f[NR::X] - c[NR::X] ) * r / (float) df;
469 f[NR::Y] = c[NR::Y] + (f[NR::Y] - c[NR::Y] ) * r / (float) df;
470 }
472 if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
473 apply_bbox2user = true;
475 // create radial gradient pattern
476 pattern = cairo_pattern_create_radial(f[NR::X], f[NR::Y], 0, c[NR::X], c[NR::Y], r);
478 // add stops
479 for (gint i = 0; unsigned(i) < rg->vector.stops.size(); i++) {
480 float rgb[3];
481 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
482 cairo_pattern_add_color_stop_rgba(pattern, rg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], rg->vector.stops[i].opacity * alpha);
483 }
484 }
486 if (pattern) {
487 SPGradient *g = SP_GRADIENT(paintserver);
489 // set extend type
490 SPGradientSpread spread = sp_gradient_get_spread(g);
491 switch (spread) {
492 case SP_GRADIENT_SPREAD_REPEAT:
493 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
494 break;
495 case SP_GRADIENT_SPREAD_REFLECT: // not supported by cairo-pdf yet
496 //cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REFLECT);
497 //break;
498 case SP_GRADIENT_SPREAD_PAD:
499 default:
500 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE); // PAD not supported by cairo-pdf yet
501 break;
502 }
504 cairo_matrix_t pattern_matrix;
505 if (g->gradientTransform_set) {
506 // apply gradient transformation
507 cairo_matrix_init(&pattern_matrix,
508 g->gradientTransform[0], g->gradientTransform[1],
509 g->gradientTransform[2], g->gradientTransform[3],
510 g->gradientTransform[4], g->gradientTransform[5]);
511 } else {
512 cairo_matrix_init_identity (&pattern_matrix);
513 }
515 if (apply_bbox2user) {
516 // convert to userspace
517 cairo_matrix_t bbox2user;
518 cairo_matrix_init (&bbox2user, pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
519 cairo_matrix_multiply (&pattern_matrix, &bbox2user, &pattern_matrix);
520 }
521 cairo_matrix_invert(&pattern_matrix); // because Cairo expects a userspace->patternspace matrix
522 cairo_pattern_set_matrix(pattern, &pattern_matrix);
523 }
525 return pattern;
526 }
528 void
529 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
530 {
531 g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
532 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
533 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
535 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
536 float rgb[3];
537 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
539 float alpha = 1.0;
540 alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
541 alpha *= _alpha_stack[_alpha_ptr];
543 cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
544 } else {
545 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
546 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
548 cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_FILL_SERVER(style), pbox, 1.0);
550 if (pattern) {
551 cairo_set_source(cr, pattern);
552 cairo_pattern_destroy(pattern);
553 }
554 }
555 }
557 unsigned int
558 PrintCairoPDF::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
559 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
560 {
561 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
562 if (_bitmap) return 0;
564 if ( style->fill.type == SP_PAINT_TYPE_COLOR
565 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
566 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) ) {
568 float alpha = 1.0;
569 alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
570 alpha *= _alpha_stack[_alpha_ptr];
572 cairo_save(cr);
574 print_fill_style(cr, style, pbox);
575 print_bpath(cr, bpath->path);
576 if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
577 cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
578 } else {
579 cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
580 }
581 if (alpha != 1.0 &&
582 style->fill.type != SP_PAINT_TYPE_COLOR) {
584 cairo_clip (cr);
585 cairo_paint_with_alpha (cr, alpha);
586 } else {
587 cairo_fill(cr);
588 }
590 cairo_restore(cr);
591 }
593 return 0;
594 }
596 void
597 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
598 {
599 float alpha = 1.0;
600 alpha *= SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
601 alpha *= _alpha_stack[_alpha_ptr];
603 if ( style->stroke.type == SP_PAINT_TYPE_COLOR ) {
604 float rgb[3];
605 sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
607 cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
608 } else if ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
609 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
611 cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
613 if (pattern) {
614 cairo_set_source(cr, pattern);
615 cairo_pattern_destroy(pattern);
616 }
617 }
619 if (style->stroke_dash.n_dash &&
620 style->stroke_dash.dash )
621 {
622 cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
623 } else {
624 cairo_set_dash(cr, NULL, 0, 0.0); // disable dashing
625 }
627 cairo_set_line_width(cr, style->stroke_width.computed);
629 // set line join type
630 cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
631 switch (style->stroke_linejoin.computed) {
632 case SP_STROKE_LINEJOIN_MITER:
633 join = CAIRO_LINE_JOIN_MITER;
634 break;
635 case SP_STROKE_LINEJOIN_ROUND:
636 join = CAIRO_LINE_JOIN_ROUND;
637 break;
638 case SP_STROKE_LINEJOIN_BEVEL:
639 join = CAIRO_LINE_JOIN_BEVEL;
640 break;
641 }
642 cairo_set_line_join(cr, join);
644 // set line cap type
645 cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
646 switch (style->stroke_linecap.computed) {
647 case SP_STROKE_LINECAP_BUTT:
648 cap = CAIRO_LINE_CAP_BUTT;
649 break;
650 case SP_STROKE_LINECAP_ROUND:
651 cap = CAIRO_LINE_CAP_ROUND;
652 break;
653 case SP_STROKE_LINECAP_SQUARE:
654 cap = CAIRO_LINE_CAP_SQUARE;
655 break;
656 }
657 cairo_set_line_cap(cr, cap);
658 cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
659 }
661 unsigned int
662 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
663 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
664 {
665 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
666 if (_bitmap) return 0;
668 if ( style->stroke.type == SP_PAINT_TYPE_COLOR ||
669 ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
670 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
672 cairo_save(cr);
674 print_stroke_style(cr, style, pbox);
675 print_bpath(cr, bpath->path);
676 cairo_stroke(cr);
678 cairo_restore(cr);
679 }
681 return 0;
682 }
684 unsigned int
685 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
686 NRMatrix const *transform, SPStyle const *style)
687 {
688 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
689 if (_bitmap) return 0;
691 guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
692 if (!px_rgba) return 0;
694 float alpha = _alpha_stack[_alpha_ptr];
696 // make a copy of the original pixbuf with premultiplied alpha
697 // if we pass the original pixbuf it will get messed up
698 for (unsigned i = 0; i < h; i++) {
699 for (unsigned j = 0; j < w; j++) {
700 guchar const *src = px + i * rs + j * 4;
701 guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
702 guchar r, g, b, alpha_dst;
704 // calculate opacity-modified alpha
705 alpha_dst = src[3];
706 if (alpha != 1.0)
707 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
709 // premul alpha (needed because this will be undone by cairo-pdf)
710 r = src[0]*alpha_dst/255;
711 g = src[1]*alpha_dst/255;
712 b = src[2]*alpha_dst/255;
714 *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
715 }
716 }
718 cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
719 if (cairo_surface_status(image_surface)) {
720 g_printf("%s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
721 return 0;
722 }
724 cairo_save(cr);
726 // scaling by width & height is not needed because it will be done by cairo-pdf
727 // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
728 cairo_matrix_t matrix;
729 cairo_matrix_init(&matrix,
730 transform->c[0]/w, transform->c[1],
731 transform->c[2], -transform->c[3]/h,
732 transform->c[4], transform->c[5] + transform->c[3]);
733 cairo_transform(cr, &matrix);
735 cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
736 cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
738 cairo_set_source(cr, pattern);
739 cairo_pattern_destroy(pattern);
741 // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
742 cairo_new_path(cr);
743 cairo_rectangle(cr, 0, 0, w, h);
744 cairo_clip(cr);
746 cairo_paint(cr);
748 cairo_restore(cr);
750 cairo_surface_destroy(image_surface);
751 g_free(px_rgba);
753 return 0;
754 }
756 #define GLYPH_ARRAY_SIZE 64
758 #ifndef RENDER_WITH_PANGO_CAIRO
760 NR::Point
761 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
762 bool vertical, bool stroke)
763 {
764 cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
765 cairo_glyph_t *glyphs = glyph_array;
766 if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
767 glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
769 PangoGlyphUnit x_offset = 0, y_offset = 0;
770 PangoGlyphInfo *info;
771 int num_invalid_glyphs = 0;
772 for (gint i = 0; i < glyph_string->num_glyphs; i++) {
773 info = &glyph_string->glyphs[i];
774 // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) or have
775 // the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set
776 if (info->glyph == 0x0FFFFFFF || info->glyph & 0x10000000) {
777 num_invalid_glyphs++;
778 continue;
779 }
781 glyphs[i - num_invalid_glyphs].index = info->glyph;
782 glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
783 glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
785 if (vertical) {
786 cairo_text_extents_t extents;
787 cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
788 y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
789 }
790 else
791 x_offset += info->geometry.width;
792 }
794 if (stroke)
795 cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
796 else
797 cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
799 if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
800 g_free(glyphs);
802 return NR::Point(x_offset, y_offset);
803 }
804 #endif
808 unsigned int
809 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
810 SPStyle const *const style)
811 {
812 bool dirty_pattern = false;
814 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
815 if (_bitmap) return 0;
817 cairo_save(cr);
819 // this needs to be there to encounter Cairo's userspace locking semantics for set_source
820 // otherwise gradients won't be shown correctly
821 cairo_translate(cr, -_last_tx, -_last_ty);
823 // create pango layout and context if needed
824 if (_layout == NULL) {
825 #ifdef RENDER_WITH_PANGO_CAIRO
826 //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
827 _layout = pango_cairo_create_layout(cr);
828 #else
829 _layout = pango_layout_new((font_factory::Default())->fontContext);
830 #endif
831 }
833 // create font instance from style and use it
834 font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
835 if (tf == NULL) { // do something
836 g_printf("Warning: trouble getting font_instance\n");
837 tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
838 }
839 PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
841 pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
842 pango_layout_set_font_description(_layout, adjusted);
843 pango_layout_set_text(_layout, text, -1);
845 pango_font_description_free(adjusted);
846 tf->Unref();
848 #ifdef RENDER_WITH_PANGO_CAIRO
849 pango_cairo_update_layout(cr, _layout);
850 #else
851 pango_layout_context_changed(_layout); // is this needed?
852 #endif
854 PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
855 if (line == NULL)
856 return 0;
858 #ifndef RENDER_WITH_PANGO_CAIRO
859 // apply the selected font
860 double size;
861 PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
862 PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
863 FcPattern *fc_pattern = fc_font->font_pattern;
865 if ( style->writing_mode.set &&
866 (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
867 style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
868 {
869 FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
870 FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
871 dirty_pattern = true;
872 }
874 cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
875 cairo_set_font_face(cr, font_face);
877 if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
878 size = 12.0;
880 // adjust size and horizontal flip
881 cairo_matrix_t matrix;
882 cairo_get_font_matrix(cr, &matrix);
883 matrix.xx = size;
884 matrix.yy = -matrix.xx;
885 cairo_set_font_matrix(cr, &matrix);
886 #endif
888 if ( style->fill.type == SP_PAINT_TYPE_COLOR
889 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
890 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
891 {
892 // set fill style
893 print_fill_style(cr, style, NULL);
895 #ifndef RENDER_WITH_PANGO_CAIRO
896 NR::Point cursor(_last_tx, _last_ty);
897 for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
898 PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
899 cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
900 }
901 #else
902 cairo_new_path(cr);
903 cairo_move_to(cr, _last_tx, _last_ty);
904 pango_cairo_show_layout_line(cr, line);
905 #endif
906 }
908 if (style->stroke.type == SP_PAINT_TYPE_COLOR
909 || ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
910 && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
911 {
912 // set stroke style
913 print_stroke_style(cr, style, NULL);
915 // paint stroke
916 #ifndef RENDER_WITH_PANGO_CAIRO
917 NR::Point cursor(_last_tx, _last_ty);
918 for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
919 PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
920 cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, true) / PANGO_SCALE;
921 }
922 #else
923 cairo_new_path(cr);
924 cairo_move_to(cr, _last_tx, _last_ty);
925 pango_cairo_layout_line_path(cr, line);
926 #endif
927 cairo_stroke(cr);
928 }
931 cairo_restore(cr);
933 #ifndef RENDER_WITH_PANGO_CAIRO
934 cairo_font_face_destroy(font_face);
936 if (dirty_pattern) {
937 FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
938 FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
939 }
940 #endif
941 tf->Unref();
943 return 0;
944 }
946 /* Helper functions */
948 void
949 PrintCairoPDF::print_bpath(cairo_t *cr, NArtBpath const *bp)
950 {
951 cairo_new_path(cr);
952 bool closed = false;
953 while (bp->code != NR_END) {
954 switch (bp->code) {
955 case NR_MOVETO:
956 if (closed) {
957 cairo_close_path(cr);
958 }
959 closed = true;
960 cairo_move_to(cr, bp->x3, bp->y3);
961 break;
962 case NR_MOVETO_OPEN:
963 if (closed) {
964 cairo_close_path(cr);
965 }
966 closed = false;
967 cairo_move_to(cr, bp->x3, bp->y3);
968 break;
969 case NR_LINETO:
970 cairo_line_to(cr, bp->x3, bp->y3);
971 break;
972 case NR_CURVETO:
973 cairo_curve_to(cr, bp->x1, bp->y1, bp->x2, bp->y2, bp->x3, bp->y3);
974 break;
975 default:
976 break;
977 }
978 bp += 1;
979 }
980 if (closed) {
981 cairo_close_path(cr);
982 }
983 }
985 static void
986 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
987 {
988 cairo_matrix_t matrix;
990 cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
991 cairo_transform(cr, &matrix);
992 }
994 static cairo_status_t
995 _write_callback(void *closure, const unsigned char *data, unsigned int length)
996 {
997 size_t written;
998 FILE *file = (FILE*)closure;
1000 written = fwrite (data, 1, length, file);
1002 if (written == length)
1003 return CAIRO_STATUS_SUCCESS;
1004 else
1005 return CAIRO_STATUS_WRITE_ERROR;
1006 }
1008 bool
1009 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
1010 {
1011 return ext->get_param_bool("textToPath");
1012 }
1014 #include "clear-n_.h"
1016 void
1017 PrintCairoPDF::init(void)
1018 {
1019 /* PDF out */
1020 (void) Inkscape::Extension::build_from_mem(
1021 "<inkscape-extension>\n"
1022 "<name>" N_("PDF Print") "</name>\n"
1023 "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1024 "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1025 "<param name=\"resolution\" type=\"string\">72</param>\n"
1026 "<param name=\"destination\" type=\"string\">| lp</param>\n"
1027 "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1028 "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1029 "<print/>\n"
1030 "</inkscape-extension>", new PrintCairoPDF());
1031 }
1034 } /* namespace Internal */
1035 } /* namespace Extension */
1036 } /* namespace Inkscape */
1038 /* End of GNU GPL code */
1041 /*
1042 Local Variables:
1043 mode:c++
1044 c-file-style:"stroustrup"
1045 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1046 indent-tabs-mode:nil
1047 fill-column:99
1048 End:
1049 */
1050 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :