Code

patch to fix multiple ps and pdf problems by Ulf Erikson
[inkscape.git] / src / extension / internal / ps.cpp
1 #define __SP_PS_C__
3 /** \file
4  * PostScript printing.
5  */
6 /*
7  * Authors:
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * Basic printing code, EXCEPT image and
12  * ascii85 filter is in public domain
13  *
14  * Image printing and Ascii85 filter:
15  *
16  * Copyright (C) 1995 Spencer Kimball and Peter Mattis
17  * Copyright (C) 1997-98 Peter Kirchgessner
18  * George White <aa056@chebucto.ns.ca>
19  * Austin Donnelly <austin@gimp.org>
20  *
21  * Licensed under GNU GPL
22  */
24 /* Plain Print */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #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 "ps.h"
59 #include "extension/system.h"
60 #include "extension/print.h"
62 #include "io/sys.h"
64 namespace Inkscape {
65 namespace Extension {
66 namespace Internal {
68 PrintPS::PrintPS() :
69     _stream(NULL),
70     _dpi(72),
71     _bitmap(false)
72 {
73 }
75 PrintPS::~PrintPS(void)
76 {
77     /* fixme: should really use pclose for popen'd streams */
78     if (_stream) fclose(_stream);
80     /* restore default signal handling for SIGPIPE */
81 #if !defined(_WIN32) && !defined(__WIN32__)
82     (void) signal(SIGPIPE, SIG_DFL);
83 #endif
85     return;
86 }
88 unsigned int
89 PrintPS::setup(Inkscape::Extension::Print * mod)
90 {
91     static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
93 #ifdef TED
94     Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
95 #endif
97     unsigned int ret = FALSE;
99     /* Create dialog */
100     GtkTooltips *tt = gtk_tooltips_new();
101     g_object_ref((GObject *) tt);
102     gtk_object_sink((GtkObject *) tt);
104     GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
105 //            SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
106             NULL,
107             (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
108             GTK_STOCK_CANCEL,
109             GTK_RESPONSE_CANCEL,
110             GTK_STOCK_PRINT,
111             GTK_RESPONSE_OK,
112             NULL);
114     gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
116     GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
117     gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
118     /* Print properties frame */
119     GtkWidget *f = gtk_frame_new(_("Print properties"));
120     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
121     GtkWidget *vb = gtk_vbox_new(FALSE, 4);
122     gtk_container_add(GTK_CONTAINER(f), vb);
123     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
124     /* Print type */
125     bool const p2bm = mod->get_param_bool("bitmap");
126     GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PostScript operators"));
127     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
128                          _("Use PostScript vector operators. The resulting image is usually smaller "
129                            "in file size and can be arbitrarily scaled, but alpha transparency "
130                            "and patterns will be lost."), NULL);
131     if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
132     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
133     rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
134     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
135                          _("Print everything as bitmap. The resulting image is usually larger "
136                            "in file size and cannot be arbitrarily scaled without quality loss, "
137                            "but all objects will be rendered exactly as displayed."), NULL);
138     if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
139     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
140     /* Resolution */
141     GtkWidget *hb = gtk_hbox_new(FALSE, 4);
142     gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
143     GtkWidget *combo = gtk_combo_new();
144     gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
145     gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
146     gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
147     gtk_widget_set_size_request(combo, 64, -1);
148     gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
149                          _("Preferred resolution (dots per inch) of bitmap"), NULL);
150     /* Setup strings */
151     GList *sl = NULL;
152     for (unsigned i = 0; pdr[i] != NULL; i++) {
153         sl = g_list_prepend(sl, (gpointer) pdr[i]);
154     }
155     sl = g_list_reverse(sl);
156     gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
157     g_list_free(sl);
158     if (1) {
159         gchar const *val = mod->get_param_string("resolution");
160         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
161     }
162     gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
163     GtkWidget *l = gtk_label_new(_("Resolution:"));
164     gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
166     /* Print destination frame */
167     f = gtk_frame_new(_("Print destination"));
168     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
169     vb = gtk_vbox_new(FALSE, 4);
170     gtk_container_add(GTK_CONTAINER(f), vb);
171     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
173     l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
174                         "leave empty to use the system default printer.\n"
175                         "Use '> filename' to print to file.\n"
176                         "Use '| prog arg...' to pipe to a program."));
177     gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
179     GtkWidget *e = gtk_entry_new();
180     if (1) {
181         gchar const *val = mod->get_param_string("destination");
182         gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
183                                            ? val
184                                            : "" ));
185     }
186     gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
188     // pressing enter in the destination field is the same as clicking Print:
189     gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
191     gtk_widget_show_all(vbox);
193     int const response = gtk_dialog_run(GTK_DIALOG(dlg));
195     g_object_unref((GObject *) tt);
197     if (response == GTK_RESPONSE_OK) {
198         gchar const *fn;
199         char const *sstr;
201         _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
202         sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
203         _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
204         /* Arrgh, have to do something */
205         fn = gtk_entry_get_text(GTK_ENTRY(e));
206         /* skip leading whitespace, bug #1068483 */
207         while (fn && *fn==' ') { fn++; }
208         /* g_print("Printing to %s\n", fn); */
210         mod->set_param_bool("bitmap", _bitmap);
211         mod->set_param_string("resolution", (gchar *)sstr);
212         mod->set_param_string("destination", (gchar *)fn);
213         ret = TRUE;
214     }
216     gtk_widget_destroy(dlg);
218     return ret;
221 unsigned int
222 PrintPS::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
224     gboolean epsexport = false;
226     _latin1_encoded_fonts.clear();
227     _newlatin1font_proc_defined = false;
229     FILE *osf = NULL;
230     FILE *osp = NULL;
232     gsize bytesRead = 0;
233     gsize bytesWritten = 0;
234     GError *error = NULL;
235     gchar const *utf8_fn = mod->get_param_string("destination");
236     gchar *local_fn = g_filename_from_utf8( utf8_fn,
237                                             -1,  &bytesRead,  &bytesWritten, &error);
238     gchar const *fn = local_fn;
240     /* TODO: Replace the below fprintf's with something that does the right thing whether in
241      * gui or batch mode (e.g. --print=blah).  Consider throwing an exception: currently one of
242      * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
243      * return code.
244      */
245     if (fn != NULL) {
246         if (*fn == '|') {
247             fn += 1;
248             while (isspace(*fn)) fn += 1;
249 #ifndef WIN32
250             osp = popen(fn, "w");
251 #else
252             osp = _popen(fn, "w");
253 #endif
254             if (!osp) {
255                 fprintf(stderr, "inkscape: popen(%s): %s\n",
256                         fn, strerror(errno));
257                 return 0;
258             }
259             _stream = osp;
260         } else if (*fn == '>') {
261             fn += 1;
262             epsexport = g_str_has_suffix(fn,".eps");
263             while (isspace(*fn)) fn += 1;
264             Inkscape::IO::dump_fopen_call(fn, "K");
265             osf = Inkscape::IO::fopen_utf8name(fn, "w+");
266             if (!osf) {
267                 fprintf(stderr, "inkscape: fopen(%s): %s\n",
268                         fn, strerror(errno));
269                 return 0;
270             }
271             _stream = osf;
272         } else {
273             /* put cwd stuff in here */
274             gchar *qn = ( *fn
275                           ? g_strdup_printf("lpr -P %s", fn)  /* FIXME: quote fn */
276                           : g_strdup("lpr") );
277 #ifndef WIN32
278             osp = popen(qn, "w");
279 #else
280             osp = _popen(qn, "w");
281 #endif
282             if (!osp) {
283                 fprintf(stderr, "inkscape: popen(%s): %s\n",
284                         qn, strerror(errno));
285                 return 0;
286             }
287             g_free(qn);
288             _stream = osp;
289         }
290     }
292     g_free(local_fn);
294     if (_stream) {
295         /* fixme: this is kinda icky */
296 #if !defined(_WIN32) && !defined(__WIN32__)
297         (void) signal(SIGPIPE, SIG_IGN);
298 #endif
299     }
301     int const res = fprintf(_stream, ( epsexport
302                                        ? "%%!PS-Adobe-3.0 EPSF-3.0\n"
303                                        : "%%!PS-Adobe-3.0\n" ));
304     /* flush this to test output stream as early as possible */
305     if (fflush(_stream)) {
306         /*g_print("caught error in sp_module_print_plain_begin\n");*/
307         if (ferror(_stream)) {
308             g_print("Error %d on output stream: %s\n", errno,
309                     g_strerror(errno));
310         }
311         g_print("Printing failed\n");
312         /* fixme: should use pclose() for pipes */
313         fclose(_stream);
314         _stream = NULL;
315         fflush(stdout);
316         return 0;
317     }
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     bool   pageLandscape;
326     pageBoundingBox = mod->get_param_bool("pageBoundingBox");
327     // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
328     if (pageBoundingBox) {
329         d.x0 = d.y0 = 0;
330         d.x1 = ceil(_width);
331         d.y1 = ceil(_height);
332     } else {
333         SPItem* doc_item = SP_ITEM(sp_document_root(doc));
334         sp_item_invoke_bbox(doc_item, &d, sp_item_i2r_affine(doc_item), TRUE);
335         // convert from px to pt
336         d.x0 *= PT_PER_PX;
337         d.x1 *= PT_PER_PX;
338         d.y0 *= PT_PER_PX;
339         d.y1 *= PT_PER_PX;
340     }
342     Inkscape::SVGOStringStream os;
343     if (res >= 0) {
345         os << "%%Creator: " << PACKAGE_STRING << "\n";
346         // This will become problematic if inkscape gains the
347         // ability to handle multi paged documents. If this is
348         // the case the %%Orientation: comments should be
349         // renamed to %%PageOrientation: and moved to the
350         // respective pages.
351         os << "%%Pages: 1\n";
353         // 2004 Dec 10, BFC:
354         // The point of the following code is (1) to do the thing that's expected by users
355         // who have done File>New>A4_landscape or ...letter_landscape (i.e., rotate
356         // the output), while (2) not messing up users who simply want their output wider
357         // than it is tall (e.g., small figures for inclusion in LaTeX).
358         // The original patch by WQ only had the w>h condition.
359         {
360              double w = (d.x1 - d.x0); // width and height of bounding box, in pt
361              double h = (d.y1 - d.y0);
362              pageLandscape = (
363                  (w > 0. && h > 0.) // empty documents fail this sanity check, have w<0, h<0
364                  && (w > h)   // implies, but does not prove, the user wanted landscape
365                  && (w > 600) // approximate maximum printable width of an A4
366                  && (!epsexport) // eps should always be portrait
367              )
368              ? true : false;
369         }
371         if (pageLandscape) {
372             os << "%%Orientation: Landscape\n";
373             os << "%%BoundingBox: " << (int) (_height - d.y1) << " "
374                << (int) d.x0 << " "
375                << (int) ceil(_height - d.y0) << " "
376                << (int) ceil(d.x1) << "\n";
377             // According to Mike Sweet (the author of CUPS)
378             // HiResBoundingBox is only appropriate
379             // for EPS files. This means that we should
380             // distinguish if we export to ps or eps here.
381             // FIXME: I couldn't find HiResBoundingBox in the PS
382             // reference manual, so I guess we should skip
383             // it.
384             os << "%%HiResBoundingBox: " << (_height - d.y1) << " "
385                << d.x0 << " "
386                << (_height - d.y0) << " "
387                << d.x1 << "\n";
388             os << "%%DocumentMedia: plain "
389                << (int) ceil(_height) << " "
390                << (int) ceil(_width) << " "
391                << "0 () ()\n";
392         } else {
393             os << "%%Orientation: Portrait\n";
394             os << "%%BoundingBox: " << (int) d.x0 << " "
395                << (int) d.y0 << " "
396                << (int) ceil(d.x1) << " "
397                << (int) ceil(d.y1) << "\n";
398             os << "%%HiResBoundingBox: " << d.x0 << " "
399                << d.y0 << " "
400                << d.x1 << " "
401                << d.y1 << "\n";
402             os << "%%DocumentMedia: plain "
403                << (int) ceil(_width) << " "
404                << (int) ceil(_height) << " "
405                << "0 () ()\n";
406         }
408         os << "%%EndComments\n";
409         // This will become problematic if we print multi paged documents:
410         os << "%%Page: 1 1\n";
412         if (pageLandscape) {
413             os << "90 rotate\n";
414             if (_bitmap) {
415                 os << "0 " << (int) -ceil(_height) << " translate\n";
416             }
417         } else {
418             if (!_bitmap) {
419                 os << "0 " << (int) ceil(_height) << " translate\n";
420             }
421         }
423         if (!_bitmap) {
424             os << PT_PER_PX << " " << -PT_PER_PX << " scale\n";
425             // from now on we can output px, but they will be treated as pt
426         }
427     }
429     /* FIXME: This function is declared to return unsigned, whereas fprintf returns a signed int *
430      * that can be zero if the first fprintf failed (os is empty) or "negative" (i.e. very positive
431      * in unsigned int interpretation) if the first fprintf failed but this one succeeds, or
432      * positive if both succeed. */
433     return fprintf(_stream, "%s", os.str().c_str());
436 unsigned int
437 PrintPS::finish(Inkscape::Extension::Print *mod)
439     if (!_stream) return 0;
441     if (_bitmap) {
442         double const dots_per_pt = _dpi / PT_PER_IN;
444         double const x0 = 0.0;
445         double const y0 = 0.0;
446         double const x1 = x0 + _width;
447         double const y1 = y0 + _height;
449         /* Bitmap width/height in bitmap dots. */
450         int const width = (int) (_width * dots_per_pt + 0.5);
451         int const height = (int) (_height * dots_per_pt + 0.5);
453         NRMatrix affine;
454         affine.c[0] = width / ((x1 - x0) * PX_PER_PT);
455         affine.c[1] = 0.0;
456         affine.c[2] = 0.0;
457         affine.c[3] = height / ((y1 - y0) * PX_PER_PT);
458         affine.c[4] = -affine.c[0] * x0;
459         affine.c[5] = -affine.c[3] * y0;
461         nr_arena_item_set_transform(mod->root, &affine);
463         guchar *const px = g_new(guchar, 4 * width * 64);
465         for (int y = 0; y < height; y += 64) {
466             /* Set area of interest. */
467             NRRectL bbox;
468             bbox.x0 = 0;
469             bbox.y0 = y;
470             bbox.x1 = width;
471             bbox.y1 = MIN(height, y + 64);
473             /* Update to renderable state. */
474             NRGC gc(NULL);
475             nr_matrix_set_identity(&gc.transform);
476             nr_arena_item_invoke_update(mod->root, &bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
477             /* Render */
478             /* This should take guchar* instead of unsigned char*) */
479             NRPixBlock pb;
480             nr_pixblock_setup_extern(&pb, NR_PIXBLOCK_MODE_R8G8B8A8N,
481                                      bbox.x0, bbox.y0, bbox.x1, bbox.y1,
482                                      (guchar*)px, 4 * width, FALSE, FALSE);
483             memset(px, 0xff, 4 * width * 64);
484             nr_arena_item_invoke_render(mod->root, &bbox, &pb, 0);
485             /* Blitter goes here */
486             NRMatrix imgt;
487             imgt.c[0] = (bbox.x1 - bbox.x0) / dots_per_pt;
488             imgt.c[1] = 0.0;
489             imgt.c[2] = 0.0;
490             imgt.c[3] = (bbox.y1 - bbox.y0) / dots_per_pt;
491             imgt.c[4] = 0.0;
492             imgt.c[5] = _height - y / dots_per_pt - (bbox.y1 - bbox.y0) / dots_per_pt;
494             print_image(_stream, px, bbox.x1 - bbox.x0, bbox.y1 - bbox.y0, 4 * width, &imgt);
495         }
497         g_free(px);
498     }
500     fprintf(_stream, "showpage\n");
501     int const res = fprintf(_stream, "%%%%EOF\n");
503     /* Flush stream to be sure. */
504     (void) fflush(_stream);
506     /* fixme: should really use pclose for popen'd streams */
507     fclose(_stream);
508     _stream = 0;
509     _latin1_encoded_fonts.clear();
511     return res;
514 unsigned int
515 PrintPS::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
517     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
518     if (_bitmap) return 0;
520     Inkscape::SVGOStringStream os;
521     os << "gsave [" << transform->c[0] << " "
522        << transform->c[1] << " "
523        << transform->c[2] << " "
524        << transform->c[3] << " "
525        << transform->c[4] << " "
526        << transform->c[5] << "] concat\n";
528     return fprintf(_stream, "%s", os.str().c_str());
531 unsigned int
532 PrintPS::release(Inkscape::Extension::Print *mod)
534     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
535     if (_bitmap) return 0;
537     return fprintf(_stream, "grestore\n");
540 unsigned int
541 PrintPS::comment(Inkscape::Extension::Print *mod, char const *comment)
543     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
544     if (_bitmap) return 0;
546     return fprintf(_stream, "%%! %s\n",comment);
549 void
550 PrintPS::print_fill_style(SVGOStringStream &os, SPStyle const *const style, NRRect const *pbox)
552     g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
553                       || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
554                            && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
556     if (style->fill.type == SP_PAINT_TYPE_COLOR) {
557         float rgb[3];
558         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
560         os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
562     } else {
563         g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
564                   && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
566         if (SP_IS_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style))) {
568             SPLinearGradient *lg = SP_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style));
569             NR::Point p1 (lg->x1.computed, lg->y1.computed);
570             NR::Point p2 (lg->x2.computed, lg->y2.computed);
571             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
572                 // convert to userspace
573                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
574                 p1 *= bbox2user;
575                 p2 *= bbox2user;
576             }
578             os << "<<\n/ShadingType 2\n/ColorSpace /DeviceRGB\n";
579             os << "/Coords [" << p1[NR::X] << " " << p1[NR::Y] << " " << p2[NR::X] << " " << p2[NR::Y] <<"]\n";
580             os << "/Extend [true true]\n";
581             os << "/Domain [0 1]\n";
582             os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
584             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
585             for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
586                 float rgb[3];
587                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
588                 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
589                 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
590                 sp_color_get_rgb_floatv(&lg->vector.stops[i+1].color, rgb);
591                 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
592                 os << "/N 1\n>>\n";
593             }
594             os << "]\n/Domain [0 1]\n";
595             os << "/Bounds [ ";
596             for (unsigned i = 0; i + 2 < lg->vector.stops.size(); i++) {
597                 os << lg->vector.stops[i+1].offset <<" ";
598             }
599             os << "]\n";
600             os << "/Encode [ ";
601             for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
602                 os << "0 1 ";
603             }
604             os << "]\n";
605             os << ">>\n>>\n";
607         } else if (SP_IS_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style))) {
609             SPRadialGradient *rg = SP_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style));
610             NR::Point c(rg->cx.computed, rg->cy.computed);
611             NR::Point f(rg->fx.computed, rg->fy.computed);
612             double r = rg->r.computed;
613             if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
614                 // convert to userspace
615                 NR::Matrix const bbox2user(pbox->x1 - pbox->x0, 0,
616                                            0, pbox->y1 - pbox->y0,
617                                            pbox->x0, pbox->y0);
618                 c *= bbox2user;
619                 f *= bbox2user;
620                 r *= bbox2user.expansion();
621             }
623             os << "<<\n/ShadingType 3\n/ColorSpace /DeviceRGB\n";
624             os << "/Coords ["<< f[NR::X] <<" "<< f[NR::Y] <<" 0 "<< c[NR::X] <<" "<< c[NR::Y] <<" "<< r <<"]\n";
625             os << "/Extend [true true]\n";
626             os << "/Domain [0 1]\n";
627             os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
629             sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
630             for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
631                 float rgb[3];
632                 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
633                 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
634                 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
635                 sp_color_get_rgb_floatv(&rg->vector.stops[i+1].color, rgb);
636                 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
637                 os << "/N 1\n>>\n";
638             }
639             os << "]\n/Domain [0 1]\n";
640             os << "/Bounds [ ";
641             for (unsigned i = 0; i + 2 < rg->vector.stops.size(); i++) {
642                 os << rg->vector.stops[i+1].offset << " ";
643             }
644             os << "]\n";
645             os << "/Encode [ ";
646             for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
647                 os << "0 1 ";
648             }
649             os << "]\n";
650             os << ">>\n>>\n";
651         }
652     }
655 void
656 PrintPS::print_stroke_style(SVGOStringStream &os, SPStyle const *style)
658     float rgb[3];
659     sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
661     os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
663     // There are rare cases in which for a solid line stroke_dasharray_set is true. To avoid
664     // invalid PS-lines such as "[0.0000000 0.0000000] 0.0000000 setdash", which should be "[] 0 setdash",
665     // we first check if all components of stroke_dash.dash are 0.
666     bool LineSolid = true;
667     if (style->stroke_dash.n_dash   &&
668         style->stroke_dash.dash       )
669     {
670         int i = 0;
671         while (LineSolid && (i < style->stroke_dash.n_dash)) {
672                 if (style->stroke_dash.dash[i] > 0.00000001)
673                     LineSolid = false;
674                 i++;
675         }
676         if (!LineSolid) {
677             os << "[";
678             for (i = 0; i < style->stroke_dash.n_dash; i++) {
679                 if (i > 0) {
680                     os << " ";
681                 }
682                 os << style->stroke_dash.dash[i];
683             }
684             os << "] " << style->stroke_dash.offset << " setdash\n";
685         } else {
686             os << "[] 0 setdash\n";
687         }
688     } else {
689         os << "[] 0 setdash\n";
690     }
692     os << style->stroke_width.computed << " setlinewidth\n";
693     os << style->stroke_linejoin.computed << " setlinejoin\n";
694     os << style->stroke_linecap.computed << " setlinecap\n";
698 unsigned int
699 PrintPS::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
700               NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
702     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
703     if (_bitmap) return 0;
705     if ( style->fill.type == SP_PAINT_TYPE_COLOR
706          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
707               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
708     {
709         Inkscape::SVGOStringStream os;
711         os << "gsave\n";
713         print_fill_style(os, style, pbox);
715         print_bpath(os, bpath->path);
717         if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
718             if (style->fill.type == SP_PAINT_TYPE_COLOR) {
719                 os << "eofill\n";
720             } else {
721                 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
722                           && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
723                 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
724                 os << "eoclip\n";
725                 if (g->gradientTransform_set) {
726                     os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
727                         << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
728                         << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
729                 }
730                 os << "shfill\n";
731                 if (g->gradientTransform_set) {
732                     os << "grestore\n";
733                 }
734             }
735         } else {
736             if (style->fill.type == SP_PAINT_TYPE_COLOR) {
737                 os << "fill\n";
738             } else {
739                 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
740                           && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
741                 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
742                 os << "clip\n";
743                 if (g->gradientTransform_set) {
744                     os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
745                         << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
746                         << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
747                 }
748                 os << "shfill\n";
749                 if (g->gradientTransform_set) {
750                     os << "grestore\n";
751                 }
752             }
753         }
755         os << "grestore\n";
757         fprintf(_stream, "%s", os.str().c_str());
758     }
760     return 0;
764 unsigned int
765 PrintPS::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
766                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
768     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
769     if (_bitmap) return 0;
771     if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
772         Inkscape::SVGOStringStream os;
774         print_stroke_style(os, style);
776         print_bpath(os, bpath->path);
778         os << "stroke\n";
780         fprintf(_stream, "%s", os.str().c_str());
781     }
783     return 0;
786 unsigned int
787 PrintPS::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
788                NRMatrix const *transform, SPStyle const *style)
790     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
791     if (_bitmap) return 0;
793     return print_image(_stream, px, w, h, rs, transform);
796 char const *
797 PrintPS::PSFontName(SPStyle const *style)
799     font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
801     char const *n;
802     char name_buf[256];
804     if (tf) {
805         tf->PSName(name_buf, sizeof(name_buf));
806         n = name_buf;
807         tf->Unref();
808     } else {
809         // this system does not have this font, so just use the name from SVG in the hope that PS interpreter will make sense of it
810         bool i = (style->font_style.value == SP_CSS_FONT_STYLE_ITALIC);
811         bool o = (style->font_style.value == SP_CSS_FONT_STYLE_OBLIQUE);
812         bool b = (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) ||
813             (style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
815         n = g_strdup_printf("%s%s%s%s",
816                             g_strdelimit(style->text->font_family.value, " ", '-'),
817                             (b || i || o) ? "-" : "",
818                             (b) ? "Bold" : "",
819                             (i) ? "Italic" : ((o) ? "Oblique" : "") );
820     }
822     return g_strdup(n);
826 unsigned int
827 PrintPS::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
828               SPStyle const *const style)
830     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
831     if (_bitmap) return 0;
833     Inkscape::SVGOStringStream os;
835     // Escape chars
836     Inkscape::SVGOStringStream escaped_text;
837     escaped_text << std::oct;
838     for (gchar const *p_text = text ; *p_text ; p_text = g_utf8_next_char(p_text)) {
839         gunichar const c = g_utf8_get_char(p_text);
840         if (c == '\\' || c == ')' || c == '(')
841             escaped_text << '\\' << static_cast<char>(c);
842         else if (c >= 0x80)
843             escaped_text << '\\' << c;
844         else
845             escaped_text << static_cast<char>(c);
846     }
848     os << "gsave\n";
850     // set font
851     char const *fn = PSFontName(style);
852     if (_latin1_encoded_fonts.find(fn) == _latin1_encoded_fonts.end()) {
853         if (!_newlatin1font_proc_defined) {
854             // input: newfontname, existingfontname
855             // output: new font object, also defined to newfontname
856             os << "/newlatin1font "         // name of the proc
857                   "{findfont dup length dict copy "     // load the font and create a copy of it
858                   "dup /Encoding ISOLatin1Encoding put "     // change the encoding in the copy
859                   "definefont} def\n";      // create the new font and leave it on the stack, define the proc
860             _newlatin1font_proc_defined = true;
861         }
862         os << "/" << fn << "-ISOLatin1 /" << fn << " newlatin1font\n";
863         _latin1_encoded_fonts.insert(fn);
864     } else
865         os << "/" << fn << "-ISOLatin1 findfont\n";
866     os << style->font_size.computed << " scalefont\n";
867     os << "setfont\n";
868     g_free((void *) fn);
870     if ( style->fill.type == SP_PAINT_TYPE_COLOR
871          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
872               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
873     {
874         // set fill style
875         print_fill_style(os, style, NULL);
876         // FIXME: we don't know the pbox of text, so have to pass NULL. This means gradients with
877         // bbox units won't work with text. However userspace gradients don't work with text either
878         // (text is black) for some reason.
880         os << "newpath\n";
881         os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
882         os << "(" << escaped_text.str() << ") show\n";
883     }
885     if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
887         // set stroke style
888         print_stroke_style(os, style);
890         // paint stroke
891         os << "newpath\n";
892         os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
893         os << "(" << escaped_text.str() << ") false charpath stroke\n";
894     }
896     os << "grestore\n";
898     fprintf(_stream, "%s", os.str().c_str());
900     return 0;
905 /* PostScript helpers */
907 void
908 PrintPS::print_bpath(SVGOStringStream &os, NArtBpath const *bp)
910     os << "newpath\n";
911     bool closed = false;
912     while (bp->code != NR_END) {
913         switch (bp->code) {
914             case NR_MOVETO:
915                 if (closed) {
916                     os << "closepath\n";
917                 }
918                 closed = true;
919                 os << bp->x3 << " " << bp->y3 << " moveto\n";
920                 break;
921             case NR_MOVETO_OPEN:
922                 if (closed) {
923                     os << "closepath\n";
924                 }
925                 closed = false;
926                 os << bp->x3 << " " << bp->y3 << " moveto\n";
927                 break;
928             case NR_LINETO:
929                 os << bp->x3 << " " << bp->y3 << " lineto\n";
930                 break;
931             case NR_CURVETO:
932                 os << bp->x1 << " " << bp->y1 << " "
933                    << bp->x2 << " " << bp->y2 << " "
934                    << bp->x3 << " " << bp->y3 << " curveto\n";
935                 break;
936             default:
937                 break;
938         }
939         bp += 1;
940     }
941     if (closed) {
942         os << "closepath\n";
943     }
946 /* The following code is licensed under GNU GPL.
947 ** The packbits, ascii85 and imaging printing code
948 ** is from the gimp's postscript.c.
949 */
951 /**
952 * \param nin Number of bytes of source data.
953 * \param src Source data.
954 * \param nout Number of output bytes.
955 * \param dst Buffer for output.
956 */
957 void
958 PrintPS::compress_packbits(int nin,
959                            guchar *src,
960                            int *nout,
961                            guchar *dst)
964     register guchar c;
965     int nrepeat, nliteral;
966     guchar *run_start;
967     guchar *start_dst = dst;
968     guchar *last_literal = NULL;
970     for (;;) {
971         if (nin <= 0) break;
973         run_start = src;
974         c = *run_start;
976         /* Search repeat bytes */
977         if ((nin > 1) && (c == src[1])) {
978             nrepeat = 1;
979             nin -= 2;
980             src += 2;
981             while ((nin > 0) && (c == *src)) {
982                 nrepeat++;
983                 src++;
984                 nin--;
985                 if (nrepeat == 127) break; /* Maximum repeat */
986             }
988             /* Add two-byte repeat to last literal run ? */
989             if ( (nrepeat == 1)
990                  && (last_literal != NULL) && (((*last_literal)+1)+2 <= 128) )
991             {
992                 *last_literal += 2;
993                 *(dst++) = c;
994                 *(dst++) = c;
995                 continue;
996             }
998             /* Add repeat run */
999             *(dst++) = (guchar)((-nrepeat) & 0xff);
1000             *(dst++) = c;
1001             last_literal = NULL;
1002             continue;
1003         }
1004         /* Search literal bytes */
1005         nliteral = 1;
1006         nin--;
1007         src++;
1009         for (;;) {
1010             if (nin <= 0) break;
1012             if ((nin >= 2) && (src[0] == src[1])) /* A two byte repeat ? */
1013                 break;
1015             nliteral++;
1016             nin--;
1017             src++;
1018             if (nliteral == 128) break; /* Maximum literal run */
1019         }
1021         /* Could be added to last literal run ? */
1022         if ((last_literal != NULL) && (((*last_literal)+1)+nliteral <= 128)) {
1023             *last_literal += nliteral;
1024         } else {
1025             last_literal = dst;
1026             *(dst++) = (guchar)(nliteral-1);
1027         }
1028         while (nliteral-- > 0) *(dst++) = *(run_start++);
1029     }
1030     *nout = dst - start_dst;
1033 void
1034 PrintPS::ascii85_init(void)
1036     ascii85_len = 0;
1037     ascii85_linewidth = 0;
1040 void
1041 PrintPS::ascii85_flush(SVGOStringStream &os)
1043     char c[5];
1044     bool const zero_case = (ascii85_buf == 0);
1045     static int const max_linewidth = 75;
1047     for (int i = 4; i >= 0; i--) {
1048         c[i] = (ascii85_buf % 85) + '!';
1049         ascii85_buf /= 85;
1050     }
1051     /* check for special case: "!!!!!" becomes "z", but only if not
1052      * at end of data. */
1053     if (zero_case && (ascii85_len == 4)) {
1054         if (ascii85_linewidth >= max_linewidth) {
1055             os << '\n';
1056             ascii85_linewidth = 0;
1057         }
1058         os << 'z';
1059         ascii85_linewidth++;
1060     } else {
1061         for (int i = 0; i < ascii85_len+1; i++) {
1062             if ((ascii85_linewidth >= max_linewidth) && (c[i] != '%')) {
1063                 os << '\n';
1064                 ascii85_linewidth = 0;
1065             }
1066             os << c[i];
1067             ascii85_linewidth++;
1068         }
1069     }
1071     ascii85_len = 0;
1072     ascii85_buf = 0;
1075 inline void
1076 PrintPS::ascii85_out(guchar byte, SVGOStringStream &os)
1078     if (ascii85_len == 4)
1079         ascii85_flush(os);
1081     ascii85_buf <<= 8;
1082     ascii85_buf |= byte;
1083     ascii85_len++;
1086 void
1087 PrintPS::ascii85_nout(int n, guchar *uptr, SVGOStringStream &os)
1089     while (n-- > 0) {
1090         ascii85_out(*uptr, os);
1091         uptr++;
1092     }
1095 void
1096 PrintPS::ascii85_done(SVGOStringStream &os)
1098     if (ascii85_len) {
1099         /* zero any unfilled buffer portion, then flush */
1100         ascii85_buf <<= (8 * (4-ascii85_len));
1101         ascii85_flush(os);
1102     }
1104     os << "~>\n";
1107 unsigned int
1108 PrintPS::print_image(FILE *ofp, guchar *px, unsigned int width, unsigned int height, unsigned int rs,
1109                      NRMatrix const *transform)
1111     Inkscape::SVGOStringStream os;
1113     os << "gsave\n";
1115     os << "[" << transform->c[0] << " "
1116        << transform->c[1] << " "
1117        << transform->c[2] << " "
1118        << transform->c[3] << " "
1119        << transform->c[4] << " "
1120        << transform->c[5] << "] concat\n";
1122     /* Write read image procedure */
1123     os << "<<\n";
1124     os << "  /ImageType 3\n";
1125     os << "  /InterleaveType 1\n";
1127     os << "  /MaskDict\n";
1128     os << "  <<\n";
1129     os << "    /ImageType 1\n";
1130     os << "    /Width " << width << "\n";
1131     os << "    /Height " << height << "\n";
1132     os << "    /ImageMatrix "
1133        << "[" << transform->c[0] << " "
1134        << transform->c[1] << " "
1135        << transform->c[2] << " "
1136        << transform->c[3] << " "
1137        << 0 << " "
1138        << height << "]\n";
1139     os << "    /BitsPerComponent 8\n";
1140     os << "    /Decode [1 0]\n";
1141     os << "  >>\n";
1143     os << "  /DataDict\n";
1144     os << "  <<\n";
1145     os << "    /ImageType 1\n";
1146     os << "    /Width " << width << "\n";
1147     os << "    /Height " << height << "\n";
1148     os << "    /ImageMatrix "
1149        << "[" << transform->c[0] << " "
1150        << transform->c[1] << " "
1151        << transform->c[2] << " "
1152        << transform->c[3] << " "
1153        << 0 << " "
1154        << height << "]\n";
1155     os << "    /DataSource currentfile /ASCII85Decode filter\n";
1156     os << "    /BitsPerComponent 8\n";
1157     os << "    /Decode [0 1 0 1 0 1]\n";
1158     os << "  >>\n";
1160     os << ">>\n";
1162     /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
1163     guchar *const packb = (guchar *)g_malloc((4*width * 105)/100+2);
1164     guchar *const plane = (guchar *)g_malloc(4*width);
1166     os << "image\n";
1168     ascii85_init();
1169     
1170     for (unsigned i = 0; i < height; i++) {
1171         guchar const *const src = px + i * rs;
1173         guchar const *src_ptr = src;
1174         guchar *plane_ptr = plane;
1175         for (unsigned j = 0; j < width; j++) {
1176             *(plane_ptr++) = *(src_ptr+3);
1177             *(plane_ptr++) = *(src_ptr+0);
1178             *(plane_ptr++) = *(src_ptr+1);
1179             *(plane_ptr++) = *(src_ptr+2);
1180             src_ptr += 4;
1181         }
1182         
1183         ascii85_nout(4*width, plane, os);
1184     }
1185     ascii85_done(os);
1187     g_free(packb);
1188     g_free(plane);
1190     os << "grestore\n";
1192     fprintf(ofp, "%s", os.str().c_str());
1194     return 0;
1197 bool
1198 PrintPS::textToPath(Inkscape::Extension::Print * ext)
1200     return ext->get_param_bool("textToPath");
1203 #include "clear-n_.h"
1205 void
1206 PrintPS::init(void)
1208     /* SVG in */
1209     (void) Inkscape::Extension::build_from_mem(
1210         "<inkscape-extension>\n"
1211         "<name>" N_("Postscript Print") "</name>\n"
1212         "<id>" SP_MODULE_KEY_PRINT_PS "</id>\n"
1213         "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1214         "<param name=\"resolution\" type=\"string\">72</param>\n"
1215         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1216         "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1217         "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1218         "<print/>\n"
1219         "</inkscape-extension>", new PrintPS());
1223 }  /* namespace Internal */
1224 }  /* namespace Extension */
1225 }  /* namespace Inkscape */
1227 /* End of GNU GPL code */
1230 /*
1231   Local Variables:
1232   mode:c++
1233   c-file-style:"stroustrup"
1234   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1235   indent-tabs-mode:nil
1236   fill-column:99
1237   End:
1238 */
1239 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :