Code

moving trunk for module inkscape
[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     int const res = fprintf(_stream, "showpage\n");
493     /* Flush stream to be sure. */
494     (void) fflush(_stream);
496     /* fixme: should really use pclose for popen'd streams */
497     fclose(_stream);
498     _stream = 0;
499     _latin1_encoded_fonts.clear();
501     return res;
504 unsigned int
505 PrintPS::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
507     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
508     if (_bitmap) return 0;
510     Inkscape::SVGOStringStream os;
511     os << "gsave [" << transform->c[0] << " "
512        << transform->c[1] << " "
513        << transform->c[2] << " "
514        << transform->c[3] << " "
515        << transform->c[4] << " "
516        << transform->c[5] << "] concat\n";
518     return fprintf(_stream, "%s", os.str().c_str());
521 unsigned int
522 PrintPS::release(Inkscape::Extension::Print *mod)
524     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
525     if (_bitmap) return 0;
527     return fprintf(_stream, "grestore\n");
530 unsigned int
531 PrintPS::comment(Inkscape::Extension::Print *mod, char const *comment)
533     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
534     if (_bitmap) return 0;
536     return fprintf(_stream, "%%! %s\n",comment);
539 void
540 PrintPS::print_fill_style(SVGOStringStream &os, SPStyle const *const style, NRRect const *pbox)
542     g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
543                       || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
544                            && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
546     if (style->fill.type == SP_PAINT_TYPE_COLOR) {
547         float rgb[3];
548         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
550         os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
552     } else {
553         g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
554                   && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
556         if (SP_IS_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style))) {
558             SPLinearGradient *lg = SP_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style));
559             NR::Point p1 (lg->x1.computed, lg->y1.computed);
560             NR::Point p2 (lg->x2.computed, lg->y2.computed);
561             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
562                 // convert to userspace
563                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
564                 p1 *= bbox2user;
565                 p2 *= bbox2user;
566             }
568             os << "<<\n/ShadingType 2\n/ColorSpace /DeviceRGB\n";
569             os << "/Coords [" << p1[NR::X] << " " << p1[NR::Y] << " " << p2[NR::X] << " " << p2[NR::Y] <<"]\n";
570             os << "/Extend [true true]\n";
571             os << "/Domain [0 1]\n";
572             os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
574             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
575             for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
576                 float rgb[3];
577                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
578                 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
579                 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
580                 sp_color_get_rgb_floatv(&lg->vector.stops[i+1].color, rgb);
581                 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
582                 os << "/N 1\n>>\n";
583             }
584             os << "]\n/Domain [0 1]\n";
585             os << "/Bounds [ ";
586             for (unsigned i = 0; i + 2 < lg->vector.stops.size(); i++) {
587                 os << lg->vector.stops[i+1].offset <<" ";
588             }
589             os << "]\n";
590             os << "/Encode [ ";
591             for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
592                 os << "0 1 ";
593             }
594             os << "]\n";
595             os << ">>\n>>\n";
597         } else if (SP_IS_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style))) {
599             SPRadialGradient *rg = SP_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style));
600             NR::Point c(rg->cx.computed, rg->cy.computed);
601             NR::Point f(rg->fx.computed, rg->fy.computed);
602             double r = rg->r.computed;
603             if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
604                 // convert to userspace
605                 NR::Matrix const bbox2user(pbox->x1 - pbox->x0, 0,
606                                            0, pbox->y1 - pbox->y0,
607                                            pbox->x0, pbox->y0);
608                 c *= bbox2user;
609                 f *= bbox2user;
610                 r *= bbox2user.expansion();
611             }
613             os << "<<\n/ShadingType 3\n/ColorSpace /DeviceRGB\n";
614             os << "/Coords ["<< f[NR::X] <<" "<< f[NR::Y] <<" 0 "<< c[NR::X] <<" "<< c[NR::Y] <<" "<< r <<"]\n";
615             os << "/Extend [true true]\n";
616             os << "/Domain [0 1]\n";
617             os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
619             sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
620             for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
621                 float rgb[3];
622                 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
623                 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
624                 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
625                 sp_color_get_rgb_floatv(&rg->vector.stops[i+1].color, rgb);
626                 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
627                 os << "/N 1\n>>\n";
628             }
629             os << "]\n/Domain [0 1]\n";
630             os << "/Bounds [ ";
631             for (unsigned i = 0; i + 2 < rg->vector.stops.size(); i++) {
632                 os << rg->vector.stops[i+1].offset << " ";
633             }
634             os << "]\n";
635             os << "/Encode [ ";
636             for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
637                 os << "0 1 ";
638             }
639             os << "]\n";
640             os << ">>\n>>\n";
641         }
642     }
645 void
646 PrintPS::print_stroke_style(SVGOStringStream &os, SPStyle const *style)
648     float rgb[3];
649     sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
651     os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
653     // There are rare cases in which for a solid line stroke_dasharray_set is true. To avoid
654     // invalid PS-lines such as "[0.0000000 0.0000000] 0.0000000 setdash", which should be "[] 0 setdash",
655     // we first check if all components of stroke_dash.dash are 0.
656     bool LineSolid = true;
657     if (style->stroke_dasharray_set &&
658         style->stroke_dash.n_dash   &&
659         style->stroke_dash.dash       )
660     {
661         int i = 0;
662         while (LineSolid && (i < style->stroke_dash.n_dash)) {
663                 i++;
664                 if (style->stroke_dash.dash[i] > 0.00000001)
665                     LineSolid = false;
666         }
667         if (!LineSolid) {
668             os << "[";
669             for (i = 0; i < style->stroke_dash.n_dash; i++) {
670                 if (i > 0) {
671                     os << " ";
672                 }
673                 os << style->stroke_dash.dash[i];
674             }
675             os << "] " << style->stroke_dash.offset << " setdash\n";
676         } else {
677             os << "[] 0 setdash\n";
678         }
679     } else {
680         os << "[] 0 setdash\n";
681     }
683     os << style->stroke_width.computed << " setlinewidth\n";
684     os << style->stroke_linejoin.computed << " setlinejoin\n";
685     os << style->stroke_linecap.computed << " setlinecap\n";
689 unsigned int
690 PrintPS::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
691               NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
693     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
694     if (_bitmap) return 0;
696     if ( style->fill.type == SP_PAINT_TYPE_COLOR
697          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
698               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
699     {
700         Inkscape::SVGOStringStream os;
702         os << "gsave\n";
704         print_fill_style(os, style, pbox);
706         print_bpath(os, bpath->path);
708         if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
709             if (style->fill.type == SP_PAINT_TYPE_COLOR) {
710                 os << "eofill\n";
711             } else {
712                 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
713                           && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
714                 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
715                 os << "eoclip\n";
716                 if (g->gradientTransform_set) {
717                     os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
718                         << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
719                         << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
720                 }
721                 os << "shfill\n";
722                 if (g->gradientTransform_set) {
723                     os << "grestore\n";
724                 }
725             }
726         } else {
727             if (style->fill.type == SP_PAINT_TYPE_COLOR) {
728                 os << "fill\n";
729             } else {
730                 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
731                           && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
732                 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
733                 os << "clip\n";
734                 if (g->gradientTransform_set) {
735                     os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
736                         << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
737                         << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
738                 }
739                 os << "shfill\n";
740                 if (g->gradientTransform_set) {
741                     os << "grestore\n";
742                 }
743             }
744         }
746         os << "grestore\n";
748         fprintf(_stream, "%s", os.str().c_str());
749     }
751     return 0;
755 unsigned int
756 PrintPS::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
757                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
759     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
760     if (_bitmap) return 0;
762     if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
763         Inkscape::SVGOStringStream os;
765         print_stroke_style(os, style);
767         print_bpath(os, bpath->path);
769         os << "stroke\n";
771         fprintf(_stream, "%s", os.str().c_str());
772     }
774     return 0;
777 unsigned int
778 PrintPS::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
779                NRMatrix const *transform, SPStyle const *style)
781     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
782     if (_bitmap) return 0;
784     return print_image(_stream, px, w, h, rs, transform);
785 #if 0
786     fprintf(_stream, "gsave\n");
787     fprintf(_stream, "/rowdata %d string def\n", 3 * w);
788     fprintf(_stream, "[%g %g %g %g %g %g] concat\n",
789             transform->c[0],
790             transform->c[1],
791             transform->c[2],
792             transform->c[3],
793             transform->c[4],
794             transform->c[5]);
795     fprintf(_stream, "%d %d 8 [%d 0 0 -%d 0 %d]\n", w, h, w, h, h);
796     fprintf(_stream, "{currentfile rowdata readhexstring pop}\n");
797     fprintf(_stream, "false 3 colorimage\n");
799     for (unsigned int r = 0; r < h; r++) {
800         guchar *s;
801         unsigned int c0, c1, c;
802         s = px + r * rs;
803         for (c0 = 0; c0 < w; c0 += 24) {
804             c1 = MIN(w, c0 + 24);
805             for (c = c0; c < c1; c++) {
806                 static char const xtab[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
807                 fputc(xtab[s[0] >> 4], _stream);
808                 fputc(xtab[s[0] & 0xf], _stream);
809                 fputc(xtab[s[1] >> 4], _stream);
810                 fputc(xtab[s[1] & 0xf], _stream);
811                 fputc(xtab[s[2] >> 4], _stream);
812                 fputc(xtab[s[2] & 0xf], _stream);
813                 s += 4;
814             }
815             fputs("\n", _stream);
816         }
817     }
819     fprintf(_stream, "grestore\n");
821     return 0;
822 #endif
825 char const *
826 PrintPS::PSFontName(SPStyle const *style)
828     font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
830     char const *n;
831     char name_buf[256];
833     if (tf) {
834         tf->PSName(name_buf, sizeof(name_buf));
835         n = name_buf;
836         tf->Unref();
837     } else {
838         // 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
839         bool i = (style->font_style.value == SP_CSS_FONT_STYLE_ITALIC);
840         bool o = (style->font_style.value == SP_CSS_FONT_STYLE_OBLIQUE);
841         bool b = (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) ||
842             (style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
844         n = g_strdup_printf("%s%s%s%s",
845                             g_strdelimit(style->text->font_family.value, " ", '-'),
846                             (b || i || o) ? "-" : "",
847                             (b) ? "Bold" : "",
848                             (i) ? "Italic" : ((o) ? "Oblique" : "") );
849     }
851     return g_strdup(n);
855 unsigned int
856 PrintPS::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
857               SPStyle const *const style)
859     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
860     if (_bitmap) return 0;
862     Inkscape::SVGOStringStream os;
864     // Escape chars
865     Inkscape::SVGOStringStream escaped_text;
866     escaped_text << std::oct;
867     for (gchar const *p_text = text ; *p_text ; p_text = g_utf8_next_char(p_text)) {
868         gunichar const c = g_utf8_get_char(p_text);
869         if (c == '\\' || c == ')' || c == '(')
870             escaped_text << '\\' << static_cast<char>(c);
871         else if (c >= 0x80)
872             escaped_text << '\\' << c;
873         else
874             escaped_text << static_cast<char>(c);
875     }
877     os << "gsave\n";
879     // set font
880     char const *fn = PSFontName(style);
881     if (_latin1_encoded_fonts.find(fn) == _latin1_encoded_fonts.end()) {
882         if (!_newlatin1font_proc_defined) {
883             // input: newfontname, existingfontname
884             // output: new font object, also defined to newfontname
885             os << "/newlatin1font "         // name of the proc
886                   "{findfont dup length dict copy "     // load the font and create a copy of it
887                   "dup /Encoding ISOLatin1Encoding put "     // change the encoding in the copy
888                   "definefont} def\n";      // create the new font and leave it on the stack, define the proc
889             _newlatin1font_proc_defined = true;
890         }
891         os << "/" << fn << "-ISOLatin1 /" << fn << " newlatin1font\n";
892         _latin1_encoded_fonts.insert(fn);
893     } else
894         os << "/" << fn << "-ISOLatin1 findfont\n";
895     os << style->font_size.computed << " scalefont\n";
896     os << "setfont\n";
897     g_free((void *) fn);
899     if ( style->fill.type == SP_PAINT_TYPE_COLOR
900          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
901               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
902     {
903         // set fill style
904         print_fill_style(os, style, NULL);
905         // FIXME: we don't know the pbox of text, so have to pass NULL. This means gradients with
906         // bbox units won't work with text. However userspace gradients don't work with text either
907         // (text is black) for some reason.
909         os << "newpath\n";
910         os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
911         os << "(" << escaped_text.str() << ") show\n";
912     }
914     if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
916         // set stroke style
917         print_stroke_style(os, style);
919         // paint stroke
920         os << "newpath\n";
921         os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
922         os << "(" << escaped_text.str() << ") false charpath stroke\n";
923     }
925     os << "grestore\n";
927     fprintf(_stream, "%s", os.str().c_str());
929     return 0;
934 /* PostScript helpers */
936 void
937 PrintPS::print_bpath(SVGOStringStream &os, NArtBpath const *bp)
939     os << "newpath\n";
940     bool closed = false;
941     while (bp->code != NR_END) {
942         switch (bp->code) {
943             case NR_MOVETO:
944                 if (closed) {
945                     os << "closepath\n";
946                 }
947                 closed = true;
948                 os << bp->x3 << " " << bp->y3 << " moveto\n";
949                 break;
950             case NR_MOVETO_OPEN:
951                 if (closed) {
952                     os << "closepath\n";
953                 }
954                 closed = false;
955                 os << bp->x3 << " " << bp->y3 << " moveto\n";
956                 break;
957             case NR_LINETO:
958                 os << bp->x3 << " " << bp->y3 << " lineto\n";
959                 break;
960             case NR_CURVETO:
961                 os << bp->x1 << " " << bp->y1 << " "
962                    << bp->x2 << " " << bp->y2 << " "
963                    << bp->x3 << " " << bp->y3 << " curveto\n";
964                 break;
965             default:
966                 break;
967         }
968         bp += 1;
969     }
970     if (closed) {
971         os << "closepath\n";
972     }
975 /* The following code is licensed under GNU GPL.
976 ** The packbits, ascii85 and imaging printing code
977 ** is from the gimp's postscript.c.
978 */
980 /**
981 * \param nin Number of bytes of source data.
982 * \param src Source data.
983 * \param nout Number of output bytes.
984 * \param dst Buffer for output.
985 */
986 void
987 PrintPS::compress_packbits(int nin,
988                            guchar *src,
989                            int *nout,
990                            guchar *dst)
993     register guchar c;
994     int nrepeat, nliteral;
995     guchar *run_start;
996     guchar *start_dst = dst;
997     guchar *last_literal = NULL;
999     for (;;) {
1000         if (nin <= 0) break;
1002         run_start = src;
1003         c = *run_start;
1005         /* Search repeat bytes */
1006         if ((nin > 1) && (c == src[1])) {
1007             nrepeat = 1;
1008             nin -= 2;
1009             src += 2;
1010             while ((nin > 0) && (c == *src)) {
1011                 nrepeat++;
1012                 src++;
1013                 nin--;
1014                 if (nrepeat == 127) break; /* Maximum repeat */
1015             }
1017             /* Add two-byte repeat to last literal run ? */
1018             if ( (nrepeat == 1)
1019                  && (last_literal != NULL) && (((*last_literal)+1)+2 <= 128) )
1020             {
1021                 *last_literal += 2;
1022                 *(dst++) = c;
1023                 *(dst++) = c;
1024                 continue;
1025             }
1027             /* Add repeat run */
1028             *(dst++) = (guchar)((-nrepeat) & 0xff);
1029             *(dst++) = c;
1030             last_literal = NULL;
1031             continue;
1032         }
1033         /* Search literal bytes */
1034         nliteral = 1;
1035         nin--;
1036         src++;
1038         for (;;) {
1039             if (nin <= 0) break;
1041             if ((nin >= 2) && (src[0] == src[1])) /* A two byte repeat ? */
1042                 break;
1044             nliteral++;
1045             nin--;
1046             src++;
1047             if (nliteral == 128) break; /* Maximum literal run */
1048         }
1050         /* Could be added to last literal run ? */
1051         if ((last_literal != NULL) && (((*last_literal)+1)+nliteral <= 128)) {
1052             *last_literal += nliteral;
1053         } else {
1054             last_literal = dst;
1055             *(dst++) = (guchar)(nliteral-1);
1056         }
1057         while (nliteral-- > 0) *(dst++) = *(run_start++);
1058     }
1059     *nout = dst - start_dst;
1062 void
1063 PrintPS::ascii85_init(void)
1065     ascii85_len = 0;
1066     ascii85_linewidth = 0;
1069 void
1070 PrintPS::ascii85_flush(SVGOStringStream &os)
1072     char c[5];
1073     bool const zero_case = (ascii85_buf == 0);
1074     static int const max_linewidth = 75;
1076     for (int i = 4; i >= 0; i--) {
1077         c[i] = (ascii85_buf % 85) + '!';
1078         ascii85_buf /= 85;
1079     }
1080     /* check for special case: "!!!!!" becomes "z", but only if not
1081      * at end of data. */
1082     if (zero_case && (ascii85_len == 4)) {
1083         if (ascii85_linewidth >= max_linewidth) {
1084             os << '\n';
1085             ascii85_linewidth = 0;
1086         }
1087         os << 'z';
1088         ascii85_linewidth++;
1089     } else {
1090         for (int i = 0; i < ascii85_len+1; i++) {
1091             if ((ascii85_linewidth >= max_linewidth) && (c[i] != '%')) {
1092                 os << '\n';
1093                 ascii85_linewidth = 0;
1094             }
1095             os << c[i];
1096             ascii85_linewidth++;
1097         }
1098     }
1100     ascii85_len = 0;
1101     ascii85_buf = 0;
1104 inline void
1105 PrintPS::ascii85_out(guchar byte, SVGOStringStream &os)
1107     if (ascii85_len == 4)
1108         ascii85_flush(os);
1110     ascii85_buf <<= 8;
1111     ascii85_buf |= byte;
1112     ascii85_len++;
1115 void
1116 PrintPS::ascii85_nout(int n, guchar *uptr, SVGOStringStream &os)
1118     while (n-- > 0) {
1119         ascii85_out(*uptr, os);
1120         uptr++;
1121     }
1124 void
1125 PrintPS::ascii85_done(SVGOStringStream &os)
1127     if (ascii85_len) {
1128         /* zero any unfilled buffer portion, then flush */
1129         ascii85_buf <<= (8 * (4-ascii85_len));
1130         ascii85_flush(os);
1131     }
1133     os << "~>\n";
1136 unsigned int
1137 PrintPS::print_image(FILE *ofp, guchar *px, unsigned int width, unsigned int height, unsigned int rs,
1138                      NRMatrix const *transform)
1140     Inkscape::SVGOStringStream os;
1142     os << "gsave\n";
1143     os << "[" << transform->c[0] << " "
1144        << transform->c[1] << " "
1145        << transform->c[2] << " "
1146        << transform->c[3] << " "
1147        << transform->c[4] << " "
1148        << transform->c[5] << "] concat\n";
1149     os << width << " " << height << " 8 ["
1150        << width << " 0 0 -" << height << " 0 " << height << "]\n";
1153     /* Write read image procedure */
1154     os << "% Strings to hold RGB-samples per scanline\n";
1155     os << "/rstr " << width << " string def\n";
1156     os << "/gstr " << width << " string def\n";
1157     os << "/bstr " << width << " string def\n";
1158     os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter rstr readstring pop}\n";
1159     os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter gstr readstring pop}\n";
1160     os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter bstr readstring pop}\n";
1161     os << "true 3\n";
1163     /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
1164     guchar *const packb = (guchar *)g_malloc((width * 105)/100+2);
1165     guchar *const plane = (guchar *)g_malloc(width);
1167     /* ps_begin_data(ofp); */
1168     os << "colorimage\n";
1170 /*#define GET_RGB_TILE(begin)                   \
1171  *  {int scan_lines;                                                    \
1172  *    scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
1173  *    gimp_pixel_rgn_get_rect(&pixel_rgn, begin, 0, i, width, scan_lines); \
1174  *    src = begin; }
1175  */
1177     for (unsigned i = 0; i < height; i++) {
1178         /* if ((i % tile_height) == 0) GET_RGB_TILE(data); */ /* Get more data */
1179         guchar const *const src = px + i * rs;
1181         /* Iterate over RGB */
1182         for (int rgb = 0; rgb < 3; rgb++) {
1183             guchar const *src_ptr = src + rgb;
1184             guchar *plane_ptr = plane;
1185             for (unsigned j = 0; j < width; j++) {
1186                 *(plane_ptr++) = *src_ptr;
1187                 src_ptr += 4;
1188             }
1190             int nout;
1191             compress_packbits(width, plane, &nout, packb);
1193             ascii85_init();
1194             ascii85_nout(nout, packb, os);
1195             ascii85_out(128, os); /* Write EOD of RunLengthDecode filter */
1196             ascii85_done(os);
1197         }
1198     }
1199     /* ps_end_data(ofp); */
1201 #if 0
1202     fprintf(ofp, "showpage\n");
1203     g_free(data);
1204 #endif
1206     g_free(packb);
1207     g_free(plane);
1209 #if 0
1210     if (ferror(ofp)) {
1211         g_message(_("write error occurred"));
1212         return (FALSE);
1213     }
1214 #endif
1216     os << "grestore\n";
1218     fprintf(ofp, "%s", os.str().c_str());
1220     return 0;
1221 //#undef GET_RGB_TILE
1224 bool
1225 PrintPS::textToPath(Inkscape::Extension::Print * ext)
1227     return ext->get_param_bool("textToPath");
1230 void
1231 PrintPS::init(void)
1233     /* SVG in */
1234     (void) Inkscape::Extension::build_from_mem(
1235         "<inkscape-extension>\n"
1236         "<name>Postscript Print</name>\n"
1237         "<id>" SP_MODULE_KEY_PRINT_PS "</id>\n"
1238         "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1239         "<param name=\"resolution\" type=\"string\">72</param>\n"
1240         "<param name=\"destination\" type=\"string\"></param>\n"
1241         "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1242         "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1243         "<print/>\n"
1244         "</inkscape-extension>", new PrintPS());
1248 }  /* namespace Internal */
1249 }  /* namespace Extension */
1250 }  /* namespace Inkscape */
1252 /* End of GNU GPL code */
1255 /*
1256   Local Variables:
1257   mode:c++
1258   c-file-style:"stroustrup"
1259   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1260   indent-tabs-mode:nil
1261   fill-column:99
1262   End:
1263 */
1264 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :