Code

c814637c6165983b7e3ce9bfe39a8576c21c00be
[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 <gtk/gtkstock.h>
36 #include <gtk/gtkvbox.h>
37 #include <gtk/gtkframe.h>
38 #include <gtk/gtkradiobutton.h>
39 #include <gtk/gtkcombo.h>
40 #include <gtk/gtklabel.h>
41 #include <gtk/gtkentry.h>
42 #include <gtk/gtktooltips.h>
44 #include <glibmm/i18n.h>
45 #include "display/nr-arena-item.h"
46 #include "display/canvas-bpath.h"
47 #include "sp-item.h"
48 #include "style.h"
49 #include "sp-linear-gradient.h"
50 #include "sp-radial-gradient.h"
52 #include "libnrtype/font-instance.h"
53 #include "libnrtype/font-style-to-pos.h"
55 #include <unit-constants.h>
57 #include "ps.h"
58 #include "extension/system.h"
59 #include "extension/print.h"
61 #include "io/sys.h"
63 namespace Inkscape {
64 namespace Extension {
65 namespace Internal {
67 PrintPS::PrintPS() :
68     _stream(NULL),
69     _dpi(72),
70     _bitmap(false)
71 {
72 }
74 PrintPS::~PrintPS(void)
75 {
76     /* fixme: should really use pclose for popen'd streams */
77     if (_stream) fclose(_stream);
79     /* restore default signal handling for SIGPIPE */
80 #if !defined(_WIN32) && !defined(__WIN32__)
81     (void) signal(SIGPIPE, SIG_DFL);
82 #endif
84     return;
85 }
87 unsigned int
88 PrintPS::setup(Inkscape::Extension::Print * mod)
89 {
90     static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
92 #ifdef TED
93     Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
94 #endif
96     unsigned int ret = FALSE;
98     /* Create dialog */
99     GtkTooltips *tt = gtk_tooltips_new();
100     g_object_ref((GObject *) tt);
101     gtk_object_sink((GtkObject *) tt);
103     GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
104 //            SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
105             NULL,
106             (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
107             GTK_STOCK_CANCEL,
108             GTK_RESPONSE_CANCEL,
109             GTK_STOCK_PRINT,
110             GTK_RESPONSE_OK,
111             NULL);
113     gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
115     GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
116     gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
117     /* Print properties frame */
118     GtkWidget *f = gtk_frame_new(_("Print properties"));
119     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
120     GtkWidget *vb = gtk_vbox_new(FALSE, 4);
121     gtk_container_add(GTK_CONTAINER(f), vb);
122     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
123     /* Print type */
124     bool const p2bm = mod->get_param_bool("bitmap");
125     GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PostScript operators"));
126     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
127                          _("Use PostScript vector operators. The resulting image is usually smaller "
128                            "in file size and can be arbitrarily scaled, but alpha transparency "
129                            "and patterns will be lost."), NULL);
130     if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
131     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
132     rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
133     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
134                          _("Print everything as bitmap. The resulting image is usually larger "
135                            "in file size and cannot be arbitrarily scaled without quality loss, "
136                            "but all objects will be rendered exactly as displayed."), NULL);
137     if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
138     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
139     /* Resolution */
140     GtkWidget *hb = gtk_hbox_new(FALSE, 4);
141     gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
142     GtkWidget *combo = gtk_combo_new();
143     gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
144     gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
145     gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
146     gtk_widget_set_size_request(combo, 64, -1);
147     gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
148                          _("Preferred resolution (dots per inch) of bitmap"), NULL);
149     /* Setup strings */
150     GList *sl = NULL;
151     for (unsigned i = 0; pdr[i] != NULL; i++) {
152         sl = g_list_prepend(sl, (gpointer) pdr[i]);
153     }
154     sl = g_list_reverse(sl);
155     gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
156     g_list_free(sl);
157     if (1) {
158         gchar const *val = mod->get_param_string("resolution");
159         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
160     }
161     gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
162     GtkWidget *l = gtk_label_new(_("Resolution:"));
163     gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
165     /* Print destination frame */
166     f = gtk_frame_new(_("Print destination"));
167     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
168     vb = gtk_vbox_new(FALSE, 4);
169     gtk_container_add(GTK_CONTAINER(f), vb);
170     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
172     l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
173                         "leave empty to use the system default printer.\n"
174                         "Use '> filename' to print to file.\n"
175                         "Use '| prog arg...' to pipe to a program."));
176     gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
178     GtkWidget *e = gtk_entry_new();
179     if (1) {
180         gchar const *val = mod->get_param_string("destination");
181         gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
182                                            ? val
183                                            : "" ));
184     }
185     gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
187     // pressing enter in the destination field is the same as clicking Print:
188     gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
190     gtk_widget_show_all(vbox);
192     int const response = gtk_dialog_run(GTK_DIALOG(dlg));
194     g_object_unref((GObject *) tt);
196     if (response == GTK_RESPONSE_OK) {
197         gchar const *fn;
198         char const *sstr;
200         _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
201         sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
202         _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
203         /* Arrgh, have to do something */
204         fn = gtk_entry_get_text(GTK_ENTRY(e));
205         /* skip leading whitespace, bug #1068483 */
206         while (fn && *fn==' ') { fn++; }
207         /* g_print("Printing to %s\n", fn); */
209         mod->set_param_bool("bitmap", _bitmap);
210         mod->set_param_string("resolution", (gchar *)sstr);
211         mod->set_param_string("destination", (gchar *)fn);
212         ret = TRUE;
213     }
215     gtk_widget_destroy(dlg);
217     return ret;
220 unsigned int
221 PrintPS::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
223     gboolean epsexport = false;
225     _latin1_encoded_fonts.clear();
226     _newlatin1font_proc_defined = false;
228     FILE *osf = NULL;
229     FILE *osp = NULL;
231     gsize bytesRead = 0;
232     gsize bytesWritten = 0;
233     GError *error = NULL;
234     gchar const *utf8_fn = mod->get_param_string("destination");
235     gchar *local_fn = g_filename_from_utf8( utf8_fn,
236                                             -1,  &bytesRead,  &bytesWritten, &error);
237     gchar const *fn = local_fn;
239     /* TODO: Replace the below fprintf's with something that does the right thing whether in
240      * gui or batch mode (e.g. --print=blah).  Consider throwing an exception: currently one of
241      * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
242      * return code.
243      */
244     if (fn != NULL) {
245         if (*fn == '|') {
246             fn += 1;
247             while (isspace(*fn)) fn += 1;
248 #ifndef WIN32
249             osp = popen(fn, "w");
250 #else
251             osp = _popen(fn, "w");
252 #endif
253             if (!osp) {
254                 fprintf(stderr, "inkscape: popen(%s): %s\n",
255                         fn, strerror(errno));
256                 return 0;
257             }
258             _stream = osp;
259         } else if (*fn == '>') {
260             fn += 1;
261             epsexport = g_str_has_suffix(fn,".eps");
262             while (isspace(*fn)) fn += 1;
263             Inkscape::IO::dump_fopen_call(fn, "K");
264             osf = Inkscape::IO::fopen_utf8name(fn, "w+");
265             if (!osf) {
266                 fprintf(stderr, "inkscape: fopen(%s): %s\n",
267                         fn, strerror(errno));
268                 return 0;
269             }
270             _stream = osf;
271         } else {
272             /* put cwd stuff in here */
273             gchar *qn = ( *fn
274                           ? g_strdup_printf("lpr -P %s", fn)  /* FIXME: quote fn */
275                           : g_strdup("lpr") );
276 #ifndef WIN32
277             osp = popen(qn, "w");
278 #else
279             osp = _popen(qn, "w");
280 #endif
281             if (!osp) {
282                 fprintf(stderr, "inkscape: popen(%s): %s\n",
283                         qn, strerror(errno));
284                 return 0;
285             }
286             g_free(qn);
287             _stream = osp;
288         }
289     }
291     g_free(local_fn);
293     if (_stream) {
294         /* fixme: this is kinda icky */
295 #if !defined(_WIN32) && !defined(__WIN32__)
296         (void) signal(SIGPIPE, SIG_IGN);
297 #endif
298     }
300     int const res = fprintf(_stream, ( epsexport
301                                        ? "%%!PS-Adobe-3.0 EPSF-3.0\n"
302                                        : "%%!PS-Adobe-3.0\n" ));
303     /* flush this to test output stream as early as possible */
304     if (fflush(_stream)) {
305         /*g_print("caught error in sp_module_print_plain_begin\n");*/
306         if (ferror(_stream)) {
307             g_print("Error %d on output stream: %s\n", errno,
308                     g_strerror(errno));
309         }
310         g_print("Printing failed\n");
311         /* fixme: should use pclose() for pipes */
312         fclose(_stream);
313         _stream = NULL;
314         fflush(stdout);
315         return 0;
316     }
318     // width and height in pt
319     _width = sp_document_width(doc) * PT_PER_PX;
320     _height = sp_document_height(doc) * PT_PER_PX;
322     NRRect d;
323     bool   pageBoundingBox;
324     bool   pageLandscape;
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 = ceil(_width);
330         d.y1 = ceil(_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     }
341     Inkscape::SVGOStringStream os;
342     if (res >= 0) {
344         os << "%%Creator: " << PACKAGE_STRING << "\n";
345         // This will become problematic if inkscape gains the
346         // ability to handle multi paged documents. If this is
347         // the case the %%Orientation: comments should be
348         // renamed to %%PageOrientation: and moved to the
349         // respective pages.
350         os << "%%Pages: 1\n";
352         // 2004 Dec 10, BFC:
353         // The point of the following code is (1) to do the thing that's expected by users
354         // who have done File>New>A4_landscape or ...letter_landscape (i.e., rotate
355         // the output), while (2) not messing up users who simply want their output wider
356         // than it is tall (e.g., small figures for inclusion in LaTeX).
357         // The original patch by WQ only had the w>h condition.
358         {
359              double w = (d.x1 - d.x0); // width and height of bounding box, in pt
360              double h = (d.y1 - d.y0);
361              pageLandscape = (
362                  (w > 0. && h > 0.) // empty documents fail this sanity check, have w<0, h<0
363                  && (w > h)   // implies, but does not prove, the user wanted landscape
364                  && (w > 600) // approximate maximum printable width of an A4
365                  && (!epsexport) // eps should always be portrait
366              )
367              ? true : false;
368         }
370         if (pageLandscape) {
371             os << "%%Orientation: Landscape\n";
372             os << "%%BoundingBox: " << (int) (_height - d.y1) << " "
373                << (int) d.x0 << " "
374                << (int) ceil(_height - d.y0) << " "
375                << (int) ceil(d.x1) << "\n";
376             // According to Mike Sweet (the author of CUPS)
377             // HiResBoundingBox is only appropriate
378             // for EPS files. This means that we should
379             // distinguish if we export to ps or eps here.
380             // FIXME: I couldn't find HiResBoundingBox in the PS
381             // reference manual, so I guess we should skip
382             // it.
383             os << "%%HiResBoundingBox: " << (_height - d.y1) << " "
384                << d.x0 << " "
385                << (_height - d.y0) << " "
386                << d.x1 << "\n";
387         } else {
388             os << "%%Orientation: Portrait\n";
389             os << "%%BoundingBox: " << (int) d.x0 << " "
390                << (int) d.y0 << " "
391                << (int) ceil(d.x1) << " "
392                << (int) ceil(d.y1) << "\n";
393             os << "%%HiResBoundingBox: " << d.x0 << " "
394                << d.y0 << " "
395                << d.x1 << " "
396                << d.y1 << "\n";
397         }
399         os << "%%EndComments\n";
400         // This will become problematic if we print multi paged documents:
401         os << "%%Page: 1 1\n";
403         if (pageLandscape) {
404             os << "90 rotate\n";
405             if (_bitmap) {
406                 os << "0 " << (int) -ceil(_height) << " translate\n";
407             }
408         } else {
409             if (!_bitmap) {
410                 os << "0 " << (int) ceil(_height) << " translate\n";
411             }
412         }
414         if (!_bitmap) {
415             os << PT_PER_PX << " " << -PT_PER_PX << " scale\n";
416             // from now on we can output px, but they will be treated as pt
417         }
418     }
420     /* FIXME: This function is declared to return unsigned, whereas fprintf returns a signed int *
421      * that can be zero if the first fprintf failed (os is empty) or "negative" (i.e. very positive
422      * in unsigned int interpretation) if the first fprintf failed but this one succeeds, or
423      * positive if both succeed. */
424     return fprintf(_stream, "%s", os.str().c_str());
427 unsigned int
428 PrintPS::finish(Inkscape::Extension::Print *mod)
430     if (!_stream) return 0;
432     if (_bitmap) {
433         double const dots_per_pt = _dpi / PT_PER_IN;
435         double const x0 = 0.0;
436         double const y0 = 0.0;
437         double const x1 = x0 + _width;
438         double const y1 = y0 + _height;
440         /* Bitmap width/height in bitmap dots. */
441         int const width = (int) (_width * dots_per_pt + 0.5);
442         int const height = (int) (_height * dots_per_pt + 0.5);
444         NRMatrix affine;
445         affine.c[0] = width / ((x1 - x0) * PX_PER_PT);
446         affine.c[1] = 0.0;
447         affine.c[2] = 0.0;
448         affine.c[3] = height / ((y1 - y0) * PX_PER_PT);
449         affine.c[4] = -affine.c[0] * x0;
450         affine.c[5] = -affine.c[3] * y0;
452         nr_arena_item_set_transform(mod->root, &affine);
454         guchar *const px = nr_new(guchar, 4 * width * 64);
456         for (int y = 0; y < height; y += 64) {
457             /* Set area of interest. */
458             NRRectL bbox;
459             bbox.x0 = 0;
460             bbox.y0 = y;
461             bbox.x1 = width;
462             bbox.y1 = MIN(height, y + 64);
464             /* Update to renderable state. */
465             NRGC gc(NULL);
466             nr_matrix_set_identity(&gc.transform);
467             nr_arena_item_invoke_update(mod->root, &bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
468             /* Render */
469             /* This should take guchar* instead of unsigned char*) */
470             NRPixBlock pb;
471             nr_pixblock_setup_extern(&pb, NR_PIXBLOCK_MODE_R8G8B8A8N,
472                                      bbox.x0, bbox.y0, bbox.x1, bbox.y1,
473                                      (guchar*)px, 4 * width, FALSE, FALSE);
474             memset(px, 0xff, 4 * width * 64);
475             nr_arena_item_invoke_render(mod->root, &bbox, &pb, 0);
476             /* Blitter goes here */
477             NRMatrix imgt;
478             imgt.c[0] = (bbox.x1 - bbox.x0) / dots_per_pt;
479             imgt.c[1] = 0.0;
480             imgt.c[2] = 0.0;
481             imgt.c[3] = (bbox.y1 - bbox.y0) / dots_per_pt;
482             imgt.c[4] = 0.0;
483             imgt.c[5] = _height - y / dots_per_pt - (bbox.y1 - bbox.y0) / dots_per_pt;
485             print_image(_stream, px, bbox.x1 - bbox.x0, bbox.y1 - bbox.y0, 4 * width, &imgt);
486         }
488         nr_free(px);
489     }
491     fprintf(_stream, "showpage\n");
492     int const res = fprintf(_stream, "%%%%EOF\n");
494     /* Flush stream to be sure. */
495     (void) fflush(_stream);
497     /* fixme: should really use pclose for popen'd streams */
498     fclose(_stream);
499     _stream = 0;
500     _latin1_encoded_fonts.clear();
502     return res;
505 unsigned int
506 PrintPS::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
508     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
509     if (_bitmap) return 0;
511     Inkscape::SVGOStringStream os;
512     os << "gsave [" << transform->c[0] << " "
513        << transform->c[1] << " "
514        << transform->c[2] << " "
515        << transform->c[3] << " "
516        << transform->c[4] << " "
517        << transform->c[5] << "] concat\n";
519     return fprintf(_stream, "%s", os.str().c_str());
522 unsigned int
523 PrintPS::release(Inkscape::Extension::Print *mod)
525     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
526     if (_bitmap) return 0;
528     return fprintf(_stream, "grestore\n");
531 unsigned int
532 PrintPS::comment(Inkscape::Extension::Print *mod, char const *comment)
534     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
535     if (_bitmap) return 0;
537     return fprintf(_stream, "%%! %s\n",comment);
540 void
541 PrintPS::print_fill_style(SVGOStringStream &os, SPStyle const *const style, NRRect const *pbox)
543     g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
544                       || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
545                            && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
547     if (style->fill.type == SP_PAINT_TYPE_COLOR) {
548         float rgb[3];
549         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
551         os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
553     } else {
554         g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
555                   && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
557         if (SP_IS_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style))) {
559             SPLinearGradient *lg = SP_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style));
560             NR::Point p1 (lg->x1.computed, lg->y1.computed);
561             NR::Point p2 (lg->x2.computed, lg->y2.computed);
562             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
563                 // convert to userspace
564                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
565                 p1 *= bbox2user;
566                 p2 *= bbox2user;
567             }
569             os << "<<\n/ShadingType 2\n/ColorSpace /DeviceRGB\n";
570             os << "/Coords [" << p1[NR::X] << " " << p1[NR::Y] << " " << p2[NR::X] << " " << p2[NR::Y] <<"]\n";
571             os << "/Extend [true true]\n";
572             os << "/Domain [0 1]\n";
573             os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
575             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
576             for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
577                 float rgb[3];
578                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
579                 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
580                 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
581                 sp_color_get_rgb_floatv(&lg->vector.stops[i+1].color, rgb);
582                 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
583                 os << "/N 1\n>>\n";
584             }
585             os << "]\n/Domain [0 1]\n";
586             os << "/Bounds [ ";
587             for (unsigned i = 0; i + 2 < lg->vector.stops.size(); i++) {
588                 os << lg->vector.stops[i+1].offset <<" ";
589             }
590             os << "]\n";
591             os << "/Encode [ ";
592             for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
593                 os << "0 1 ";
594             }
595             os << "]\n";
596             os << ">>\n>>\n";
598         } else if (SP_IS_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style))) {
600             SPRadialGradient *rg = SP_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style));
601             NR::Point c(rg->cx.computed, rg->cy.computed);
602             NR::Point f(rg->fx.computed, rg->fy.computed);
603             double r = rg->r.computed;
604             if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
605                 // convert to userspace
606                 NR::Matrix const bbox2user(pbox->x1 - pbox->x0, 0,
607                                            0, pbox->y1 - pbox->y0,
608                                            pbox->x0, pbox->y0);
609                 c *= bbox2user;
610                 f *= bbox2user;
611                 r *= bbox2user.expansion();
612             }
614             os << "<<\n/ShadingType 3\n/ColorSpace /DeviceRGB\n";
615             os << "/Coords ["<< f[NR::X] <<" "<< f[NR::Y] <<" 0 "<< c[NR::X] <<" "<< c[NR::Y] <<" "<< r <<"]\n";
616             os << "/Extend [true true]\n";
617             os << "/Domain [0 1]\n";
618             os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
620             sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
621             for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
622                 float rgb[3];
623                 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
624                 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
625                 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
626                 sp_color_get_rgb_floatv(&rg->vector.stops[i+1].color, rgb);
627                 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
628                 os << "/N 1\n>>\n";
629             }
630             os << "]\n/Domain [0 1]\n";
631             os << "/Bounds [ ";
632             for (unsigned i = 0; i + 2 < rg->vector.stops.size(); i++) {
633                 os << rg->vector.stops[i+1].offset << " ";
634             }
635             os << "]\n";
636             os << "/Encode [ ";
637             for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
638                 os << "0 1 ";
639             }
640             os << "]\n";
641             os << ">>\n>>\n";
642         }
643     }
646 void
647 PrintPS::print_stroke_style(SVGOStringStream &os, SPStyle const *style)
649     float rgb[3];
650     sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
652     os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
654     // There are rare cases in which for a solid line stroke_dasharray_set is true. To avoid
655     // invalid PS-lines such as "[0.0000000 0.0000000] 0.0000000 setdash", which should be "[] 0 setdash",
656     // we first check if all components of stroke_dash.dash are 0.
657     bool LineSolid = true;
658     if (style->stroke_dasharray_set &&
659         style->stroke_dash.n_dash   &&
660         style->stroke_dash.dash       )
661     {
662         int i = 0;
663         while (LineSolid && (i < style->stroke_dash.n_dash)) {
664                 if (style->stroke_dash.dash[i] > 0.00000001)
665                     LineSolid = false;
666                 i++;
667         }
668         if (!LineSolid) {
669             os << "[";
670             for (i = 0; i < style->stroke_dash.n_dash; i++) {
671                 if (i > 0) {
672                     os << " ";
673                 }
674                 os << style->stroke_dash.dash[i];
675             }
676             os << "] " << style->stroke_dash.offset << " setdash\n";
677         } else {
678             os << "[] 0 setdash\n";
679         }
680     } else {
681         os << "[] 0 setdash\n";
682     }
684     os << style->stroke_width.computed << " setlinewidth\n";
685     os << style->stroke_linejoin.computed << " setlinejoin\n";
686     os << style->stroke_linecap.computed << " setlinecap\n";
690 unsigned int
691 PrintPS::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
692               NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
694     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
695     if (_bitmap) return 0;
697     if ( style->fill.type == SP_PAINT_TYPE_COLOR
698          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
699               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
700     {
701         Inkscape::SVGOStringStream os;
703         os << "gsave\n";
705         print_fill_style(os, style, pbox);
707         print_bpath(os, bpath->path);
709         if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
710             if (style->fill.type == SP_PAINT_TYPE_COLOR) {
711                 os << "eofill\n";
712             } else {
713                 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
714                           && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
715                 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
716                 os << "eoclip\n";
717                 if (g->gradientTransform_set) {
718                     os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
719                         << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
720                         << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
721                 }
722                 os << "shfill\n";
723                 if (g->gradientTransform_set) {
724                     os << "grestore\n";
725                 }
726             }
727         } else {
728             if (style->fill.type == SP_PAINT_TYPE_COLOR) {
729                 os << "fill\n";
730             } else {
731                 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
732                           && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
733                 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
734                 os << "clip\n";
735                 if (g->gradientTransform_set) {
736                     os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
737                         << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
738                         << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
739                 }
740                 os << "shfill\n";
741                 if (g->gradientTransform_set) {
742                     os << "grestore\n";
743                 }
744             }
745         }
747         os << "grestore\n";
749         fprintf(_stream, "%s", os.str().c_str());
750     }
752     return 0;
756 unsigned int
757 PrintPS::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
758                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
760     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
761     if (_bitmap) return 0;
763     if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
764         Inkscape::SVGOStringStream os;
766         print_stroke_style(os, style);
768         print_bpath(os, bpath->path);
770         os << "stroke\n";
772         fprintf(_stream, "%s", os.str().c_str());
773     }
775     return 0;
778 unsigned int
779 PrintPS::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
780                NRMatrix const *transform, SPStyle const *style)
782     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
783     if (_bitmap) return 0;
785     return print_image(_stream, px, w, h, rs, transform);
786 #if 0
787     fprintf(_stream, "gsave\n");
788     fprintf(_stream, "/rowdata %d string def\n", 3 * w);
789     fprintf(_stream, "[%g %g %g %g %g %g] concat\n",
790             transform->c[0],
791             transform->c[1],
792             transform->c[2],
793             transform->c[3],
794             transform->c[4],
795             transform->c[5]);
796     fprintf(_stream, "%d %d 8 [%d 0 0 -%d 0 %d]\n", w, h, w, h, h);
797     fprintf(_stream, "{currentfile rowdata readhexstring pop}\n");
798     fprintf(_stream, "false 3 colorimage\n");
800     for (unsigned int r = 0; r < h; r++) {
801         guchar *s;
802         unsigned int c0, c1, c;
803         s = px + r * rs;
804         for (c0 = 0; c0 < w; c0 += 24) {
805             c1 = MIN(w, c0 + 24);
806             for (c = c0; c < c1; c++) {
807                 static char const xtab[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
808                 fputc(xtab[s[0] >> 4], _stream);
809                 fputc(xtab[s[0] & 0xf], _stream);
810                 fputc(xtab[s[1] >> 4], _stream);
811                 fputc(xtab[s[1] & 0xf], _stream);
812                 fputc(xtab[s[2] >> 4], _stream);
813                 fputc(xtab[s[2] & 0xf], _stream);
814                 s += 4;
815             }
816             fputs("\n", _stream);
817         }
818     }
820     fprintf(_stream, "grestore\n");
822     return 0;
823 #endif
826 char const *
827 PrintPS::PSFontName(SPStyle const *style)
829     font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
831     char const *n;
832     char name_buf[256];
834     if (tf) {
835         tf->PSName(name_buf, sizeof(name_buf));
836         n = name_buf;
837         tf->Unref();
838     } else {
839         // 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
840         bool i = (style->font_style.value == SP_CSS_FONT_STYLE_ITALIC);
841         bool o = (style->font_style.value == SP_CSS_FONT_STYLE_OBLIQUE);
842         bool b = (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) ||
843             (style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
845         n = g_strdup_printf("%s%s%s%s",
846                             g_strdelimit(style->text->font_family.value, " ", '-'),
847                             (b || i || o) ? "-" : "",
848                             (b) ? "Bold" : "",
849                             (i) ? "Italic" : ((o) ? "Oblique" : "") );
850     }
852     return g_strdup(n);
856 unsigned int
857 PrintPS::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
858               SPStyle const *const style)
860     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
861     if (_bitmap) return 0;
863     Inkscape::SVGOStringStream os;
865     // Escape chars
866     Inkscape::SVGOStringStream escaped_text;
867     escaped_text << std::oct;
868     for (gchar const *p_text = text ; *p_text ; p_text = g_utf8_next_char(p_text)) {
869         gunichar const c = g_utf8_get_char(p_text);
870         if (c == '\\' || c == ')' || c == '(')
871             escaped_text << '\\' << static_cast<char>(c);
872         else if (c >= 0x80)
873             escaped_text << '\\' << c;
874         else
875             escaped_text << static_cast<char>(c);
876     }
878     os << "gsave\n";
880     // set font
881     char const *fn = PSFontName(style);
882     if (_latin1_encoded_fonts.find(fn) == _latin1_encoded_fonts.end()) {
883         if (!_newlatin1font_proc_defined) {
884             // input: newfontname, existingfontname
885             // output: new font object, also defined to newfontname
886             os << "/newlatin1font "         // name of the proc
887                   "{findfont dup length dict copy "     // load the font and create a copy of it
888                   "dup /Encoding ISOLatin1Encoding put "     // change the encoding in the copy
889                   "definefont} def\n";      // create the new font and leave it on the stack, define the proc
890             _newlatin1font_proc_defined = true;
891         }
892         os << "/" << fn << "-ISOLatin1 /" << fn << " newlatin1font\n";
893         _latin1_encoded_fonts.insert(fn);
894     } else
895         os << "/" << fn << "-ISOLatin1 findfont\n";
896     os << style->font_size.computed << " scalefont\n";
897     os << "setfont\n";
898     g_free((void *) fn);
900     if ( style->fill.type == SP_PAINT_TYPE_COLOR
901          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
902               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
903     {
904         // set fill style
905         print_fill_style(os, style, NULL);
906         // FIXME: we don't know the pbox of text, so have to pass NULL. This means gradients with
907         // bbox units won't work with text. However userspace gradients don't work with text either
908         // (text is black) for some reason.
910         os << "newpath\n";
911         os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
912         os << "(" << escaped_text.str() << ") show\n";
913     }
915     if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
917         // set stroke style
918         print_stroke_style(os, style);
920         // paint stroke
921         os << "newpath\n";
922         os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
923         os << "(" << escaped_text.str() << ") false charpath stroke\n";
924     }
926     os << "grestore\n";
928     fprintf(_stream, "%s", os.str().c_str());
930     return 0;
935 /* PostScript helpers */
937 void
938 PrintPS::print_bpath(SVGOStringStream &os, NArtBpath const *bp)
940     os << "newpath\n";
941     bool closed = false;
942     while (bp->code != NR_END) {
943         switch (bp->code) {
944             case NR_MOVETO:
945                 if (closed) {
946                     os << "closepath\n";
947                 }
948                 closed = true;
949                 os << bp->x3 << " " << bp->y3 << " moveto\n";
950                 break;
951             case NR_MOVETO_OPEN:
952                 if (closed) {
953                     os << "closepath\n";
954                 }
955                 closed = false;
956                 os << bp->x3 << " " << bp->y3 << " moveto\n";
957                 break;
958             case NR_LINETO:
959                 os << bp->x3 << " " << bp->y3 << " lineto\n";
960                 break;
961             case NR_CURVETO:
962                 os << bp->x1 << " " << bp->y1 << " "
963                    << bp->x2 << " " << bp->y2 << " "
964                    << bp->x3 << " " << bp->y3 << " curveto\n";
965                 break;
966             default:
967                 break;
968         }
969         bp += 1;
970     }
971     if (closed) {
972         os << "closepath\n";
973     }
976 /* The following code is licensed under GNU GPL.
977 ** The packbits, ascii85 and imaging printing code
978 ** is from the gimp's postscript.c.
979 */
981 /**
982 * \param nin Number of bytes of source data.
983 * \param src Source data.
984 * \param nout Number of output bytes.
985 * \param dst Buffer for output.
986 */
987 void
988 PrintPS::compress_packbits(int nin,
989                            guchar *src,
990                            int *nout,
991                            guchar *dst)
994     register guchar c;
995     int nrepeat, nliteral;
996     guchar *run_start;
997     guchar *start_dst = dst;
998     guchar *last_literal = NULL;
1000     for (;;) {
1001         if (nin <= 0) break;
1003         run_start = src;
1004         c = *run_start;
1006         /* Search repeat bytes */
1007         if ((nin > 1) && (c == src[1])) {
1008             nrepeat = 1;
1009             nin -= 2;
1010             src += 2;
1011             while ((nin > 0) && (c == *src)) {
1012                 nrepeat++;
1013                 src++;
1014                 nin--;
1015                 if (nrepeat == 127) break; /* Maximum repeat */
1016             }
1018             /* Add two-byte repeat to last literal run ? */
1019             if ( (nrepeat == 1)
1020                  && (last_literal != NULL) && (((*last_literal)+1)+2 <= 128) )
1021             {
1022                 *last_literal += 2;
1023                 *(dst++) = c;
1024                 *(dst++) = c;
1025                 continue;
1026             }
1028             /* Add repeat run */
1029             *(dst++) = (guchar)((-nrepeat) & 0xff);
1030             *(dst++) = c;
1031             last_literal = NULL;
1032             continue;
1033         }
1034         /* Search literal bytes */
1035         nliteral = 1;
1036         nin--;
1037         src++;
1039         for (;;) {
1040             if (nin <= 0) break;
1042             if ((nin >= 2) && (src[0] == src[1])) /* A two byte repeat ? */
1043                 break;
1045             nliteral++;
1046             nin--;
1047             src++;
1048             if (nliteral == 128) break; /* Maximum literal run */
1049         }
1051         /* Could be added to last literal run ? */
1052         if ((last_literal != NULL) && (((*last_literal)+1)+nliteral <= 128)) {
1053             *last_literal += nliteral;
1054         } else {
1055             last_literal = dst;
1056             *(dst++) = (guchar)(nliteral-1);
1057         }
1058         while (nliteral-- > 0) *(dst++) = *(run_start++);
1059     }
1060     *nout = dst - start_dst;
1063 void
1064 PrintPS::ascii85_init(void)
1066     ascii85_len = 0;
1067     ascii85_linewidth = 0;
1070 void
1071 PrintPS::ascii85_flush(SVGOStringStream &os)
1073     char c[5];
1074     bool const zero_case = (ascii85_buf == 0);
1075     static int const max_linewidth = 75;
1077     for (int i = 4; i >= 0; i--) {
1078         c[i] = (ascii85_buf % 85) + '!';
1079         ascii85_buf /= 85;
1080     }
1081     /* check for special case: "!!!!!" becomes "z", but only if not
1082      * at end of data. */
1083     if (zero_case && (ascii85_len == 4)) {
1084         if (ascii85_linewidth >= max_linewidth) {
1085             os << '\n';
1086             ascii85_linewidth = 0;
1087         }
1088         os << 'z';
1089         ascii85_linewidth++;
1090     } else {
1091         for (int i = 0; i < ascii85_len+1; i++) {
1092             if ((ascii85_linewidth >= max_linewidth) && (c[i] != '%')) {
1093                 os << '\n';
1094                 ascii85_linewidth = 0;
1095             }
1096             os << c[i];
1097             ascii85_linewidth++;
1098         }
1099     }
1101     ascii85_len = 0;
1102     ascii85_buf = 0;
1105 inline void
1106 PrintPS::ascii85_out(guchar byte, SVGOStringStream &os)
1108     if (ascii85_len == 4)
1109         ascii85_flush(os);
1111     ascii85_buf <<= 8;
1112     ascii85_buf |= byte;
1113     ascii85_len++;
1116 void
1117 PrintPS::ascii85_nout(int n, guchar *uptr, SVGOStringStream &os)
1119     while (n-- > 0) {
1120         ascii85_out(*uptr, os);
1121         uptr++;
1122     }
1125 void
1126 PrintPS::ascii85_done(SVGOStringStream &os)
1128     if (ascii85_len) {
1129         /* zero any unfilled buffer portion, then flush */
1130         ascii85_buf <<= (8 * (4-ascii85_len));
1131         ascii85_flush(os);
1132     }
1134     os << "~>\n";
1137 unsigned int
1138 PrintPS::print_image(FILE *ofp, guchar *px, unsigned int width, unsigned int height, unsigned int rs,
1139                      NRMatrix const *transform)
1141     Inkscape::SVGOStringStream os;
1143     os << "gsave\n";
1144     os << "[" << transform->c[0] << " "
1145        << transform->c[1] << " "
1146        << transform->c[2] << " "
1147        << transform->c[3] << " "
1148        << transform->c[4] << " "
1149        << transform->c[5] << "] concat\n";
1150     os << width << " " << height << " 8 ["
1151        << width << " 0 0 -" << height << " 0 " << height << "]\n";
1154     /* Write read image procedure */
1155     os << "% Strings to hold RGB-samples per scanline\n";
1156     os << "/rstr " << width << " string def\n";
1157     os << "/gstr " << width << " string def\n";
1158     os << "/bstr " << width << " string def\n";
1159     os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter rstr readstring pop}\n";
1160     os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter gstr readstring pop}\n";
1161     os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter bstr readstring pop}\n";
1162     os << "true 3\n";
1164     /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
1165     guchar *const packb = (guchar *)g_malloc((width * 105)/100+2);
1166     guchar *const plane = (guchar *)g_malloc(width);
1168     /* ps_begin_data(ofp); */
1169     os << "colorimage\n";
1171 /*#define GET_RGB_TILE(begin)                   \
1172  *  {int scan_lines;                                                    \
1173  *    scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
1174  *    gimp_pixel_rgn_get_rect(&pixel_rgn, begin, 0, i, width, scan_lines); \
1175  *    src = begin; }
1176  */
1178     for (unsigned i = 0; i < height; i++) {
1179         /* if ((i % tile_height) == 0) GET_RGB_TILE(data); */ /* Get more data */
1180         guchar const *const src = px + i * rs;
1182         /* Iterate over RGB */
1183         for (int rgb = 0; rgb < 3; rgb++) {
1184             guchar const *src_ptr = src + rgb;
1185             guchar *plane_ptr = plane;
1186             for (unsigned j = 0; j < width; j++) {
1187                 *(plane_ptr++) = *src_ptr;
1188                 src_ptr += 4;
1189             }
1191             int nout;
1192             compress_packbits(width, plane, &nout, packb);
1194             ascii85_init();
1195             ascii85_nout(nout, packb, os);
1196             ascii85_out(128, os); /* Write EOD of RunLengthDecode filter */
1197             ascii85_done(os);
1198         }
1199     }
1200     /* ps_end_data(ofp); */
1202 #if 0
1203     fprintf(ofp, "showpage\n");
1204     g_free(data);
1205 #endif
1207     g_free(packb);
1208     g_free(plane);
1210 #if 0
1211     if (ferror(ofp)) {
1212         g_message(_("write error occurred"));
1213         return (FALSE);
1214     }
1215 #endif
1217     os << "grestore\n";
1219     fprintf(ofp, "%s", os.str().c_str());
1221     return 0;
1222 //#undef GET_RGB_TILE
1225 bool
1226 PrintPS::textToPath(Inkscape::Extension::Print * ext)
1228     return ext->get_param_bool("textToPath");
1231 #include "clear-n_.h"
1233 void
1234 PrintPS::init(void)
1236     /* SVG in */
1237     (void) Inkscape::Extension::build_from_mem(
1238         "<inkscape-extension>\n"
1239         "<name>" N_("Postscript Print") "</name>\n"
1240         "<id>" SP_MODULE_KEY_PRINT_PS "</id>\n"
1241         "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1242         "<param name=\"resolution\" type=\"string\">72</param>\n"
1243         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1244         "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1245         "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1246         "<print/>\n"
1247         "</inkscape-extension>", new PrintPS());
1251 }  /* namespace Internal */
1252 }  /* namespace Extension */
1253 }  /* namespace Inkscape */
1255 /* End of GNU GPL code */
1258 /*
1259   Local Variables:
1260   mode:c++
1261   c-file-style:"stroustrup"
1262   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1263   indent-tabs-mode:nil
1264   fill-column:99
1265   End:
1266 */
1267 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :