Code

Removed left-in debug stuff.
[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 #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 }
91 PrintCairoPDF::~PrintCairoPDF(void)
92 {
93     if (cr) cairo_destroy(cr);
94     if (pdf_surface) cairo_surface_destroy(pdf_surface);
95     if (_layout) g_object_unref(_layout);
96     
97     /* restore default signal handling for SIGPIPE */
98 #if !defined(_WIN32) && !defined(__WIN32__)
99     (void) signal(SIGPIPE, SIG_DFL);
100 #endif
102     return;
105 unsigned int
106 PrintCairoPDF::setup(Inkscape::Extension::Print * mod)
108     static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
110 #ifdef TED
111     Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
112 #endif
114     unsigned int ret = FALSE;
116     /* Create dialog */
117     GtkTooltips *tt = gtk_tooltips_new();
118     g_object_ref((GObject *) tt);
119     gtk_object_sink((GtkObject *) tt);
121     GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
122 //            SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
123             NULL,
124             (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
125             GTK_STOCK_CANCEL,
126             GTK_RESPONSE_CANCEL,
127             GTK_STOCK_PRINT,
128             GTK_RESPONSE_OK,
129             NULL);
131     gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
133     GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
134     gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
135     /* Print properties frame */
136     GtkWidget *f = gtk_frame_new(_("Print properties"));
137     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
138     GtkWidget *vb = gtk_vbox_new(FALSE, 4);
139     gtk_container_add(GTK_CONTAINER(f), vb);
140     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
141     /* Print type */
142     bool const p2bm = mod->get_param_bool("bitmap");
143     GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PDF operators"));
144     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
145                          _("Use PDF vector operators. The resulting image is usually smaller "
146                            "in file size and can be arbitrarily scaled, but "
147                            "patterns will be lost."), NULL);
148     if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
149     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
150     rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
151     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
152                          _("Print everything as bitmap. The resulting image is usually larger "
153                            "in file size and cannot be arbitrarily scaled without quality loss, "
154                            "but all objects will be rendered exactly as displayed."), NULL);
155     if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
156     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
157     /* Resolution */
158     GtkWidget *hb = gtk_hbox_new(FALSE, 4);
159     gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
160     GtkWidget *combo = gtk_combo_new();
161     gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
162     gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
163     gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
164     gtk_widget_set_size_request(combo, 64, -1);
165     gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
166                          _("Preferred resolution (dots per inch) of bitmap"), NULL);
167     /* Setup strings */
168     GList *sl = NULL;
169     for (unsigned i = 0; pdr[i] != NULL; i++) {
170         sl = g_list_prepend(sl, (gpointer) pdr[i]);
171     }
172     sl = g_list_reverse(sl);
173     gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
174     g_list_free(sl);
175     if (1) {
176         gchar const *val = mod->get_param_string("resolution");
177         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
178     }
179     gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
180     GtkWidget *l = gtk_label_new(_("Resolution:"));
181     gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
183     /* Print destination frame */
184     f = gtk_frame_new(_("Print destination"));
185     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
186     vb = gtk_vbox_new(FALSE, 4);
187     gtk_container_add(GTK_CONTAINER(f), vb);
188     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
190     l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
191                         "leave empty to use the system default printer.\n"
192                         "Use '> filename' to print to file.\n"
193                         "Use '| prog arg...' to pipe to a program."));
194     gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
196     GtkWidget *e = gtk_entry_new();
197     if (1) {
198         gchar const *val = mod->get_param_string("destination");
199         gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
200                                            ? val
201                                            : "" ));
202     }
203     gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
205     // pressing enter in the destination field is the same as clicking Print:
206     gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
208     gtk_widget_show_all(vbox);
210     int const response = gtk_dialog_run(GTK_DIALOG(dlg));
212     g_object_unref((GObject *) tt);
214     if (response == GTK_RESPONSE_OK) {
215         gchar const *fn;
216         char const *sstr;
218         _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
219         sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
220         _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
221         /* Arrgh, have to do something */
222         fn = gtk_entry_get_text(GTK_ENTRY(e));
223         /* skip leading whitespace, bug #1068483 */
224         while (fn && *fn==' ') { fn++; }
225         /* g_print("Printing to %s\n", fn); */
227         mod->set_param_bool("bitmap", _bitmap);
228         mod->set_param_string("resolution", (gchar *)sstr);
229         mod->set_param_string("destination", (gchar *)fn);
230         ret = TRUE;
231     }
233     gtk_widget_destroy(dlg);
235     return ret;
238 unsigned int
239 PrintCairoPDF::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
241     FILE *osf = NULL;
242     FILE *osp = NULL;
244     _alpha_stack.clear();
245     _alpha_stack.push_back(1.0);
247     gsize bytesRead = 0;
248     gsize bytesWritten = 0;
249     GError *error = NULL;
250     gchar const *utf8_fn = mod->get_param_string("destination");
251     gchar *local_fn = g_filename_from_utf8( utf8_fn,
252                                             -1,  &bytesRead,  &bytesWritten, &error);
253     gchar const *fn = local_fn;
255     /* TODO: Replace the below fprintf's with something that does the right thing whether in
256      * gui or batch mode (e.g. --print=blah).  Consider throwing an exception: currently one of
257      * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
258      * return code.
259      */
260     if (fn != NULL) {
261         if (*fn == '|') {
262             fn += 1;
263             while (isspace(*fn)) fn += 1;
264 #ifndef WIN32
265             osp = popen(fn, "w");
266 #else
267             osp = _popen(fn, "w");
268 #endif
269             if (!osp) {
270                 fprintf(stderr, "inkscape: popen(%s): %s\n",
271                         fn, strerror(errno));
272                 return 0;
273             }
274             _stream = osp;
275         } else if (*fn == '>') {
276             fn += 1;
277             while (isspace(*fn)) fn += 1;
278             Inkscape::IO::dump_fopen_call(fn, "K");
279             osf = Inkscape::IO::fopen_utf8name(fn, "w+");
280             if (!osf) {
281                 fprintf(stderr, "inkscape: fopen(%s): %s\n",
282                         fn, strerror(errno));
283                 return 0;
284             }
285             _stream = osf;
286         } else {
287             /* put cwd stuff in here */
288             gchar *qn = ( *fn
289                           ? g_strdup_printf("lpr -P %s", fn)  /* FIXME: quote fn */
290                           : g_strdup("lpr") );
291 #ifndef WIN32
292             osp = popen(qn, "w");
293 #else
294             osp = _popen(qn, "w");
295 #endif
296             if (!osp) {
297                 fprintf(stderr, "inkscape: popen(%s): %s\n",
298                         qn, strerror(errno));
299                 return 0;
300             }
301             g_free(qn);
302             _stream = osp;
303         }
304     }
306     g_free(local_fn);
308     if (_stream) {
309         /* fixme: this is kinda icky */
310 #if !defined(_WIN32) && !defined(__WIN32__)
311         (void) signal(SIGPIPE, SIG_IGN);
312 #endif
313     }
314     
315     // test output stream?
317     // width and height in pt
318     _width = sp_document_width(doc) * PT_PER_PX;
319     _height = sp_document_height(doc) * PT_PER_PX;
321     NRRect d;
322     bool   pageBoundingBox;
323     pageBoundingBox = mod->get_param_bool("pageBoundingBox");
324     // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
325     if (pageBoundingBox) {
326         d.x0 = d.y0 = 0;
327         d.x1 = _width;
328         d.y1 = _height;
329     } else {
330         SPItem* doc_item = SP_ITEM(sp_document_root(doc));
331         sp_item_invoke_bbox(doc_item, &d, sp_item_i2r_affine(doc_item), TRUE);
332         // convert from px to pt
333         d.x0 *= PT_PER_PX;
334         d.x1 *= PT_PER_PX;
335         d.y0 *= PT_PER_PX;
336         d.y1 *= PT_PER_PX;
337     }
338     printf("%f %f\n", _width, _height);
340     pdf_surface = cairo_pdf_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, d.x1-d.x0, d.y1-d.y0);
341     cr = cairo_create(pdf_surface);
342     
343     if (!_bitmap) {
344         cairo_scale(cr, PT_PER_PX, PT_PER_PX);
345         
346         // from now on we can output px, but they will be treated as pt
347         // note that the we do not have to flip the y axis
348         // because Cairo's coordinate system is identical to Inkscape's
349     }   
351     return 1;
354 unsigned int
355 PrintCairoPDF::finish(Inkscape::Extension::Print *mod)
357     if (!_stream) return 0;
358     if (_bitmap) return 0;
360     cairo_show_page(cr);        
362     cairo_destroy(cr);
363     cairo_surface_destroy(pdf_surface);
364     cr = NULL;
365     pdf_surface = NULL;
367     /* Flush stream to be sure. */
368     (void) fflush(_stream);
370     /* fixme: should really use pclose for popen'd streams */
371     fclose(_stream);
372     _stream = 0;
374     return 1;
377 unsigned int
378 PrintCairoPDF::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
380     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
381     if (_bitmap) return 0;
382     
383     cairo_save(cr);
384     _concat_transform(cr, transform->c[0], transform->c[1], transform->c[2], transform->c[3], transform->c[4], transform->c[5]);
385 //    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]);
386     // remember these to be able to undo them when outputting text
387     _last_tx = transform->c[4];
388     _last_ty = transform->c[5];
389     
390     float new_opacity = _alpha_stack.back() * opacity;
391     _alpha_stack.push_back(new_opacity);
392     
393     return 1;
396 unsigned int
397 PrintCairoPDF::release(Inkscape::Extension::Print *mod)
399     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
400     if (_bitmap) return 0;
401     
402     cairo_restore(cr);
403 //    g_printf("release\n");
404     _alpha_stack.pop_back();
405     g_assert(_alpha_stack.size() > 0);
407     return 1;
410 unsigned int
411 PrintCairoPDF::comment(Inkscape::Extension::Print *mod, char const *comment)
413     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
414     if (_bitmap) return 0;
416     return 1;
419 cairo_pattern_t*
420 PrintCairoPDF::create_pattern_for_paint(SPPaintServer const *const paintserver, NRRect const *pbox, float alpha)
422     cairo_pattern_t *pattern = NULL;
423     bool apply_bbox2user = false;
424     
425     if (SP_IS_LINEARGRADIENT (paintserver)) {
427             SPLinearGradient *lg=SP_LINEARGRADIENT(paintserver);
428             
429             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
431             NR::Point p1 (lg->x1.computed, lg->y1.computed);
432             NR::Point p2 (lg->x2.computed, lg->y2.computed);
433             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
434                 // convert to userspace
435                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
436                 p1 *= bbox2user;
437                 p2 *= bbox2user;
438             }
439             
440             // create linear gradient pattern
441             pattern = cairo_pattern_create_linear(p1[NR::X], p1[NR::Y], p2[NR::X], p2[NR::Y]);
442             
443             // add stops
444             for (gint i = 0; unsigned(i) < lg->vector.stops.size(); i++) {
445                 float rgb[3];
446                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
447                 cairo_pattern_add_color_stop_rgba(pattern, lg->vector.stops[i].offset, rgb[0], rgb[1], rgb[2], lg->vector.stops[i].opacity * alpha);
448             }
449     } else if (SP_IS_RADIALGRADIENT (paintserver)) {
451         SPRadialGradient *rg=SP_RADIALGRADIENT(paintserver);
453         sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
455         NR::Point c (rg->cx.computed, rg->cy.computed);
456         NR::Point f (rg->fx.computed, rg->fy.computed);
457         double r = rg->r.computed;
458         
459         NR::Coord const df = hypot(f[NR::X] - c[NR::X], f[NR::Y] - c[NR::Y]);
460         if (df >= r) {
461             f[NR::X] = c[NR::X] + (f[NR::X] - c[NR::X] ) * r / (float) df;
462             f[NR::Y] = c[NR::Y] + (f[NR::Y] - c[NR::Y] ) * r / (float) df;
463         }
464         
465         if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX)
466             apply_bbox2user = true;
467         
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     }
478         
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     }
517         
518     return pattern;
521 void
522 PrintCairoPDF::print_fill_style(cairo_t *cr, SPStyle const *const style, NRRect const *pbox)
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)) ) );
527     
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.back();
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);
542         
543         if (pattern) {
544                 cairo_set_source(cr, pattern);
545             cairo_pattern_destroy(pattern);
546         }
547     }
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)
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)) ) ) {
560         
561         float alpha = 1.0;
562         alpha *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
563         alpha *= _alpha_stack.back();
564                 
565         cairo_save(cr);
566         
567         print_fill_style(cr, style, pbox);
568         print_bpath(cr, bpath->path);
569         if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
570             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
571         } else {
572             cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
573         }
574         if (alpha != 1.0 &&
575             style->fill.type != SP_PAINT_TYPE_COLOR) {
577             cairo_clip (cr);
578             cairo_paint_with_alpha (cr, alpha);
579         } else {
580             cairo_fill(cr);
581         }
582         
583         cairo_restore(cr);
584     }
586     return 0;
589 void
590 PrintCairoPDF::print_stroke_style(cairo_t *cr, SPStyle const *style, NRRect const *pbox)
592     float alpha = 1.0;
593     alpha *= SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
594     alpha *= _alpha_stack.back();
596     if ( style->stroke.type == SP_PAINT_TYPE_COLOR ) {
597         float rgb[3];
598         sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
599       
600         cairo_set_source_rgba(cr, rgb[0], rgb[1], rgb[2], alpha);
601     } else if ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
602                   && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) {
604         cairo_pattern_t *pattern = create_pattern_for_paint(SP_STYLE_STROKE_SERVER(style), pbox, alpha);
605         
606         if (pattern) {
607                 cairo_set_source(cr, pattern);
608             cairo_pattern_destroy(pattern);
609         }
610     }
612     if (style->stroke_dash.n_dash   &&
613         style->stroke_dash.dash       )
614     {
615         cairo_set_dash(cr, style->stroke_dash.dash, style->stroke_dash.n_dash, style->stroke_dash.offset);
616     } else {
617         cairo_set_dash(cr, NULL, 0, 0.0);       // disable dashing
618     }
619     
620     cairo_set_line_width(cr, style->stroke_width.computed);
621     
622     // set line join type
623     cairo_line_join_t join = CAIRO_LINE_JOIN_MITER;
624     switch (style->stroke_linejoin.computed) {
625         case SP_STROKE_LINEJOIN_MITER:
626             join = CAIRO_LINE_JOIN_MITER;
627             break;
628         case SP_STROKE_LINEJOIN_ROUND:
629             join = CAIRO_LINE_JOIN_ROUND;
630             break;
631         case SP_STROKE_LINEJOIN_BEVEL:
632             join = CAIRO_LINE_JOIN_BEVEL;
633             break;
634     }           
635     cairo_set_line_join(cr, join);
636     
637     // set line cap type
638     cairo_line_cap_t cap = CAIRO_LINE_CAP_BUTT;
639     switch (style->stroke_linecap.computed) {
640         case SP_STROKE_LINECAP_BUTT:
641             cap = CAIRO_LINE_CAP_BUTT;
642             break;
643         case SP_STROKE_LINECAP_ROUND:
644             cap = CAIRO_LINE_CAP_ROUND;
645             break;
646         case SP_STROKE_LINECAP_SQUARE:
647             cap = CAIRO_LINE_CAP_SQUARE;
648             break;
649     }           
650     cairo_set_line_cap(cr, cap);
651     cairo_set_miter_limit(cr, MAX(1, style->stroke_miterlimit.value));
654 unsigned int
655 PrintCairoPDF::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
656                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
658     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
659     if (_bitmap) return 0;
661     if ( style->stroke.type == SP_PAINT_TYPE_COLOR ||
662         ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
663               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) ) {
665         cairo_save(cr);
666         
667         print_stroke_style(cr, style, pbox);
668         print_bpath(cr, bpath->path);
669         cairo_stroke(cr);
670                 
671         cairo_restore(cr);
672     }
674     return 0;
677 unsigned int
678 PrintCairoPDF::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
679                NRMatrix const *transform, SPStyle const *style)
681     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
682     if (_bitmap) return 0;
683     
684     guchar* px_rgba = (guchar*)g_malloc(4 * w * h);
685     if (!px_rgba) return 0;
686     
687     float alpha = _alpha_stack.back();
689     // make a copy of the original pixbuf with premultiplied alpha
690     // if we pass the original pixbuf it will get messed up
691     for (unsigned i = 0; i < h; i++) {
692         for (unsigned j = 0; j < w; j++) {
693             guchar const *src = px + i * rs + j * 4;
694             guint32 *dst = (guint32 *)(px_rgba + i * rs + j * 4);
695             guchar r, g, b, alpha_dst;
696             
697             // calculate opacity-modified alpha
698             alpha_dst = src[3];
699             if (alpha != 1.0)
700                 alpha_dst = (guchar)ceil((float)alpha_dst * alpha);
702             // premul alpha (needed because this will be undone by cairo-pdf)
703             r = src[0]*alpha_dst/255;
704             g = src[1]*alpha_dst/255;
705             b = src[2]*alpha_dst/255;
706             
707             *dst = (((alpha_dst) << 24) | (((r)) << 16) | (((g)) << 8) | (b));
708         }
709     }
710     
711     cairo_surface_t *image_surface = cairo_image_surface_create_for_data(px_rgba, CAIRO_FORMAT_ARGB32, w, h, w * 4);
712     if (cairo_surface_status(image_surface)) {
713         g_printf("Error: %s\n", cairo_status_to_string(cairo_surface_status(image_surface)));
714         return 0;
715     }
716     
717     cairo_save(cr);
718     
719         // scaling by width & height is not needed because it will be done by cairo-pdf
720         // we have to translate down by height also in order to eliminate the last translation done by sp_image_print
721     cairo_matrix_t matrix;
722     cairo_matrix_init(&matrix,
723                     transform->c[0]/w, transform->c[1],
724                     transform->c[2], -transform->c[3]/h,
725                     transform->c[4], transform->c[5] + transform->c[3]);
726     cairo_transform(cr, &matrix);
728     cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image_surface);
729     cairo_pattern_set_extend(pattern, CAIRO_EXTEND_NONE);
731     cairo_set_source(cr, pattern);
732     cairo_pattern_destroy(pattern);
733     
734     // set clip region so that the pattern will not be repeated (bug in Cairo prior 1.2.1)
735     cairo_new_path(cr);
736     cairo_rectangle(cr, 0, 0, w, h);
737     cairo_clip(cr);
739     cairo_paint(cr);
740     
741     cairo_restore(cr);
742     
743     cairo_surface_destroy(image_surface);
744     g_free(px_rgba);
745     
746     return 0;
749 #define GLYPH_ARRAY_SIZE 64
751 #ifndef RENDER_WITH_PANGO_CAIRO
753 NR::Point
754 PrintCairoPDF::draw_glyphs(cairo_t *cr, NR::Point p, PangoFont *font, PangoGlyphString *glyph_string,
755                bool vertical, bool stroke)
757     cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
758     cairo_glyph_t *glyphs = glyph_array;
759     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
760         glyphs = (cairo_glyph_t*)g_malloc(sizeof(cairo_glyph_t) * glyph_string->num_glyphs);
762     PangoGlyphUnit x_offset = 0, y_offset = 0;
763     PangoGlyphInfo *info;
764     int num_invalid_glyphs = 0;
765     for (gint i = 0; i < glyph_string->num_glyphs; i++) {
766         info = &glyph_string->glyphs[i];
767         // skip glyphs which are PANGO_GLYPH_EMPTY (0x0FFFFFFF) or have 
768         // the PANGO_GLYPH_UNKNOWN_FLAG (0x10000000) set
769         if (info->glyph == 0x0FFFFFFF || info->glyph & 0x10000000) {
770             num_invalid_glyphs++;
771             continue;
772         }
774         glyphs[i - num_invalid_glyphs].index = info->glyph;
775         glyphs[i - num_invalid_glyphs].x = p[NR::X] + (x_offset + info->geometry.x_offset)/PANGO_SCALE;
776         glyphs[i - num_invalid_glyphs].y = p[NR::Y] + (y_offset + info->geometry.y_offset)/PANGO_SCALE;
778         if (vertical) {
779             cairo_text_extents_t extents;
780             cairo_glyph_extents(cr, &glyphs[i - num_invalid_glyphs], 1, &extents);
781             y_offset += (PangoGlyphUnit)(extents.y_advance * PANGO_SCALE);
782         }
783         else
784             x_offset += info->geometry.width;
785     }
787     if (stroke)
788         cairo_glyph_path(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
789     else
790         cairo_show_glyphs(cr, glyphs, glyph_string->num_glyphs - num_invalid_glyphs);
792     if (glyph_string->num_glyphs > GLYPH_ARRAY_SIZE)
793         g_free(glyphs);
795     return NR::Point(x_offset, y_offset);
797 #endif
801 unsigned int
802 PrintCairoPDF::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
803               SPStyle const *const style)
805     bool dirty_pattern = false;
807     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
808     if (_bitmap) return 0;
810     cairo_save(cr);
812     // this needs to be there to encounter Cairo's userspace locking semantics for set_source
813     // otherwise gradients won't be shown correctly
814     cairo_translate(cr, -_last_tx, -_last_ty);
816     // create pango layout and context if needed
817     if (_layout == NULL) {
818 #ifdef RENDER_WITH_PANGO_CAIRO
819         //_context = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pango_cairo_font_map_get_default()));
820         _layout = pango_cairo_create_layout(cr);
821 #else
822         _layout = pango_layout_new((font_factory::Default())->fontContext);
823 #endif
824     }
826     // create font instance from style and use it
827     font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
828     if (tf == NULL) {   // do something
829         g_printf("Warning: trouble getting font_instance\n");
830         tf = (font_factory::Default())->Face("sans", font_style_to_pos(*style));
831     }        
832     PangoFontDescription *adjusted = pango_font_description_copy(tf->descr);
833     
834     pango_font_description_set_absolute_size(adjusted, (gint)(style->font_size.computed * PANGO_SCALE));
835     pango_layout_set_font_description(_layout, adjusted);
836     pango_layout_set_text(_layout, text, -1);
838     pango_font_description_free(adjusted);
839     tf->Unref();
841 #ifdef RENDER_WITH_PANGO_CAIRO
842     pango_cairo_update_layout(cr, _layout);
843 #else
844     pango_layout_context_changed(_layout);   // is this needed?
845 #endif
847     PangoLayoutLine *line = pango_layout_get_line(_layout, 0);
848     if (line == NULL)
849         return 0;
851 #ifndef RENDER_WITH_PANGO_CAIRO
852     // apply the selected font
853     double size;
854     PangoLayoutRun *first_run = (PangoLayoutRun *)line->runs->data;
855     PangoFcFont *fc_font = PANGO_FC_FONT(first_run->item->analysis.font);
856     FcPattern *fc_pattern = fc_font->font_pattern;
858     if ( style->writing_mode.set &&
859        (style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_RL ||
860         style->writing_mode.computed == SP_CSS_WRITING_MODE_TB_LR) )
861     {
862         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
863         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcTrue);
864         dirty_pattern = true;
865     }
867     cairo_font_face_t *font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
868     cairo_set_font_face(cr, font_face);
870     if (FcPatternGetDouble(fc_pattern, FC_PIXEL_SIZE, 0, &size) != FcResultMatch)
871         size = 12.0;
873     // adjust size and horizontal flip
874     cairo_matrix_t matrix;
875     cairo_get_font_matrix(cr, &matrix);
876     matrix.xx = size;
877     matrix.yy = -matrix.xx;
878     cairo_set_font_matrix(cr, &matrix);
879 #endif
880     
881     if ( style->fill.type == SP_PAINT_TYPE_COLOR
882          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
883               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
884     {
885         // set fill style
886         print_fill_style(cr, style, NULL);
888 #ifndef RENDER_WITH_PANGO_CAIRO
889         NR::Point cursor(_last_tx, _last_ty);
890         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
891             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
892             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, false) / PANGO_SCALE;
893         }
894 #else
895         cairo_new_path(cr);
896         cairo_move_to(cr, _last_tx, _last_ty);
897         pango_cairo_show_layout_line(cr, line);
898 #endif
899     }
901     if (style->stroke.type == SP_PAINT_TYPE_COLOR
902          || ( style->stroke.type == SP_PAINT_TYPE_PAINTSERVER
903               && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style)) ) )
904     {
905         // set stroke style
906         print_stroke_style(cr, style, NULL);
908         // paint stroke
909 #ifndef RENDER_WITH_PANGO_CAIRO
910         NR::Point cursor(_last_tx, _last_ty);
911         for (GSList *tmpList = line->runs; tmpList && tmpList->data; tmpList = tmpList->next) {
912             PangoLayoutRun *run = (PangoLayoutRun *)tmpList->data;
913             cursor += draw_glyphs(cr, cursor, run->item->analysis.font, run->glyphs, dirty_pattern, true) / PANGO_SCALE;
914         }
915 #else
916         cairo_new_path(cr);
917         cairo_move_to(cr, _last_tx, _last_ty);
918         pango_cairo_layout_line_path(cr, line);
919 #endif
920         cairo_stroke(cr);
921     }
924     cairo_restore(cr);
926 #ifndef RENDER_WITH_PANGO_CAIRO
927     cairo_font_face_destroy(font_face);
929     if (dirty_pattern) {
930         FcPatternDel(fc_pattern, FC_VERTICAL_LAYOUT);
931         FcPatternAddBool(fc_pattern, FC_VERTICAL_LAYOUT, FcFalse);
932     }
933 #endif
934     tf->Unref();
936 return 0;
939 /* Helper functions */
941 void
942 PrintCairoPDF::print_bpath(cairo_t *cr, NArtBpath const *bp)
944     cairo_new_path(cr);
945     bool closed = false;
946     while (bp->code != NR_END) {
947         switch (bp->code) {
948             case NR_MOVETO:
949                 if (closed) {
950                     cairo_close_path(cr);
951                 }
952                 closed = true;
953                 cairo_move_to(cr, bp->x3, bp->y3);
954                 break;
955             case NR_MOVETO_OPEN:
956                 if (closed) {
957                     cairo_close_path(cr);
958                 }
959                 closed = false;
960                 cairo_move_to(cr, bp->x3, bp->y3);
961                 break;
962             case NR_LINETO:
963                 cairo_line_to(cr, bp->x3, bp->y3);
964                 break;
965             case NR_CURVETO:
966                 cairo_curve_to(cr, bp->x1, bp->y1, bp->x2, bp->y2, bp->x3, bp->y3);
967                 break;
968             default:
969                 break;
970         }
971         bp += 1;
972     }
973     if (closed) {
974         cairo_close_path(cr);
975     }
978 static void
979 _concat_transform(cairo_t *cr, double xx, double yx, double xy, double yy, double x0, double y0)
981     cairo_matrix_t matrix;
983     cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0); 
984     cairo_transform(cr, &matrix);
987 static cairo_status_t
988 _write_callback(void *closure, const unsigned char *data, unsigned int length)
990     size_t written;
991     FILE *file = (FILE*)closure;
993     written = fwrite (data, 1, length, file);
995     if (written == length)
996         return CAIRO_STATUS_SUCCESS;
997     else
998         return CAIRO_STATUS_WRITE_ERROR;
1001 bool
1002 PrintCairoPDF::textToPath(Inkscape::Extension::Print * ext)
1004     return ext->get_param_bool("textToPath");
1007 #include "clear-n_.h"
1009 void
1010 PrintCairoPDF::init(void)
1012     /* PDF out */
1013     (void) Inkscape::Extension::build_from_mem(
1014         "<inkscape-extension>\n"
1015         "<name>" N_("PDF Print") "</name>\n"
1016         "<id>" SP_MODULE_KEY_PRINT_CAIRO_PDF "</id>\n"
1017         "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1018         "<param name=\"resolution\" type=\"string\">72</param>\n"
1019         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1020         "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1021         "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1022         "<print/>\n"
1023         "</inkscape-extension>", new PrintCairoPDF());
1027 }  /* namespace Internal */
1028 }  /* namespace Extension */
1029 }  /* namespace Inkscape */
1031 /* End of GNU GPL code */
1034 /*
1035   Local Variables:
1036   mode:c++
1037   c-file-style:"stroustrup"
1038   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1039   indent-tabs-mode:nil
1040   fill-column:99
1041   End:
1042 */
1043 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :