Code

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